Spaces:
Sleeping
Sleeping
Create cohereAPI.py
Browse files- cohereAPI.py +32 -0
cohereAPI.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cohere
|
| 2 |
+
import asyncio
|
| 3 |
+
|
| 4 |
+
async def send_message(system_message, user_message, conversation_history, api_key):
|
| 5 |
+
# Initialize the Cohere client
|
| 6 |
+
co = cohere.ClientV2(api_key)
|
| 7 |
+
|
| 8 |
+
# Prepare all messages including history
|
| 9 |
+
messages = [{"role": "system", "content": system_message}]
|
| 10 |
+
messages.extend(conversation_history)
|
| 11 |
+
messages.append({"role": "user", "content": user_message})
|
| 12 |
+
|
| 13 |
+
# Send request to Cohere asynchronously
|
| 14 |
+
# Since the Cohere Python client may not have native async support,
|
| 15 |
+
# we'll run it in a thread pool to avoid blocking
|
| 16 |
+
loop = asyncio.get_event_loop()
|
| 17 |
+
response = await loop.run_in_executor(
|
| 18 |
+
None,
|
| 19 |
+
lambda: co.chat(
|
| 20 |
+
model="command-a-03-2025",
|
| 21 |
+
messages=messages
|
| 22 |
+
)
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
# Get the response
|
| 26 |
+
response_content = response.message.content[0].text
|
| 27 |
+
|
| 28 |
+
# Update conversation history for this session
|
| 29 |
+
conversation_history.append({"role": "user", "content": user_message})
|
| 30 |
+
conversation_history.append({"role": "assistant", "content": response_content})
|
| 31 |
+
|
| 32 |
+
return response_content, conversation_history
|