Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
from huggingface_hub import InferenceClient
|
4 |
+
|
5 |
+
# Constants
|
6 |
+
DEFAULT_MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.1"
|
7 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
8 |
+
|
9 |
+
def chat_with_model(system_prompt, user_message, max_tokens=500, model_id=""):
|
10 |
+
"""
|
11 |
+
Generate a chat completion using the specified or default Mistral model.
|
12 |
+
|
13 |
+
Args:
|
14 |
+
system_prompt (str): The system prompt to set the context.
|
15 |
+
user_message (str): The user's input message.
|
16 |
+
max_tokens (int): Maximum number of tokens to generate.
|
17 |
+
model_id (str): The model ID to use. If empty, uses the default model.
|
18 |
+
|
19 |
+
Returns:
|
20 |
+
str: The model's response.
|
21 |
+
"""
|
22 |
+
model_id = model_id.strip() if model_id else DEFAULT_MODEL_ID
|
23 |
+
|
24 |
+
client = InferenceClient(model_id, token=HF_TOKEN)
|
25 |
+
|
26 |
+
messages = [
|
27 |
+
{"role": "system", "content": system_prompt},
|
28 |
+
{"role": "user", "content": user_message}
|
29 |
+
]
|
30 |
+
|
31 |
+
response = ""
|
32 |
+
try:
|
33 |
+
for message in client.chat_completion(
|
34 |
+
messages=messages,
|
35 |
+
max_tokens=max_tokens,
|
36 |
+
stream=True
|
37 |
+
):
|
38 |
+
response += message.choices[0].delta.content or ""
|
39 |
+
except Exception as e:
|
40 |
+
response = f"Error: {str(e)}"
|
41 |
+
|
42 |
+
return response
|
43 |
+
|
44 |
+
def create_gradio_interface():
|
45 |
+
"""Create and configure the Gradio interface."""
|
46 |
+
return gr.Interface(
|
47 |
+
fn=chat_with_model,
|
48 |
+
inputs=[
|
49 |
+
gr.Textbox(label="System Prompt", placeholder="Enter the system prompt here..."),
|
50 |
+
gr.Textbox(label="User Message", placeholder="Ask a question..."),
|
51 |
+
gr.Slider(minimum=50, maximum=1000, value=500, step=50, label="Max Tokens"),
|
52 |
+
gr.Textbox(label="Model ID", placeholder=f"Enter model ID (default: {DEFAULT_MODEL_ID})")
|
53 |
+
],
|
54 |
+
outputs=gr.Textbox(label="Response"),
|
55 |
+
title="Mistral Chatbot",
|
56 |
+
description="Chat with Mistral model using your own system prompts and choose your model.",
|
57 |
+
examples=[
|
58 |
+
["You are a helpful AI assistant.", "What is the capital of France?", 500, ""],
|
59 |
+
["You are an expert in Python programming.", "Explain list comprehensions.", 500, ""]
|
60 |
+
]
|
61 |
+
)
|
62 |
+
|
63 |
+
if __name__ == "__main__":
|
64 |
+
iface = create_gradio_interface()
|
65 |
+
iface.launch(show_api=True, share=False, show_error=True)
|