|
| 1 | +import json |
| 2 | +import time |
| 3 | +import inspect |
| 4 | +from typing import Any, Callable, Dict, List, Optional, Tuple |
| 5 | +import urllib.request |
| 6 | +import urllib.error |
| 7 | + |
| 8 | +JSONSchema = Dict[str, Any] |
| 9 | + |
| 10 | + |
| 11 | +def _pytype_to_json_schema(py_type: Any) -> str: |
| 12 | + if py_type in (int, float): |
| 13 | + return "number" |
| 14 | + if py_type is bool: |
| 15 | + return "boolean" |
| 16 | + if py_type is str: |
| 17 | + return "string" |
| 18 | + return "string" |
| 19 | + |
| 20 | + |
| 21 | +class ChatGPTModel: |
| 22 | + """ |
| 23 | + OpenAI / OpenRouter compatible chat client with tool-calling loop. |
| 24 | + """ |
| 25 | + |
| 26 | + def __init__( |
| 27 | + self, |
| 28 | + model: str, |
| 29 | + api_key: str, |
| 30 | + url: str, |
| 31 | + max_iterations: int = 6, |
| 32 | + sleep_between: float = 0.2, |
| 33 | + ): |
| 34 | + self.model = model |
| 35 | + self.api_key = api_key |
| 36 | + self.url = url |
| 37 | + self.max_iterations = max_iterations |
| 38 | + self.sleep_between = sleep_between |
| 39 | + |
| 40 | + self._functions: Dict[str, Callable[..., Any]] = {} |
| 41 | + self._tools: List[Dict[str, Any]] = [] |
| 42 | + |
| 43 | + # ------------------------------------------------------------------ TOOLS |
| 44 | + |
| 45 | + def tool(self, fn: Optional[Callable] = None, *, name: Optional[str] = None): |
| 46 | + def register(f: Callable): |
| 47 | + tool_name = name or f.__name__ |
| 48 | + self._functions[tool_name] = f |
| 49 | + self._rebuild_tools() |
| 50 | + return f |
| 51 | + |
| 52 | + return register(fn) if fn else register |
| 53 | + |
| 54 | + def _rebuild_tools(self): |
| 55 | + tools = [] |
| 56 | + |
| 57 | + for name, fn in self._functions.items(): |
| 58 | + sig = inspect.signature(fn) |
| 59 | + properties = {} |
| 60 | + required = [] |
| 61 | + |
| 62 | + for pname, p in sig.parameters.items(): |
| 63 | + ann = p.annotation if p.annotation is not inspect._empty else str |
| 64 | + properties[pname] = {"type": _pytype_to_json_schema(ann)} |
| 65 | + if p.default is inspect._empty: |
| 66 | + required.append(pname) |
| 67 | + |
| 68 | + tools.append( |
| 69 | + { |
| 70 | + "type": "function", |
| 71 | + "function": { |
| 72 | + "name": name, |
| 73 | + "description": fn.__doc__ or "", |
| 74 | + "parameters": { |
| 75 | + "type": "object", |
| 76 | + "properties": properties, |
| 77 | + "required": required, |
| 78 | + }, |
| 79 | + }, |
| 80 | + } |
| 81 | + ) |
| 82 | + |
| 83 | + self._tools = tools |
| 84 | + |
| 85 | + # ------------------------------------------------------------- HTTP CALL |
| 86 | + |
| 87 | + def _post(self, payload: Dict[str, Any]) -> Dict[str, Any]: |
| 88 | + data = json.dumps(payload).encode() |
| 89 | + headers = { |
| 90 | + "Content-Type": "application/json", |
| 91 | + "Authorization": f"Bearer {self.api_key}", |
| 92 | + } |
| 93 | + |
| 94 | + req = urllib.request.Request(self.url, data=data, headers=headers, method="POST") |
| 95 | + |
| 96 | + try: |
| 97 | + with urllib.request.urlopen(req, timeout=30) as resp: |
| 98 | + return json.loads(resp.read().decode()) |
| 99 | + except urllib.error.HTTPError as e: |
| 100 | + body = e.read().decode(errors="ignore") |
| 101 | + raise RuntimeError(f"HTTP {e.code}: {body}") |
| 102 | + except Exception as e: |
| 103 | + raise RuntimeError(f"Network error: {e}") |
| 104 | + |
| 105 | + # --------------------------------------------------------- TOOL EXECUTION |
| 106 | + |
| 107 | + def _execute_tool(self, name: str, args: Dict[str, Any]) -> Dict[str, Any]: |
| 108 | + fn = self._functions.get(name) |
| 109 | + if not fn: |
| 110 | + return {"error": f"Tool '{name}' not registered"} |
| 111 | + |
| 112 | + try: |
| 113 | + return fn(**args) |
| 114 | + except Exception as e: |
| 115 | + return {"error": str(e)} |
| 116 | + |
| 117 | + # ------------------------------------------------------------------ CALL |
| 118 | + |
| 119 | + def call(self, history: List[str], prompt: str, role: str = "user") -> Optional[str]: |
| 120 | + self._rebuild_tools() |
| 121 | + |
| 122 | + messages = [{"role": "user", "content": h} for h in history] |
| 123 | + messages.append({"role": role, "content": prompt}) |
| 124 | + |
| 125 | + for _ in range(self.max_iterations): |
| 126 | + payload = { |
| 127 | + "model": self.model, |
| 128 | + "messages": messages, |
| 129 | + } |
| 130 | + |
| 131 | + if self._tools: |
| 132 | + payload["tools"] = self._tools |
| 133 | + payload["tool_choice"] = "auto" |
| 134 | + |
| 135 | + resp = self._post(payload) |
| 136 | + choices = resp.get("choices", []) |
| 137 | + |
| 138 | + for choice in choices: |
| 139 | + msg = choice.get("message", {}) |
| 140 | + |
| 141 | + # ---------------- TOOL CALL |
| 142 | + if "tool_calls" in msg: |
| 143 | + for call in msg["tool_calls"]: |
| 144 | + name = call["function"]["name"] |
| 145 | + args = json.loads(call["function"].get("arguments", "{}")) |
| 146 | + |
| 147 | + result = self._execute_tool(name, args) |
| 148 | + |
| 149 | + messages.append(msg) |
| 150 | + messages.append( |
| 151 | + { |
| 152 | + "role": "tool", |
| 153 | + "tool_call_id": call["id"], |
| 154 | + "content": json.dumps(result), |
| 155 | + } |
| 156 | + ) |
| 157 | + |
| 158 | + time.sleep(self.sleep_between) |
| 159 | + break |
| 160 | + else: |
| 161 | + continue |
| 162 | + break |
| 163 | + |
| 164 | + # ---------------- FINAL TEXT |
| 165 | + content = msg.get("content") |
| 166 | + if content: |
| 167 | + messages.append(msg) |
| 168 | + return content |
| 169 | + |
| 170 | + return None |
| 171 | + |
| 172 | + return None |
| 173 | + |
| 174 | + |
| 175 | +__all__ = ["ChatGPTModel"] |
0 commit comments