|
| 1 | +import inspect |
| 2 | +import json |
1 | 3 | from abc import ABC, abstractmethod |
| 4 | +from typing import Any, Awaitable, Callable, Optional |
2 | 5 |
|
3 | 6 |
|
4 | 7 | class BaseAiHandler(ABC): |
@@ -26,3 +29,111 @@ async def chat_completion(self, model: str, system: str, user: str, temperature: |
26 | 29 | temperature (float): the temperature to use for the chat completion |
27 | 30 | """ |
28 | 31 | pass |
| 32 | + |
| 33 | + async def chat_completion_with_tools( |
| 34 | + self, |
| 35 | + model: str, |
| 36 | + system: str, |
| 37 | + user: str, |
| 38 | + tools: Optional[list[dict[str, Any]]] = None, |
| 39 | + tool_executor: Optional[Callable[[str, dict[str, Any]], Any | Awaitable[Any]]] = None, |
| 40 | + temperature: float = 0.2, |
| 41 | + img_path: str = None, |
| 42 | + max_tool_turns: int = 4, |
| 43 | + max_tool_output_chars: int = 12000, |
| 44 | + ): |
| 45 | + """ |
| 46 | + Run a structured tool-calling loop on top of plain chat completion. |
| 47 | +
|
| 48 | + The model is instructed to emit JSON tool requests in the form: |
| 49 | + {"type": "tool_call", "tool": "server.tool", "arguments": {...}} |
| 50 | + and to finish with: |
| 51 | + {"type": "final", "content": "..."} |
| 52 | + """ |
| 53 | + if not tools or tool_executor is None: |
| 54 | + return await self.chat_completion(model, system, user, temperature=temperature, img_path=img_path) |
| 55 | + |
| 56 | + tool_catalog_text = json.dumps(tools, indent=2, sort_keys=True) |
| 57 | + structured_system = ( |
| 58 | + f"{system}\n\n" |
| 59 | + f"Available MCP tools (JSON schema):\n{tool_catalog_text}\n\n" |
| 60 | + "When you need a tool, respond with a JSON object exactly in this shape:\n" |
| 61 | + '{"type":"tool_call","tool":"server.tool","arguments":{...}}\n' |
| 62 | + "When you are finished, respond with a JSON object exactly in this shape:\n" |
| 63 | + '{"type":"final","content":"..."}\n' |
| 64 | + "Do not wrap the JSON in markdown fences." |
| 65 | + ) |
| 66 | + |
| 67 | + current_user = user |
| 68 | + remaining_turns = max_tool_turns |
| 69 | + current_img_path = img_path |
| 70 | + |
| 71 | + while True: |
| 72 | + response_text, finish_reason = await self.chat_completion( |
| 73 | + model=model, |
| 74 | + system=structured_system, |
| 75 | + user=current_user, |
| 76 | + temperature=temperature, |
| 77 | + img_path=current_img_path, |
| 78 | + ) |
| 79 | + current_img_path = None |
| 80 | + |
| 81 | + parsed_response = self._parse_tool_or_final_response(response_text) |
| 82 | + if parsed_response is None: |
| 83 | + return response_text, finish_reason |
| 84 | + |
| 85 | + response_type = parsed_response.get("type", "final") |
| 86 | + if response_type == "final": |
| 87 | + return str(parsed_response.get("content", "")), finish_reason |
| 88 | + |
| 89 | + if response_type != "tool_call": |
| 90 | + return response_text, finish_reason |
| 91 | + |
| 92 | + if remaining_turns <= 0: |
| 93 | + raise ValueError("MCP tool orchestration exceeded the configured turn budget") |
| 94 | + |
| 95 | + tool_name = str(parsed_response.get("tool", "")).strip() |
| 96 | + arguments = parsed_response.get("arguments") or {} |
| 97 | + if not tool_name: |
| 98 | + raise ValueError("MCP tool orchestration returned an empty tool name") |
| 99 | + if not isinstance(arguments, dict): |
| 100 | + raise ValueError("MCP tool orchestration arguments must be a JSON object") |
| 101 | + |
| 102 | + tool_result = tool_executor(tool_name, arguments) |
| 103 | + if inspect.isawaitable(tool_result): |
| 104 | + tool_result = await tool_result |
| 105 | + |
| 106 | + tool_result_text = self._normalize_tool_result_text(tool_result, max_tool_output_chars) |
| 107 | + current_user = ( |
| 108 | + f"{user}\n\n" |
| 109 | + f"Previous assistant tool request:\n{response_text}\n\n" |
| 110 | + f"Tool result for {tool_name}:\n{tool_result_text}" |
| 111 | + ) |
| 112 | + remaining_turns -= 1 |
| 113 | + |
| 114 | + @staticmethod |
| 115 | + def _normalize_tool_result_text(tool_result: Any, max_tool_output_chars: int) -> str: |
| 116 | + if isinstance(tool_result, str): |
| 117 | + result_text = tool_result |
| 118 | + else: |
| 119 | + result_text = json.dumps(tool_result, indent=2, sort_keys=True, default=str) |
| 120 | + |
| 121 | + if len(result_text) > max_tool_output_chars: |
| 122 | + return result_text[: max_tool_output_chars - 20] + "\n[tool output truncated]" |
| 123 | + return result_text |
| 124 | + |
| 125 | + @staticmethod |
| 126 | + def _parse_tool_or_final_response(response_text: str) -> Optional[dict[str, Any]]: |
| 127 | + candidate = response_text.strip() |
| 128 | + if not candidate.startswith("{") or not candidate.endswith("}"): |
| 129 | + return None |
| 130 | + |
| 131 | + try: |
| 132 | + parsed = json.loads(candidate) |
| 133 | + except json.JSONDecodeError: |
| 134 | + return None |
| 135 | + |
| 136 | + if not isinstance(parsed, dict): |
| 137 | + return None |
| 138 | + |
| 139 | + return parsed |
0 commit comments