from __future__ import annotations import argparse import json import os from dataclasses import asdict, dataclass from typing import Any, Callable from openai import OpenAI MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-chat") BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com") MAX_TURNS = 6 MAX_TOOL_CALLS = 12 @dataclass class Usage: prompt_tokens: int = 0 completion_tokens: int = 0 total_tokens: int = 0 def add(self, response_usage: Any) -> None: if response_usage is None: return self.prompt_tokens += int(response_usage.prompt_tokens or 0) self.completion_tokens += int(response_usage.completion_tokens or 0) self.total_tokens += int(response_usage.total_tokens or 0) @dataclass class ToolEvent: turn: int call_id: str name: str arguments: dict[str, Any] result: Any def calculate(operation: str, a: float, b: float) -> dict[str, float | str]: """执行受控的四则运算,不接受任意表达式。""" if operation == "add": value = a + b elif operation == "subtract": value = a - b elif operation == "multiply": value = a * b elif operation == "divide": if b == 0: raise ValueError("除数不能为零") value = a / b else: raise ValueError(f"不支持的运算:{operation}") return {"operation": operation, "a": a, "b": b, "value": value} ORDERS = { "1001": { "order_id": "1001", "customer": "华东智造", "status": "paid", "amount": 12999.0, }, "1002": { "order_id": "1002", "customer": "南方零售", "status": "pending", "amount": 4999.0, }, } def get_order_summary(order_id: str) -> dict[str, Any]: """读取演示订单,不连接外部数据库。""" if order_id not in ORDERS: return {"order_id": order_id, "found": False} return {"found": True, **ORDERS[order_id]} TOOL_HANDLERS: dict[str, Callable[..., Any]] = { "calculate": calculate, "get_order_summary": get_order_summary, } TOOLS = [ { "type": "function", "function": { "name": "calculate", "description": "执行两个数字之间的四则运算。所有数值计算都必须调用此工具。", "parameters": { "type": "object", "properties": { "operation": { "type": "string", "enum": ["add", "subtract", "multiply", "divide"], }, "a": {"type": "number"}, "b": {"type": "number"}, }, "required": ["operation", "a", "b"], "additionalProperties": False, }, }, }, { "type": "function", "function": { "name": "get_order_summary", "description": "查询单个演示订单的客户、状态和金额。每次只能查询一个订单编号。", "parameters": { "type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"], "additionalProperties": False, }, }, }, ] SYSTEM_PROMPT = """你是一个中文订单业务助手。 查询订单必须调用 get_order_summary,任何数值计算必须调用 calculate。 当计算依赖订单金额时,先查询订单,再把真实金额传给 calculate。 用户同时查询多个订单时,为每个订单分别调用 get_order_summary。 不要编造工具结果,不要执行工具列表之外的操作。 拿到全部工具结果后,用简洁中文回答,并说明调用过的工具。""" def create_client() -> OpenAI: """创建 DeepSeek OpenAI 兼容客户端,密钥只从环境变量读取。""" api_key = os.getenv("DEEPSEEK_API_KEY") if not api_key: raise RuntimeError("未设置 DEEPSEEK_API_KEY 环境变量") return OpenAI(api_key=api_key, base_url=BASE_URL, timeout=30.0, max_retries=2) def validate_arguments(name: str, arguments: Any) -> dict[str, Any]: """在调用本地函数前再次校验参数,不能只相信模型生成的 JSON。""" if not isinstance(arguments, dict): raise ValueError("工具参数必须是JSON对象") if name == "calculate": required = {"operation", "a", "b"} if set(arguments) != required: raise ValueError("calculate 参数不完整或包含未知字段") if arguments["operation"] not in {"add", "subtract", "multiply", "divide"}: raise ValueError("calculate operation 不合法") if not all( isinstance(arguments[key], (int, float)) and not isinstance(arguments[key], bool) for key in ("a", "b") ): raise ValueError("calculate 的 a、b 必须是数字") elif name == "get_order_summary": if set(arguments) != {"order_id"} or not isinstance(arguments["order_id"], str): raise ValueError("get_order_summary 参数不合法") if not arguments["order_id"].isdigit() or len(arguments["order_id"]) > 20: raise ValueError("order_id 必须是长度不超过20的数字字符串") else: raise ValueError(f"不允许调用工具:{name}") return arguments def dispatch_tool(name: str, raw_arguments: str | dict[str, Any]) -> tuple[dict[str, Any], Any]: """按白名单分派工具,并把异常转换为稳定的工具结果。""" try: arguments = json.loads(raw_arguments) if isinstance(raw_arguments, str) else raw_arguments arguments = validate_arguments(name, arguments) result = TOOL_HANDLERS[name](**arguments) return arguments, {"ok": True, "data": result} except (json.JSONDecodeError, TypeError, ValueError, KeyError) as exc: return {}, {"ok": False, "error": str(exc)} def run_agent(question: str, client: OpenAI | None = None) -> dict[str, Any]: """运行可审计的手动工具调用循环。""" active_client = client or create_client() messages: list[dict[str, Any]] = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": question}, ] events: list[ToolEvent] = [] usage = Usage() for turn in range(1, MAX_TURNS + 1): response = active_client.chat.completions.create( model=MODEL, messages=messages, tools=TOOLS, tool_choice="auto", temperature=0, ) usage.add(getattr(response, "usage", None)) message = response.choices[0].message messages.append(message.model_dump(exclude_none=True)) if not message.tool_calls: return { "question": question, "answer": message.content or "模型没有返回文本。", "tool_events": [asdict(event) for event in events], "turns": turn, "usage": asdict(usage), "model": MODEL, } if len(events) + len(message.tool_calls) > MAX_TOOL_CALLS: raise RuntimeError(f"工具调用超过 {MAX_TOOL_CALLS} 次,已停止") for tool_call in message.tool_calls: arguments, result = dispatch_tool( tool_call.function.name, tool_call.function.arguments, ) events.append( ToolEvent( turn=turn, call_id=tool_call.id, name=tool_call.function.name, arguments=arguments, result=result, ) ) messages.append( { "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result, ensure_ascii=False), } ) raise RuntimeError(f"对话超过 {MAX_TURNS} 轮,已停止") def main() -> None: parser = argparse.ArgumentParser(description="DeepSeek OpenAI兼容工具调用示例") parser.add_argument("question", help="要交给Agent的问题") args = parser.parse_args() print(json.dumps(run_agent(args.question), ensure_ascii=False, indent=2)) if __name__ == "__main__": main()