from __future__ import annotations import argparse import json import os import re from dataclasses import asdict, dataclass from pathlib import Path from typing import Any from urllib.error import HTTPError, URLError from urllib.parse import quote, urlencode, urlparse from urllib.request import Request, urlopen import jsonref from jsonschema import Draft202012Validator from openai import OpenAI MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-chat") BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com") MAX_TURNS = 8 MAX_TOOL_CALLS = 12 HTTP_TIMEOUT_SECONDS = 5.0 MAX_RESPONSE_BYTES = 128_000 HTTP_METHODS = {"get", "post", "put", "patch", "delete"} MUTATING_METHODS = {"POST", "PUT", "PATCH", "DELETE"} @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 Operation: operation_id: str method: str path: str parameters: list[dict[str, Any]] request_body_schema: dict[str, Any] | None tool_schema: dict[str, Any] @dataclass class ToolEvent: turn: int call_id: str name: str arguments: dict[str, Any] result: dict[str, Any] def load_openapi_spec(spec_path: str | Path) -> dict[str, Any]: """加载JSON规范并解析本地$ref,返回普通Python字典。""" path = Path(spec_path).resolve() with path.open("r", encoding="utf-8") as handle: resolved = jsonref.load( handle, base_uri=path.as_uri(), proxies=False, lazy_load=False, ) # 经过非代理模式解析后再做一次JSON往返,确保下游只接收普通类型。 return json.loads(json.dumps(resolved, ensure_ascii=False)) def _parameter_schema(parameter: dict[str, Any]) -> dict[str, Any]: schema = dict(parameter.get("schema") or {}) if parameter.get("description") and "description" not in schema: schema["description"] = parameter["description"] return schema def build_tools_and_operations( spec: dict[str, Any], ) -> tuple[list[dict[str, Any]], dict[str, Operation]]: """把允许的OpenAPI操作转换为DeepSeek tools,并建立白名单路由。""" tools: list[dict[str, Any]] = [] operations: dict[str, Operation] = {} for route_path, path_item in (spec.get("paths") or {}).items(): path_parameters = list(path_item.get("parameters") or []) for method, operation_spec in path_item.items(): if method.lower() not in HTTP_METHODS or not isinstance(operation_spec, dict): continue if operation_spec.get("x-agent-enabled") is not True: continue operation_id = str(operation_spec.get("operationId") or "").strip() if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{0,63}", operation_id): raise ValueError(f"operationId不合法:{operation_id or ''}") if operation_id in operations: raise ValueError(f"operationId重复:{operation_id}") parameters = path_parameters + list(operation_spec.get("parameters") or []) argument_properties: dict[str, Any] = {} argument_required: list[str] = [] if parameters: parameter_properties: dict[str, Any] = {} parameter_required: list[str] = [] for parameter in parameters: name = str(parameter.get("name") or "") if not name: raise ValueError(f"{operation_id}存在无名称参数") parameter_properties[name] = _parameter_schema(parameter) if parameter.get("required"): parameter_required.append(name) parameter_object: dict[str, Any] = { "type": "object", "properties": parameter_properties, "additionalProperties": False, } if parameter_required: parameter_object["required"] = parameter_required argument_properties["parameters"] = parameter_object if parameter_required: argument_required.append("parameters") request_body = operation_spec.get("requestBody") or {} request_body_schema = ( request_body.get("content", {}) .get("application/json", {}) .get("schema") ) if request_body_schema: argument_properties["requestBody"] = request_body_schema if request_body.get("required"): argument_required.append("requestBody") arguments_schema: dict[str, Any] = { "type": "object", "properties": argument_properties, "additionalProperties": False, } if argument_required: arguments_schema["required"] = argument_required description = str( operation_spec.get("description") or operation_spec.get("summary") or f"调用{method.upper()} {route_path}" ) tool = { "type": "function", "function": { "name": operation_id, "description": f"{description} HTTP {method.upper()} {route_path}", "parameters": arguments_schema, }, } operation = Operation( operation_id=operation_id, method=method.upper(), path=route_path, parameters=parameters, request_body_schema=request_body_schema, tool_schema=arguments_schema, ) tools.append(tool) operations[operation_id] = operation if not tools: raise ValueError("OpenAPI规范中没有允许Agent使用的操作") return tools, operations def create_client() -> OpenAI: """创建DeepSeek兼容客户端,密钥只从环境变量读取。""" 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) class OpenAPIExecutor: """按OpenAPI白名单验证参数并调用固定REST服务。""" def __init__( self, base_api_url: str, operations: dict[str, Operation], allow_mutations: bool = False, ) -> None: parsed = urlparse(base_api_url) if parsed.scheme not in {"http", "https"} or not parsed.hostname: raise ValueError("REST API地址必须是明确的http或https地址") self.base_api_url = base_api_url.rstrip("/") self.allowed_origin = (parsed.scheme, parsed.hostname, parsed.port) self.operations = operations self.allow_mutations = allow_mutations def _error(self, code: str, message: str) -> dict[str, Any]: return {"ok": False, "error": {"code": code, "message": message}} def execute( self, operation_id: str, raw_arguments: str | dict[str, Any] ) -> tuple[dict[str, Any], dict[str, Any]]: try: arguments = ( json.loads(raw_arguments) if isinstance(raw_arguments, str) else raw_arguments ) except json.JSONDecodeError as exc: return {}, self._error("invalid_json", str(exc)) if not isinstance(arguments, dict): return {}, self._error("invalid_arguments", "工具参数必须是JSON对象") operation = self.operations.get(operation_id) if not operation: return arguments, self._error("operation_not_allowed", f"不允许调用:{operation_id}") if operation.method in MUTATING_METHODS and not self.allow_mutations: return arguments, self._error( "mutation_not_authorized", f"{operation.method}操作需要应用程序显式授权", ) validation_errors = sorted( Draft202012Validator(operation.tool_schema).iter_errors(arguments), key=lambda item: list(item.path), ) if validation_errors: error = validation_errors[0] location = ".".join(str(part) for part in error.path) or "arguments" return arguments, self._error("schema_validation_failed", f"{location}: {error.message}") parameter_values = arguments.get("parameters", {}) route_path = operation.path query_values: dict[str, Any] = {} for parameter in operation.parameters: name = parameter["name"] value = parameter_values.get(name) if parameter.get("in") == "path": route_path = route_path.replace("{" + name + "}", quote(str(value), safe="")) elif parameter.get("in") == "query" and value is not None: query_values[name] = value url = f"{self.base_api_url}{route_path}" if query_values: url = f"{url}?{urlencode(query_values, doseq=True)}" parsed_url = urlparse(url) if (parsed_url.scheme, parsed_url.hostname, parsed_url.port) != self.allowed_origin: return arguments, self._error("origin_not_allowed", "REST请求越过允许的服务边界") body = None headers = {"Accept": "application/json"} if operation.request_body_schema is not None: body = json.dumps(arguments.get("requestBody"), ensure_ascii=False).encode("utf-8") headers["Content-Type"] = "application/json; charset=utf-8" request = Request(url, data=body, method=operation.method, headers=headers) try: with urlopen(request, timeout=HTTP_TIMEOUT_SECONDS) as response: raw_body = response.read(MAX_RESPONSE_BYTES + 1) if len(raw_body) > MAX_RESPONSE_BYTES: return arguments, self._error("response_too_large", "REST响应超过大小限制") response_data = json.loads(raw_body.decode("utf-8")) if raw_body else None return arguments, { "ok": True, "status": response.status, "operation": operation_id, "data": response_data, } except HTTPError as exc: raw_error = exc.read(MAX_RESPONSE_BYTES).decode("utf-8", errors="replace") try: detail: Any = json.loads(raw_error) except json.JSONDecodeError: detail = raw_error return arguments, self._error("http_error", f"HTTP {exc.code}: {detail}") except (URLError, TimeoutError, json.JSONDecodeError) as exc: return arguments, self._error("request_failed", str(exc)) SYSTEM_PROMPT = """你是中文活动管理助手。 只要用户请求涉及活动数据,就必须使用提供的工具,不能编造活动或编号。 创建活动后如果还要查询或删除该活动,必须先读取创建结果中的真实id,再发起下一次工具调用。 同一轮可以请求多个彼此独立的只读工具;存在数据依赖时必须按轮次串行调用。 工具能否执行由应用程序决定。工具返回错误时,向用户说明失败原因,不要虚构成功。 完成全部操作后,用简洁中文总结实际结果,并列出调用过的工具。""" def run_agent( instruction: str, spec_path: str | Path, base_api_url: str, allow_mutations: bool = False, client: OpenAI | None = None, ) -> dict[str, Any]: spec = load_openapi_spec(spec_path) tools, operations = build_tools_and_operations(spec) executor = OpenAPIExecutor(base_api_url, operations, allow_mutations=allow_mutations) active_client = client or create_client() messages: list[dict[str, Any]] = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": instruction}, ] 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 { "instruction": instruction, "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 = executor.execute( 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 OpenAPI REST Agent") parser.add_argument("instruction", help="要执行的中文活动管理指令") parser.add_argument( "--spec", default=str(Path(__file__).with_name("openapi_spec.json")), help="OpenAPI JSON文件", ) parser.add_argument( "--api-url", default=os.getenv("EVENTS_API_BASE_URL", "http://127.0.0.1:8765"), help="固定REST服务地址", ) parser.add_argument( "--allow-mutations", action="store_true", help="显式允许POST、PUT、PATCH和DELETE操作", ) args = parser.parse_args() result = run_agent( instruction=args.instruction, spec_path=args.spec, base_api_url=args.api_url, allow_mutations=args.allow_mutations, ) print(json.dumps(result, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()