umar-30 commited on
Commit
bcbe151
·
verified ·
1 Parent(s): 409c8b3

update the code

Browse files
Files changed (1) hide show
  1. app/agent/task_agent.py +13 -67
app/agent/task_agent.py CHANGED
@@ -1,7 +1,8 @@
1
- Task Agent implementation using OpenAI API directly.
 
2
 
3
  Provides an AI agent that maps natural language to MCP tools for task management.
4
- Uses OpenAI's gpt-4o-mini for reliable function calling/tool use support.
5
  """
6
  import json
7
  from typing import Any
@@ -11,7 +12,6 @@ Task Agent implementation using OpenAI API directly.
11
  from .prompts import SYSTEM_PROMPT
12
  from ..mcp import tools as mcp_tools
13
 
14
- # Tool definitions for OpenAI function calling
15
  TOOLS = [
16
  {
17
  "type": "function",
@@ -21,7 +21,7 @@ Task Agent implementation using OpenAI API directly.
21
  "parameters": {
22
  "type": "object",
23
  "properties": {
24
- "user_id": {"type": "string", "description": "The user's unique identifier"},
25
  "title": {"type": "string", "description": "The task title"},
26
  "description": {"type": "string", "description": "Optional task description"}
27
  },
@@ -37,7 +37,7 @@ Task Agent implementation using OpenAI API directly.
37
  "parameters": {
38
  "type": "object",
39
  "properties": {
40
- "user_id": {"type": "string", "description": "The user's unique identifier"}
41
  },
42
  "required": ["user_id"]
43
  }
@@ -47,13 +47,12 @@ Task Agent implementation using OpenAI API directly.
47
  "type": "function",
48
  "function": {
49
  "name": "complete_task",
50
- "description": "Mark a task as completed. IMPORTANT: You must first call list_tasks to get the task UUID, then use that UUID here.",
51
  "parameters": {
52
  "type": "object",
53
  "properties": {
54
- "user_id": {"type": "string", "description": "The user's unique identifier"},
55
- "task_id": {"type": "string", "description": "The task's UUID (e.g., 'd18627f4-73ff-4450-943e-451c24962de0'). NOT the task
56
- title!"}
57
  },
58
  "required": ["user_id", "task_id"]
59
  }
@@ -63,12 +62,12 @@ Task Agent implementation using OpenAI API directly.
63
  "type": "function",
64
  "function": {
65
  "name": "update_task",
66
- "description": "Update a task's title or description",
67
  "parameters": {
68
  "type": "object",
69
  "properties": {
70
- "user_id": {"type": "string", "description": "The user's unique identifier"},
71
- "task_id": {"type": "string", "description": "The task's unique identifier (UUID)"},
72
  "title": {"type": "string", "description": "New task title"},
73
  "description": {"type": "string", "description": "New task description"}
74
  },
@@ -84,8 +83,8 @@ Task Agent implementation using OpenAI API directly.
84
  "parameters": {
85
  "type": "object",
86
  "properties": {
87
- "user_id": {"type": "string", "description": "The user's unique identifier"},
88
- "task_id": {"type": "string", "description": "The task's unique identifier (UUID)"}
89
  },
90
  "required": ["user_id", "task_id"]
91
  }
@@ -95,7 +94,6 @@ Task Agent implementation using OpenAI API directly.
95
 
96
 
97
  def execute_tool(name: str, arguments: dict) -> Any:
98
- """Execute a tool by name with given arguments."""
99
  if name == "add_task":
100
  return mcp_tools.add_task(
101
  arguments["user_id"],
@@ -120,27 +118,13 @@ Task Agent implementation using OpenAI API directly.
120
 
121
 
122
  class TaskAgent:
123
- """
124
- AI agent for task management via natural language.
125
- Uses OpenAI API directly for reliable tool/function calling support.
126
- """
127
-
128
  def __init__(self, model: str | None = None):
129
- """
130
- Initialize the TaskAgent.
131
-
132
- Args:
133
- model: Model to use (default: gpt-4o-mini)
134
- """
135
  from ..config import get_settings
136
  settings = get_settings()
137
-
138
- # Use OpenAI directly for reliable tool use support
139
  self.client = AsyncOpenAI(
140
  api_key=settings.openai_api_key,
141
  base_url=settings.openai_base_url,
142
  )
143
- # Use gpt-4o-mini for fast, reliable tool calling
144
  self.model = model or "gpt-4o-mini"
145
 
146
  async def run(
@@ -149,76 +133,42 @@ Task Agent implementation using OpenAI API directly.
149
  user_id: str,
150
  context: dict[str, Any] | None = None
151
  ) -> dict[str, Any]:
152
- """
153
- Process a user message and return the agent's response.
154
-
155
- Args:
156
- message: User's natural language message
157
- user_id: User identifier for tool calls
158
- context: Optional additional context
159
-
160
- Returns:
161
- dict with response and tool_calls
162
- """
163
- # Build messages
164
  messages = [
165
  {"role": "system", "content": SYSTEM_PROMPT + f"\n\nCurrent User ID: {user_id}"}
166
  ]
167
-
168
- # Add conversation history if available
169
  if context and context.get("conversation_history"):
170
  for msg in context["conversation_history"][-5:]:
171
  messages.append({
172
  "role": msg["role"],
173
  "content": msg["content"]
174
  })
175
-
176
- # Add current user message
177
  messages.append({"role": "user", "content": message})
178
-
179
  tool_calls_made = []
180
-
181
- # Call the model
182
  response = await self.client.chat.completions.create(
183
  model=self.model,
184
  messages=messages,
185
  tools=TOOLS,
186
  tool_choice="auto",
187
  )
188
-
189
  assistant_message = response.choices[0].message
190
-
191
- # Handle tool calls if any
192
  while assistant_message.tool_calls:
193
- # Add assistant message with tool calls
194
  messages.append(assistant_message)
195
-
196
- # Execute each tool call
197
  for tool_call in assistant_message.tool_calls:
198
  function_name = tool_call.function.name
199
  arguments = json.loads(tool_call.function.arguments)
200
-
201
- # Inject user_id if not provided
202
  if "user_id" not in arguments:
203
  arguments["user_id"] = user_id
204
-
205
- # Execute the tool
206
  result = execute_tool(function_name, arguments)
207
-
208
  tool_calls_made.append({
209
  "name": function_name,
210
  "arguments": arguments,
211
  "result": result
212
  })
213
-
214
- # Add tool result to messages
215
  messages.append({
216
  "role": "tool",
217
  "tool_call_id": tool_call.id,
218
  "content": json.dumps(result)
219
  })
220
-
221
- # Get next response
222
  response = await self.client.chat.completions.create(
223
  model=self.model,
224
  messages=messages,
@@ -226,10 +176,7 @@ Task Agent implementation using OpenAI API directly.
226
  tool_choice="auto",
227
  )
228
  assistant_message = response.choices[0].message
229
-
230
- # Get final text response
231
  response_text = assistant_message.content or ""
232
-
233
  return {
234
  "response": response_text,
235
  "tool_calls": tool_calls_made
@@ -237,5 +184,4 @@ Task Agent implementation using OpenAI API directly.
237
 
238
 
239
  def create_task_agent(model: str | None = None) -> TaskAgent:
240
- """Factory function to create a TaskAgent instance."""
241
  return TaskAgent(model=model)
 
1
+ """
2
+ Task Agent implementation using OpenAI API directly.
3
 
