智能体 MCP 调用流

"""
简单的智能体 Demo
使用阿里千问判断并调用对应的 MCP 工具
"""
import os
from openai import OpenAI
# 阿里千问 API 配置(兼容 OpenAI 格式)
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY", "sk-xxxxxxxxxxxxxxxxxxxx"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)
# 定义工具(模拟 MCP 工具)
TOOLS = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称,如:北京、上海"}
},
"required": ["city"]
}
}
},
{
"type": "function",
"function": {
"name": "get_time",
"description": "获取当前时间",
"parameters": {"type": "object", "properties": {}}
}
},
{
"type": "function",
"function": {
"name": "calculate",
"description": "进行数学计算",
"parameters": {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "数学表达式,如:1+2*3"}
},
"required": ["expression"]
}
}
}
]
# 工具实现(写死的数据)
def get_weather(city: str) -> str:
weather_data = {
"北京": "晴,5°C,北风3级",
"上海": "多云,12°C,东风2级",
"广州": "阴,20°C,南风1级",
}
return weather_data.get(city, f"暂不支持查询 {city} 的天气")
def get_time() -> str:
from datetime import datetime
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def calculate(expression: str) -> str:
try:
return str(eval(expression))
except:
return "计算出错"
# 工具调用映射
TOOL_FUNCTIONS = {
"get_weather": get_weather,
"get_time": get_time,
"calculate": calculate,
}
def run_agent(user_input: str):
"""运行智能体"""
print(f"\n用户: {user_input}")
# 1. 调用千问,让它判断使用哪个工具
response = client.chat.completions.create(
model="qwen-plus",
messages=[
{"role": "system", "content": "你是一个智能助手,根据用户需求调用合适的工具。"},
{"role": "user", "content": user_input}
],
tools=TOOLS,
tool_choice="auto"
)
msg = response.choices[0].message
# 2. 如果模型决定调用工具
if msg.tool_calls:
tool_call = msg.tool_calls[0]
func_name = tool_call.function.name
args = eval(tool_call.function.arguments) if tool_call.function.arguments else {}
print(f"智能体决定调用: {func_name}({args})")
# 3. 执行工具
result = TOOL_FUNCTIONS[func_name](**args)
print(f"工具返回: {result}")
# 4. 把结果返回给模型生成最终回复
final_response = client.chat.completions.create(
model="qwen-plus",
messages=[
{"role": "system", "content": "你是一个智能助手"},
{"role": "user", "content": user_input},
msg,
{"role": "tool", "tool_call_id": tool_call.id, "content": result}
]
)
print(f"智能体: {final_response.choices[0].message.content}")
else:
# 不需要工具,直接回复
print(f"智能体: {msg.content}")
if __name__ == "__main__":
# 测试几个场景
run_agent("北京天气怎么样?")
run_agent("现在几点了?")
run_agent("帮我算一下 123 * 456")
run_agent("你好")
结果:
用户: 北京天气怎么样?
智能体决定调用: get_weather({'city': '北京'})
工具返回: 晴,5°C,北风3级
智能体: 今天北京天气晴朗,气温为5°C,有北风3级。建议外出时注意保暖,适当增添衣物。
用户: 现在几点了?
智能体决定调用: get_time({})
工具返回: 2025-12-30 11:27:43
智能体: 现在是2025年12月30日,星期二,上午11点27分。
用户: 帮我算一下 123 * 456
智能体决定调用: calculate({'expression': '123*456'})
工具返回: 56088
智能体: 123 × 456 = 56088
用户: 你好
智能体: 你好!有什么我可以帮你的吗?
浙公网安备 33010602011771号