Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +54 -0
- requirements.txt +2 -0
app.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import cohere
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
co = cohere.ClientV2(os.getenv("COHERE_API_KEY"))
|
| 6 |
+
|
| 7 |
+
def chat(message, history, system_prompt):
|
| 8 |
+
messages = []
|
| 9 |
+
if system_prompt:
|
| 10 |
+
messages.append({"role": "system", "content": system_prompt})
|
| 11 |
+
for item in history:
|
| 12 |
+
messages.append({"role": item["role"], "content": item["content"]})
|
| 13 |
+
messages.append({"role": "user", "content": message})
|
| 14 |
+
|
| 15 |
+
stream = co.chat_stream(
|
| 16 |
+
model="command-a-03-2025",
|
| 17 |
+
messages=messages
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
response = ""
|
| 21 |
+
for event in stream:
|
| 22 |
+
if event.type == "content-delta":
|
| 23 |
+
response += event.delta.message.content.text
|
| 24 |
+
yield response
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
with gr.Blocks() as demo:
|
| 28 |
+
gr.Markdown("## Chatbot Cohere (Gradio)")
|
| 29 |
+
|
| 30 |
+
system_prompt = gr.Textbox(
|
| 31 |
+
value="Tu es un assistant utile.",
|
| 32 |
+
label="Prompt système"
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
chatbot = gr.Chatbot()
|
| 36 |
+
msg = gr.Textbox(label="Message")
|
| 37 |
+
|
| 38 |
+
def user_fn(message, history):
|
| 39 |
+
return "", history + [{"role": "user", "content": message}]
|
| 40 |
+
|
| 41 |
+
def bot_fn(history, system_prompt):
|
| 42 |
+
message = history[-1]["content"]
|
| 43 |
+
previous = history[:-1]
|
| 44 |
+
history = history + [{"role": "assistant", "content": ""}]
|
| 45 |
+
for chunk in chat(message, previous, system_prompt):
|
| 46 |
+
history[-1]["content"] = chunk
|
| 47 |
+
yield history
|
| 48 |
+
|
| 49 |
+
msg.submit(user_fn, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 50 |
+
bot_fn, [chatbot, system_prompt], chatbot
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
demo.queue()
|
| 54 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=5.0.0
|
| 2 |
+
cohere>=5.0.0
|