4
  Provides an AI agent that maps natural language to MCP tools for task management.
5
+ Uses OpenAI gpt-4o-mini for reliable function calling/tool use support.
6
  """
7
  import json
8
  from typing import Any
 
12
  from .prompts import SYSTEM_PROMPT
13
  from ..mcp import tools as mcp_tools
14
 
 
15
  TOOLS = [
16
  {
17
  "type": "function",
 
21
  "parameters": {
22
  "type": "object",
23
  "properties": {
24
+ "user_id": {"type": "string", "description": "The user unique identifier"},
25
  "title": {"type": "string", "description": "The task title"},
26
  "description": {"type": "string", "description": "Optional task description"}
27
  },
 
37
  "parameters": {
38
  "type": "object",
39
  "properties": {
40
+ "user_id": {"type": "string", "description": "The user unique identifier"}
41
  },
42
  "required": ["user_id"]
43
  }
 
47
  "type": "function",
48
  "function": {
49
  "name": "complete_task",
50
+ "description": "Mark a task as completed. You must first call list_tasks to get the task UUID.",
51
  "parameters": {
52
  "type": "object",
53
  "properties": {
54
+ "user_id": {"type": "string", "description": "The user unique identifier"},
55
+ "task_id": {"type": "string", "description": "The task UUID. NOT the task title!"}
 
56
  },
57
  "required": ["user_id", "task_id"]
58
  }
 
62
  "type": "function",
63
  "function": {
64
  "name": "update_task",
65
+ "description": "Update a task title or description",
66
  "parameters": {
67
  "type": "object",
68
  "properties": {
69
+ "user_id": {"type": "string", "description": "The user unique identifier"},
70
+ "task_id": {"type": "string", "description": "The task unique identifier (UUID)"},
71
  "title": {"type": "string", "description": "New task title"},
72
  "description": {"type": "string", "description": "New task description"}
73
  },
 
83
  "parameters": {
84
  "type": "object",
85
  "properties": {
86
+ "user_id": {"type": "string", "description": "The user unique identifier"},
87
+ "task_id": {"type": "string", "description": "The task unique identifier (UUID)"}
88
  },
89
  "required": ["user_id", "task_id"]
90
  }
 
94
 
95
 
96
  def execute_tool(name: str, arguments: dict) -> Any:
 
97
  if name == "add_task":
98
  return mcp_tools.add_task(
99
  arguments["user_id"],
 
118
 
119
 
120
  class TaskAgent:
 
 
 
 
 
121
  def __init__(self, model: str | None = None):
 
 
 
 
 
 
122
  from ..config import get_settings
123
  settings = get_settings()
 
 
124
  self.client = AsyncOpenAI(
125
  api_key=settings.openai_api_key,
126
  base_url=settings.openai_base_url,
127
  )
 
128
  self.model = model or "gpt-4o-mini"
129
 
130
  async def run(
 
133
  user_id: str,
134
  context: dict[str, Any] | None = None
135
  ) -> dict[str, Any]:
 
 
 
 
 
 
 
 
 
 
 
 
136
  messages = [
137
  {"role": "system", "content": SYSTEM_PROMPT + f"\n\nCurrent User ID: {user_id}"}
138
  ]
 
 
139
  if context and context.get("conversation_history"):
140
  for msg in context["conversation_history"][-5:]:
141
  messages.append({
142
  "role": msg["role"],
143
  "content": msg["content"]
144
  })
 
 
145
  messages.append({"role": "user", "content": message})
 
146
  tool_calls_made = []
 
 
147
  response = await self.client.chat.completions.create(
148
  model=self.model,
149
  messages=messages,
150
  tools=TOOLS,
151
  tool_choice="auto",
152
  )
 
153
  assistant_message = response.choices[0].message
 
 
154
  while assistant_message.tool_calls:
 
155
  messages.append(assistant_message)
 
 
156
  for tool_call in assistant_message.tool_calls:
157
  function_name = tool_call.function.name
158
  arguments = json.loads(tool_call.function.arguments)
 
 
159
  if "user_id" not in arguments:
160
  arguments["user_id"] = user_id
 
 
161
  result = execute_tool(function_name, arguments)
 
162
  tool_calls_made.append({
163
  "name": function_name,
164
  "arguments": arguments,
165
  "result": result
166
  })
 
 
167
  messages.append({
168
  "role": "tool",
169
  "tool_call_id": tool_call.id,
170
  "content": json.dumps(result)
171
  })
 
 
172
  response = await self.client.chat.completions.create(
173
  model=self.model,
174
  messages=messages,
 
176
  tool_choice="auto",
177
  )
178
  assistant_message = response.choices[0].message
 
 
179
  response_text = assistant_message.content or ""
 
180
  return {
181
  "response": response_text,
182
  "tool_calls": tool_calls_made
 
184
 
185
 
186
  def create_task_agent(model: str | None = None) -> TaskAgent:
 
187
  return TaskAgent(model=model)