-
Notifications
You must be signed in to change notification settings - Fork 334
/
Copy pathaugmented_llm_deepseek.py
292 lines (253 loc) · 11.1 KB
/
augmented_llm_deepseek.py
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
from typing import List
from mcp_agent.workflows.llm.augmented_llm_openai import OpenAIAugmentedLLM,mcp_content_to_openai_content
import json
from loguru import logger
from openai import OpenAI
from openai.types.chat import (
ChatCompletionToolParam,
ChatCompletionToolMessageParam,
ChatCompletionMessage,
ChatCompletionMessageParam,
ChatCompletionSystemMessageParam,
ChatCompletionUserMessageParam,
)
from mcp.types import (
CallToolRequestParams,
CallToolRequest,
CallToolResult,
TextContent,
)
from mcp_agent.workflows.llm.augmented_llm import (
RequestParams,
)
class DeepSeekAugmentedLLM(OpenAIAugmentedLLM):
def get_messages(self, message, params: RequestParams | None = None):
messages: List[ChatCompletionMessageParam] = []
system_prompt = self.instruction or params.systemPrompt
if system_prompt:
messages.append(
ChatCompletionSystemMessageParam(role="system", content=system_prompt)
)
if params.use_history:
messages.extend(self.history.get())
if isinstance(message, str):
messages.append(
ChatCompletionUserMessageParam(role="user", content=message)
)
elif isinstance(message, list):
messages.extend(message)
else:
messages.append(message)
return messages
async def generate(self, message, request_params: RequestParams | None = None):
"""
Process a query using an LLM and available tools.
The default implementation uses OpenAI's ChatCompletion as the LLM.
Override this method to use a different LLM.
"""
config = self.context.config
params = self.get_request_params(request_params)
openai_client = OpenAI(
api_key=config.openai.api_key, base_url=config.openai.base_url
)
i = 0
try:
while i< request_params.max_iterations:
try:
if not hasattr(self,'tool_response'):
tool_response = await self.aggregator.list_tools()
self.tool_response = tool_response
break
except Exception as e:
logger.error(f"Error: {e}")
i+=1
available_tools: List[ChatCompletionToolParam] = [
ChatCompletionToolParam(
type="function",
function={
"name": tool.name,
"description": tool.description,
"parameters": tool.inputSchema,
"strict": True,
},
)
for tool in self.tool_response.tools
]
if not available_tools:
available_tools = None
responses: List[ChatCompletionMessage] = []
model = await self.select_model(params)
base_messages = self.get_messages(message, params)
messages = base_messages
for i in range(params.max_iterations):
arguments = {
"model": model,
"messages": messages,
"stop": params.stopSequences,
"tools": available_tools,
}
if self._reasoning:
arguments = {
**arguments,
"max_completion_tokens": params.maxTokens,
"reasoning_effort": self._reasoning_effort,
}
else:
arguments = {**arguments, "max_tokens": params.maxTokens}
# if available_tools:
# arguments["parallel_tool_calls"] = params.parallel_tool_calls
if params.metadata:
arguments = {**arguments, **params.metadata}
self.logger.debug(f"{arguments}")
self._log_chat_progress(chat_turn=len(messages) // 2, model=model)
executor_result = await self.executor.execute(
openai_client.chat.completions.create, **arguments
)
response = executor_result[0]
self.logger.debug(
"OpenAI ChatCompletion response:",
data=response,
)
if isinstance(response, BaseException):
self.logger.error(f"Error: {response}")
break
if not response.choices or len(response.choices) == 0:
# No response from the model, we're done
break
# TODO: saqadri - handle multiple choices for more complex interactions.
# Keeping it simple for now because multiple choices will also complicate memory management
choice = response.choices[0]
message = choice.message
responses.append(message)
converted_message = self.convert_message_to_message_param(
message, name=self.name
)
messages.append(converted_message)
if (
choice.finish_reason in ["tool_calls", "function_call"]
and message.tool_calls
):
# Execute all tool calls in parallel.
tool_tasks = [
self.execute_tool_call(tool_call)
for tool_call in message.tool_calls
]
# Wait for all tool calls to complete.
tool_results = await self.executor.execute(*tool_tasks, return_exceptions=True)
self.logger.debug(
f"Iteration {i}: Tool call results: {str(tool_results) if tool_results else 'None'}"
)
# Add results (success or failure) to messages.
# Use zip to correlate results back to original tool calls for proper error reporting
for tool_call, result in zip(message.tool_calls, tool_results):
tool_call_id = tool_call.id
if isinstance(result, BaseException):
error_message = f"Error executing tool {tool_call.function.name}: {str(result)}"
self.logger.error(
f"Warning: Error during tool execution for call {tool_call_id}: {result}. Appending error message to history."
)
# Append error message to messages
messages.append(
ChatCompletionToolMessageParam(
role="tool",
tool_call_id=tool_call_id,
content=error_message,
)
)
elif result is not None:
# Append successful tool result to messages
messages.append(result)
# If result is None, do nothing (tool produced no message content)
elif choice.finish_reason == "length":
# We have reached the max tokens limit
self.logger.debug(
f"Iteration {i}: Stopping because finish_reason is 'length'"
)
# TODO: saqadri - would be useful to return the reason for stopping to the caller
break
elif choice.finish_reason == "content_filter":
# The response was filtered by the content filter
self.logger.debug(
f"Iteration {i}: Stopping because finish_reason is 'content_filter'"
)
# TODO: saqadri - would be useful to return the reason for stopping to the caller
break
elif choice.finish_reason == "stop":
self.logger.debug(
f"Iteration {i}: Stopping because finish_reason is 'stop'"
)
break
if params.use_history:
self.history.set(messages)
self._log_chat_finished(model=model)
finally:
try:
openai_client.close()
except Exception as e:
logger.error(f"Error closing OpenAI client: {e}")
return responses
async def execute_tool_call(
self,
tool_call: ChatCompletionToolParam,
) -> ChatCompletionToolMessageParam | None:
"""
Execute a single tool call and return the result message.
Returns None if there's no content to add to messages.
"""
tool_name = tool_call.function.name
tool_args_str = tool_call.function.arguments
tool_call_id = tool_call.id
tool_args = {}
try:
if tool_args_str:
tool_args = json.loads(tool_args_str)
except json.JSONDecodeError as e:
raise Exception(f"Error parsing tool call arguments for '{tool_name}': {str(e)}")
tool_call_request = CallToolRequest(
method="tools/call",
params=CallToolRequestParams(name=tool_name, arguments=tool_args),
)
result = await self.call_tool(
request=tool_call_request, tool_call_id=tool_call_id
)
if result.content:
return ChatCompletionToolMessageParam(
role="tool",
tool_call_id=tool_call_id,
content='\n'.join([mcp_content_to_openai_content(c)['text'] for c in result.content]),
)
return None
async def call_tool(
self,
request: CallToolRequest,
tool_call_id: str | None = None,
) -> CallToolResult:
"""Call a tool with the given parameters and optional ID"""
try:
preprocess = await self.pre_tool_call(
tool_call_id=tool_call_id,
request=request,
)
if isinstance(preprocess, bool):
if not preprocess:
return CallToolResult(
isError=True,
content=[
TextContent(
text=f"Error: Tool '{request.params.name}' was not allowed to run."
)
],
)
else:
request = preprocess
tool_name = request.params.name
tool_args = request.params.arguments
result = await self.aggregator.call_tool(tool_name, tool_args)
postprocess = await self.post_tool_call(
tool_call_id=tool_call_id, request=request, result=result
)
if isinstance(postprocess, CallToolResult):
result = postprocess
return result
except Exception as e:
raise Exception(f"Error executing tool '{request.params.name}': {str(e)}")