Spaces:
Sleeping
Sleeping
Update cohereAPI.py
Browse files- cohereAPI.py +36 -11
cohereAPI.py
CHANGED
@@ -1,7 +1,8 @@
|
|
1 |
import cohere
|
2 |
import asyncio
|
3 |
|
4 |
-
|
|
|
5 |
# Initialize the Cohere client
|
6 |
co = cohere.ClientV2(api_key)
|
7 |
|
@@ -10,16 +11,40 @@ async def send_message(system_message, user_message, conversation_history, api_k
|
|
10 |
messages.extend(conversation_history)
|
11 |
messages.append({"role": "user", "content": user_message})
|
12 |
|
13 |
-
# Send request to Cohere
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
)
|
24 |
|
25 |
# Get the response
|
|
|
1 |
import cohere
|
2 |
import asyncio
|
3 |
|
4 |
+
def send_message_stream(system_message, user_message, conversation_history, api_key, model_name="command-a-03-2025"):
|
5 |
+
"""Stream response from Cohere API"""
|
6 |
# Initialize the Cohere client
|
7 |
co = cohere.ClientV2(api_key)
|
8 |
|
|
|
11 |
messages.extend(conversation_history)
|
12 |
messages.append({"role": "user", "content": user_message})
|
13 |
|
14 |
+
# Send streaming request to Cohere
|
15 |
+
stream = co.chat_stream(
|
16 |
+
model=model_name,
|
17 |
+
messages=messages
|
18 |
+
)
|
19 |
+
|
20 |
+
# Collect full response for history
|
21 |
+
full_response = ""
|
22 |
+
|
23 |
+
# Yield chunks as they come
|
24 |
+
for chunk in stream:
|
25 |
+
if chunk.type == "content-delta":
|
26 |
+
text_chunk = chunk.delta.message.content.text
|
27 |
+
full_response += text_chunk
|
28 |
+
yield text_chunk
|
29 |
+
|
30 |
+
# Update conversation history after streaming is complete
|
31 |
+
conversation_history.append({"role": "user", "content": user_message})
|
32 |
+
conversation_history.append({"role": "assistant", "content": full_response})
|
33 |
+
|
34 |
+
def send_message(system_message, user_message, conversation_history, api_key, model_name="command-a-03-2025"):
|
35 |
+
"""Non-streaming version for backward compatibility"""
|
36 |
+
# Initialize the Cohere client
|
37 |
+
co = cohere.ClientV2(api_key)
|
38 |
+
|
39 |
+
# Prepare all messages including history
|
40 |
+
messages = [{"role": "system", "content": system_message}]
|
41 |
+
messages.extend(conversation_history)
|
42 |
+
messages.append({"role": "user", "content": user_message})
|
43 |
+
|
44 |
+
# Send request to Cohere synchronously
|
45 |
+
response = co.chat(
|
46 |
+
model=model_name,
|
47 |
+
messages=messages
|
48 |
)
|
49 |
|
50 |
# Get the response
|