|
| 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,149 @@ 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 ONLY a JSON object exactly in this shape:\n" |
| 61 | + '{"type":"tool_call","tool":"server.tool","arguments":{...}}\n' |
| 62 | + "Do not include a final answer in the same message as a tool call.\n" |
| 63 | + "When you are finished, respond with ONLY a JSON object exactly in this shape:\n" |
| 64 | + '{"type":"final","content":"..."}\n' |
| 65 | + "Do not wrap the JSON in markdown fences." |
| 66 | + ) |
| 67 | + |
| 68 | + conversation_history = [user] |
| 69 | + remaining_turns = max_tool_turns |
| 70 | + current_img_path = img_path |
| 71 | + |
| 72 | + while True: |
| 73 | + current_user = "\n\n".join(conversation_history) |
| 74 | + response_text, finish_reason = await self.chat_completion( |
| 75 | + model=model, |
| 76 | + system=structured_system, |
| 77 | + user=current_user, |
| 78 | + temperature=temperature, |
| 79 | + img_path=current_img_path, |
| 80 | + ) |
| 81 | + current_img_path = None |
| 82 | + |
| 83 | + parsed_response = self._parse_tool_or_final_response(response_text) |
| 84 | + if parsed_response is None: |
| 85 | + return response_text, finish_reason |
| 86 | + |
| 87 | + response_type = parsed_response.get("type", "final") |
| 88 | + if response_type == "final": |
| 89 | + return str(parsed_response.get("content", "")), finish_reason |
| 90 | + |
| 91 | + if response_type != "tool_call": |
| 92 | + return response_text, finish_reason |
| 93 | + |
| 94 | + if remaining_turns <= 0: |
| 95 | + raise ValueError("MCP tool orchestration exceeded the configured turn budget") |
| 96 | + |
| 97 | + tool_name = str(parsed_response.get("tool", "")).strip() |
| 98 | + arguments = parsed_response.get("arguments") or {} |
| 99 | + if not tool_name: |
| 100 | + raise ValueError("MCP tool orchestration returned an empty tool name") |
| 101 | + if not isinstance(arguments, dict): |
| 102 | + raise ValueError("MCP tool orchestration arguments must be a JSON object") |
| 103 | + |
| 104 | + tool_result = tool_executor(tool_name, arguments) |
| 105 | + if inspect.isawaitable(tool_result): |
| 106 | + tool_result = await tool_result |
| 107 | + |
| 108 | + tool_result_text = self._normalize_tool_result_text(tool_result, max_tool_output_chars) |
| 109 | + conversation_history.append(f"Previous assistant tool request:\n{response_text}") |
| 110 | + conversation_history.append(f"Tool result for {tool_name}:\n{tool_result_text}") |
| 111 | + remaining_turns -= 1 |
| 112 | + |
| 113 | + @staticmethod |
| 114 | + def _normalize_tool_result_text(tool_result: Any, max_tool_output_chars: int) -> str: |
| 115 | + if isinstance(tool_result, str): |
| 116 | + result_text = tool_result |
| 117 | + else: |
| 118 | + result_text = json.dumps(tool_result, indent=2, sort_keys=True, default=str) |
| 119 | + |
| 120 | + if len(result_text) > max_tool_output_chars: |
| 121 | + return result_text[: max_tool_output_chars - 20] + "\n[tool output truncated]" |
| 122 | + return result_text |
| 123 | + |
| 124 | + @staticmethod |
| 125 | + def _parse_tool_or_final_response(response_text: str) -> Optional[dict[str, Any]]: |
| 126 | + candidate = response_text.strip() |
| 127 | + if not candidate: |
| 128 | + return None |
| 129 | + |
| 130 | + for json_candidate in BaseAiHandler._iter_json_object_candidates(candidate): |
| 131 | + try: |
| 132 | + parsed = json.loads(json_candidate) |
| 133 | + except json.JSONDecodeError: |
| 134 | + continue |
| 135 | + |
| 136 | + if isinstance(parsed, dict): |
| 137 | + response_type = parsed.get("type") |
| 138 | + if response_type in {"tool_call", "final"}: |
| 139 | + return parsed |
| 140 | + |
| 141 | + return None |
| 142 | + |
| 143 | + @staticmethod |
| 144 | + def _iter_json_object_candidates(text: str) -> list[str]: |
| 145 | + candidates: list[str] = [] |
| 146 | + depth = 0 |
| 147 | + start_index: Optional[int] = None |
| 148 | + in_string = False |
| 149 | + is_escaped = False |
| 150 | + |
| 151 | + for index, char in enumerate(text): |
| 152 | + if in_string: |
| 153 | + if is_escaped: |
| 154 | + is_escaped = False |
| 155 | + elif char == "\\": |
| 156 | + is_escaped = True |
| 157 | + elif char == '"': |
| 158 | + in_string = False |
| 159 | + continue |
| 160 | + |
| 161 | + if char == '"': |
| 162 | + in_string = True |
| 163 | + continue |
| 164 | + |
| 165 | + if char == "{": |
| 166 | + if depth == 0: |
| 167 | + start_index = index |
| 168 | + depth += 1 |
| 169 | + continue |
| 170 | + |
| 171 | + if char == "}" and depth > 0: |
| 172 | + depth -= 1 |
| 173 | + if depth == 0 and start_index is not None: |
| 174 | + candidates.append(text[start_index : index + 1]) |
| 175 | + start_index = None |
| 176 | + |
| 177 | + return candidates |
0 commit comments