PD03 commited on
Commit
93dde6b
·
verified ·
1 Parent(s): ffbdc7d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -8
app.py CHANGED
@@ -58,17 +58,69 @@ class AIAssistant:
58
  async def initialize(self):
59
  self.available_tools = await self.mcp_client.list_tools()
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  async def process_message(self, user_message: str) -> Tuple[str, str]:
62
- try:
63
- response = self.openai_client.chat.completions.create(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  model="gpt-3.5-turbo",
65
- messages=[{"role": "user", "content": user_message}],
66
- temperature=0.7,
67
- max_tokens=1000
68
  )
69
- return response.choices[0].message.content, ""
70
- except Exception as e:
71
- return f"❌ Error: {str(e)}", ""
72
 
73
 
74
  # Globals
 
58
  async def initialize(self):
59
  self.available_tools = await self.mcp_client.list_tools()
60
 
61
+ def get_system_prompt(self) -> str:
62
+ tools_description = "\n".join([
63
+ f"- {tool['name']}: {tool['description']}"
64
+ for tool in self.available_tools
65
+ ])
66
+ return f"""You are an AI assistant with access to tools:
67
+ {tools_description}
68
+
69
+ Use these tools explicitly if user queries require external data.
70
+
71
+ Respond with 'CALL_TOOL: tool_name(parameter=value)' to invoke tools.
72
+ """
73
+
74
+ def extract_tool_calls(self, response: str) -> List[Dict[str, Any]]:
75
+ tool_calls = []
76
+ lines = response.split('\n')
77
+ for line in lines:
78
+ if line.startswith('CALL_TOOL:'):
79
+ tool_part = line[len('CALL_TOOL:'):].strip()
80
+ tool_name, args = tool_part.split('(', 1)
81
+ args = args.rstrip(')')
82
+ arg_dict = {}
83
+ for arg in args.split(','):
84
+ key, value = arg.split('=')
85
+ arg_dict[key.strip()] = value.strip().strip('"\'')
86
+ tool_calls.append({'name': tool_name.strip(), 'arguments': arg_dict})
87
+ return tool_calls
88
+
89
  async def process_message(self, user_message: str) -> Tuple[str, str]:
90
+ messages = [
91
+ {"role": "system", "content": self.get_system_prompt()},
92
+ {"role": "user", "content": user_message}
93
+ ]
94
+ response = self.openai_client.chat.completions.create(
95
+ model="gpt-3.5-turbo",
96
+ messages=messages,
97
+ temperature=0
98
+ )
99
+ ai_response = response.choices[0].message.content
100
+ tool_calls = self.extract_tool_calls(ai_response)
101
+
102
+ tool_info = ""
103
+ if tool_calls:
104
+ tool_results = []
105
+ for call in tool_calls:
106
+ result = await self.mcp_client.call_tool(call['name'], call['arguments'])
107
+ tool_results.append(result)
108
+ tool_info += f"Called {call['name']}: {result}\n"
109
+
110
+ # Let AI interpret the tool results
111
+ final_messages = messages + [
112
+ {"role": "assistant", "content": ai_response},
113
+ {"role": "user", "content": f"Tool results:\n{json.dumps(tool_results)}"}
114
+ ]
115
+
116
+ final_response = self.openai_client.chat.completions.create(
117
  model="gpt-3.5-turbo",
118
+ messages=final_messages,
119
+ temperature=0
 
120
  )
121
+ return final_response.choices[0].message.content, tool_info
122
+
123
+ return ai_response, ""
124
 
125
 
126
  # Globals