File size: 7,291 Bytes
310260a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | """
Cohere Agent Service Module
This module provides the CohereAgentService class that uses Cohere API for chat.
"""
from typing import List, Dict, Any
import json
import time
import cohere
from ..config import settings
from ..tools.mcp_server import mcp_server
from ..tools import (
get_list_tasks_definition,
get_create_task_definition,
get_mark_complete_definition,
get_update_task_definition,
get_delete_task_definition,
get_get_task_definition
)
from ..database import engine
class CohereAgentService:
"""
Cohere Agent Service for processing conversational task management requests.
"""
def __init__(self, user_id: int):
"""
Initialize CohereAgentService for a specific user.
Args:
user_id: Authenticated user ID for data scoping
"""
self.user_id = user_id
self.client = cohere.Client(api_key=settings.COHERE_API_KEY)
self.model = settings.COHERE_MODEL
self.mcp_context = mcp_server.create_context(user_id=user_id)
def create_user_scoped_tools(self) -> List[Dict[str, Any]]:
"""
Create user-scoped tool definitions for Cohere function calling.
Converts OpenAI-style tool definitions to Cohere format.
"""
openai_tools = [
get_list_tasks_definition(),
get_create_task_definition(),
get_mark_complete_definition(),
get_update_task_definition(),
get_delete_task_definition(),
get_get_task_definition()
]
# Convert OpenAI format to Cohere format
cohere_tools = []
for tool in openai_tools:
func = tool["function"]
cohere_tool = {
"name": func["name"],
"description": func["description"],
"parameter_definitions": {}
}
# Convert parameters
if "parameters" in func and "properties" in func["parameters"]:
for param_name, param_info in func["parameters"]["properties"].items():
cohere_tool["parameter_definitions"][param_name] = {
"description": param_info.get("description", ""),
"type": param_info.get("type", "string"),
"required": param_name in func["parameters"].get("required", [])
}
cohere_tools.append(cohere_tool)
return cohere_tools
async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
"""
Execute a tool with the given arguments.
"""
try:
# Get the tool handler from MCP server
tool_handler = mcp_server.get_tool(tool_name)
if not tool_handler:
return {"error": f"Tool '{tool_name}' not found"}
# Execute with user context
result = await tool_handler(self.mcp_context, **arguments)
return result
except Exception as e:
return {"error": str(e)}
async def process_message(
self,
message: str,
conversation_history: List[Dict[str, str]]
) -> Dict[str, Any]:
"""
Process a user message using Cohere API.
"""
try:
# Get tools
tools = self.create_user_scoped_tools()
# Convert conversation history to Cohere format
chat_history = []
for msg in conversation_history:
if msg["role"] == "user":
chat_history.append({
"role": "USER",
"message": msg["content"]
})
elif msg["role"] == "assistant":
chat_history.append({
"role": "CHATBOT",
"message": msg["content"]
})
# System message (preamble in Cohere)
preamble = """You are a helpful task management assistant for KIro Todo application.
Your role is to help users manage their tasks through natural language conversation. You have access to tools for:
- Listing tasks
- Creating new tasks
- Updating tasks
- Deleting tasks
- Marking tasks as complete/incomplete
Be friendly, concise, and helpful. Always confirm actions clearly."""
# Call Cohere API with tools
response = self.client.chat(
model=self.model,
message=message,
chat_history=chat_history,
tools=tools,
preamble=preamble,
temperature=0.7
)
executed_tool_calls = []
# Check if model wants to use tools
if response.tool_calls:
# Execute each tool call
for tool_call in response.tool_calls:
tool_name = tool_call.name
tool_args = tool_call.parameters
# Execute tool
start_time = time.time()
tool_result = await self.execute_tool(tool_name, tool_args)
duration_ms = int((time.time() - start_time) * 1000)
executed_tool_calls.append({
"tool": tool_name,
"parameters": tool_args,
"result": tool_result,
"duration_ms": duration_ms
})
# Make second call with tool results
tool_results = [
{
"call": {
"name": tc["tool"],
"parameters": tc["parameters"]
},
"outputs": [tc["result"]]
}
for tc in executed_tool_calls
]
final_response = self.client.chat(
model=self.model,
message=message,
chat_history=chat_history,
tools=tools,
tool_results=tool_results,
preamble=preamble,
temperature=0.7
)
return {
"content": final_response.text,
"tool_calls": executed_tool_calls if executed_tool_calls else None,
"model": self.model,
"finish_reason": "complete"
}
else:
# No tool calls
return {
"content": response.text,
"tool_calls": None,
"model": self.model,
"finish_reason": "complete"
}
except Exception as e:
print(f"Error processing message with Cohere: {str(e)}")
raise
def format_conversation_history(
self,
messages: List[Any]
) -> List[Dict[str, str]]:
"""
Format database messages for Cohere API.
"""
formatted = []
for msg in messages:
formatted.append({
"role": msg.role.value,
"content": msg.content
})
return formatted
|