Datasets:
Download code/evaluation-code/ent400-a06a1576/tools/evaluation/providers.py from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 31.7 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/ent400-a06a1576/tools/evaluation/providers.py
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/evaluation-code/ent400-a06a1576/tools/evaluation/providers.py
-
curl -L -o providers.py https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/ent400-a06a1576/tools/evaluation/providers.py
31.7 kB
| """Model API clients over plain HTTP (standard library only). | |
| One request shape in, one response shape out, so every model is called the | |
| same way regardless of vendor: | |
| request = {'system': str|None, 'parts': [part, ...], 'max_tokens': int, | |
| 'temperature': float, 'seed': int|None} | |
| part = {'type': 'text', 'text': str} | |
| | {'type': 'image', 'path': str, 'mime': 'image/jpeg'} | |
| | {'type': 'video', 'path': str, 'mime': 'video/mp4', | |
| 'frames': [image part, ...] | None, 'fps': float|None} | |
| response = {'text': str, 'usage': {...}, 'raw': dict, 'latency_s': float} | |
| Protocols: | |
| - ``openai``: Chat Completions. Covers OpenAI itself and every compatible | |
| server: vLLM / SGLang / LMDeploy deployments of open models, DashScope | |
| (Qwen API), OpenRouter, Zhipu and similar gateways. Video parts are sent as | |
| ``video_url`` (vLLM, DashScope) when ``video_style='video_url'``, as a list | |
| of frames inside one ``video`` item (DashScope Qwen-VL) with | |
| ``video_style='frame_list'``, or expanded to frames otherwise. | |
| - ``gemini``: Google Generative Language ``generateContent`` (the REST API | |
| behind ``google.generativeai`` / ``google-genai``). Videos go inline up to | |
| ``inline_limit_bytes`` and through the Files API above it. | |
| - ``anthropic``: Messages API. No video input; video parts must be expanded to | |
| frames by the caller. | |
| - ``codex``: text-only blind answers through the ``codex exec`` CLI (its own login, no key variable). | |
| - ``mock``: deterministic offline echo used by tests and dry runs. | |
| SDK protocols (install the corresponding package with pip; imported lazily): | |
| - ``openai_sdk``: ``openai.OpenAI(base_url=..., api_key=...)`` then | |
| ``client.chat.completions.create``. Same message content as ``openai``, so | |
| it serves GPT through a gateway, DashScope and vLLM alike. | |
| - ``google_genai``: ``google.generativeai.GenerativeModel(model) | |
| .generate_content(parts)``. Images go inline; a video file is uploaded with | |
| ``genai.upload_file`` and waited on until ACTIVE. | |
| Each endpoint names its own key variable (``api_key_env``), so every model can | |
| carry a separate key. Keys are read from the environment, never from config | |
| files, and never written to outputs. | |
| """ | |
| import base64 | |
| import json | |
| import mimetypes | |
| import os | |
| import random | |
| import shutil | |
| import subprocess | |
| import tempfile | |
| import threading | |
| import time | |
| import urllib.error | |
| import urllib.parse | |
| import urllib.request | |
| from pathlib import Path | |
| PROTOCOLS = ('openai', 'openai_sdk', 'gemini', 'google_genai', 'anthropic', 'codex', 'mock') | |
| RETRY_STATUS = {408, 409, 425, 429, 500, 502, 503, 504, 529} | |
| def _reasoning(message): | |
| """Thinking text of a chat completion: ``reasoning_content`` (DashScope, older vLLM) or | |
| ``reasoning`` (vLLM 0.32 reasoning parsers).""" | |
| return message.get('reasoning_content') or message.get('reasoning') | |
| class ProviderError(RuntimeError): | |
| def __init__(self, message, status=None, body=None, retryable=False): | |
| super().__init__(message) | |
| self.status, self.body, self.retryable = status, body, retryable | |
| def _b64(path): | |
| return base64.b64encode(Path(path).read_bytes()).decode('ascii') | |
| def _mime(part, default): | |
| return part.get('mime') or mimetypes.guess_type(part['path'])[0] or default | |
| def _post(url, payload, headers, timeout, data=None): | |
| body = data if data is not None else json.dumps(payload).encode() | |
| req = urllib.request.Request(url, data=body, method='POST', | |
| headers={'Content-Type': 'application/json', **headers}) | |
| try: | |
| with urllib.request.urlopen(req, timeout=timeout) as resp: | |
| return json.loads(resp.read().decode()), dict(resp.headers) | |
| except urllib.error.HTTPError as exc: | |
| text = exc.read().decode(errors='replace')[:4000] | |
| raise ProviderError(f'HTTP {exc.code}: {text[:300]}', exc.code, text, | |
| exc.code in RETRY_STATUS) from None | |
| except (urllib.error.URLError, TimeoutError, ConnectionError) as exc: | |
| raise ProviderError(f'network error: {exc}', retryable=True) from None | |
| def _get(url, headers, timeout): | |
| req = urllib.request.Request(url, headers=headers) | |
| try: | |
| with urllib.request.urlopen(req, timeout=timeout) as resp: | |
| return json.loads(resp.read().decode()) | |
| except urllib.error.HTTPError as exc: | |
| text = exc.read().decode(errors='replace')[:4000] | |
| raise ProviderError(f'HTTP {exc.code}: {text[:300]}', exc.code, text, | |
| exc.code in RETRY_STATUS) from None | |
| except (urllib.error.URLError, TimeoutError, ConnectionError) as exc: | |
| raise ProviderError(f'network error: {exc}', retryable=True) from None | |
| def expand_video(parts): | |
| """Replace video parts by their frames; error when a video has none.""" | |
| out = [] | |
| for part in parts: | |
| if part['type'] != 'video': | |
| out.append(part) | |
| elif part.get('frames'): | |
| out.extend(part['frames']) | |
| else: | |
| raise ProviderError('this protocol cannot read encoded video; send frames') | |
| return out | |
| class Client: | |
| """Endpoint config keys: protocol, model, base_url, api_key_env, timeout_s, | |
| max_retries, retry_status, extra (merged into the request body), headers, and protocol | |
| specific options documented on each builder. | |
| ``retry_status`` (list of HTTP codes) narrows retries to those codes; timeouts, network | |
| errors and other statuses then fail at once, so ``timeout_s`` bounds every item. Used for | |
| a proxy that cuts long requests after a fixed time (10-27): retry 429s, never re-send a request it already | |
| cut (504). | |
| ``api_key_env`` may be a list of variable names (11-09): requests take the keys in turn, so a gateway that | |
| limits each key spreads the load. HTTP 429 (rate limit) does not use up ``max_retries``: the request waits | |
| and tries again on the next key, backing off up to 60 s per wait, for at most ``rate_limit_wait_s`` seconds | |
| in all (default 1800); after that the 429 is raised like any other error.""" | |
| def __init__(self, config): | |
| if config.get('protocol') not in PROTOCOLS: | |
| raise ValueError(f"protocol must be one of {PROTOCOLS}") | |
| self.config = dict(config) | |
| self.protocol = config['protocol'] | |
| self.model = config.get('model', 'mock') | |
| self.timeout = float(config.get('timeout_s', 300)) | |
| self.retries = int(config.get('max_retries', 4)) | |
| retry_status = config.get('retry_status') | |
| self.retry_status = set(retry_status) if retry_status is not None else None | |
| key_env = config.get('api_key_env') | |
| names = [key_env] if isinstance(key_env, str) else list(key_env or []) | |
| self.keys = [os.environ.get(n, '') for n in names] | |
| for n, k in zip(names, self.keys): | |
| if not k and self.protocol != 'mock': | |
| raise ValueError(f'environment variable {n} is not set') | |
| if self.protocol == 'google_genai' and len(self.keys) > 1: # genai.configure holds one key for the whole process | |
| raise ValueError('google_genai cannot rotate keys; list several keys with protocol gemini (HTTP) instead') | |
| self.rate_limit_wait = float(config.get('rate_limit_wait_s', 1800)) | |
| self._local, self._lock, self._turn = threading.local(), threading.Lock(), 0 | |
| def key(self): | |
| """Key for the request this thread is sending (the first key outside generate).""" | |
| return getattr(self._local, 'key', None) or (self.keys[0] if self.keys else '') | |
| def _next_key(self): | |
| if len(self.keys) > 1: | |
| with self._lock: | |
| self._local.key, self._turn = self.keys[self._turn % len(self.keys)], self._turn + 1 | |
| def describe(self): | |
| """Public, credential-free description stored with every result.""" | |
| keep = ('protocol', 'model', 'base_url', 'video_style', 'extra', 'image_detail', 'note', | |
| 'max_tokens_field', 'send_seed', 'send_temperature', 'fixed_temperature', 'family', | |
| 'max_images', 'timeout_s', 'max_retries', 'retry_status', 'effort') | |
| out = {k: self.config[k] for k in keep if k in self.config} | |
| if len(self.keys) > 1: # only when several, so single-key run.json files still resume | |
| out['api_keys'] = len(self.keys) | |
| if 'rate_limit_wait_s' in self.config: | |
| out['rate_limit_wait_s'] = self.config['rate_limit_wait_s'] | |
| return out | |
| def native_video(self): | |
| """Whether encoded video files are sent as video (else expanded to frames).""" | |
| if self.protocol in ('gemini', 'google_genai'): | |
| return True | |
| if self.protocol in ('openai', 'openai_sdk'): | |
| return self.config.get('video_style') in ('video_url', 'file') | |
| return False | |
| def count_images(self, request): | |
| """Images this endpoint will actually send for ``request``.""" | |
| n = 0 | |
| for part in request['parts']: | |
| if part['type'] == 'image': | |
| n += 1 | |
| elif part['type'] == 'video' and not (part.get('path') and self.native_video()): | |
| n += len(part.get('frames') or []) | |
| return n | |
| def generate(self, request): | |
| cap = self.config.get('max_images') | |
| if cap is not None and self.count_images(request) > cap: | |
| raise ProviderError(f'request has {self.count_images(request)} images; endpoint limit is {cap}') | |
| attempt, waited, limited = 0, 0.0, 0 | |
| while True: | |
| self._next_key() | |
| start = time.monotonic() | |
| try: | |
| result = getattr(self, f'_{self.protocol}')(request) | |
| result['latency_s'] = round(time.monotonic() - start, 3) | |
| result['attempts'] = attempt + 1 | |
| if limited: | |
| result['rate_limited'] = {'times': limited, 'waited_s': round(waited, 1)} | |
| has_video = any(p['type'] == 'video' and p.get('path') for p in request['parts']) | |
| result['video_input'] = ('native' if self.native_video() else 'frames') if has_video else None | |
| return result | |
| except ProviderError as exc: | |
| if exc.status == 429 and waited < self.rate_limit_wait: | |
| pause = min(60.0, 5.0 * 2 ** min(limited, 4)) * (0.5 + random.random()) | |
| pause = min(pause, self.rate_limit_wait - waited) | |
| time.sleep(pause) | |
| waited, limited = waited + pause, limited + 1 | |
| continue | |
| retryable = (exc.retryable if self.retry_status is None | |
| else exc.status is not None and exc.status in self.retry_status) | |
| if not retryable or attempt >= self.retries: | |
| raise | |
| time.sleep(min(60.0, 2.0 ** attempt + random.random())) | |
| attempt += 1 | |
| def _temperature(self, request): | |
| """``fixed_temperature`` overrides the request; ``send_temperature: false`` omits it.""" | |
| if 'fixed_temperature' in self.config: | |
| return self.config['fixed_temperature'] | |
| if not self.config.get('send_temperature', True): | |
| return None | |
| return request.get('temperature') | |
| # -- OpenAI-compatible ------------------------------------------------- | |
| def _openai_content(self, parts): | |
| style = self.config.get('video_style', 'frames') | |
| detail = self.config.get('image_detail') | |
| content = [] | |
| for part in parts: | |
| if part['type'] == 'text': | |
| content.append({'type': 'text', 'text': part['text']}) | |
| elif part['type'] == 'image': | |
| url = {'url': f"data:{_mime(part, 'image/jpeg')};base64,{_b64(part['path'])}"} | |
| if detail: | |
| url['detail'] = detail | |
| content.append({'type': 'image_url', 'image_url': url}) | |
| elif part['type'] == 'video' and style == 'video_url' and part.get('path'): | |
| content.append({'type': 'video_url', 'video_url': { | |
| 'url': f"data:{_mime(part, 'video/mp4')};base64,{_b64(part['path'])}"}}) | |
| elif part['type'] == 'video' and style == 'file' and part.get('path'): | |
| content.append({'type': 'file', 'file': { | |
| 'file_data': f"data:{_mime(part, 'video/mp4')};base64,{_b64(part['path'])}", | |
| 'filename': Path(part['path']).name}}) | |
| elif part['type'] == 'video' and style == 'frame_list' and part.get('frames'): | |
| content.append({'type': 'video', 'video': [ | |
| f"data:{_mime(f, 'image/jpeg')};base64,{_b64(f['path'])}" for f in part['frames']]}) | |
| else: | |
| content.extend(self._openai_content(expand_video([part]))) | |
| return content | |
| def _openai(self, request): | |
| base = self.config.get('base_url', 'https://api.openai.com/v1').rstrip('/') | |
| messages = [] | |
| if request.get('system'): | |
| messages.append({'role': 'system', 'content': request['system']}) | |
| messages.append({'role': 'user', 'content': self._openai_content(request['parts'])}) | |
| payload = {'model': self.model, 'messages': messages} | |
| token_field = self.config.get('max_tokens_field', 'max_tokens') | |
| payload[token_field] = request.get('max_tokens', 1024) | |
| temperature = self._temperature(request) | |
| if temperature is not None: | |
| payload['temperature'] = temperature | |
| if request.get('seed') is not None and self.config.get('send_seed', True): | |
| payload['seed'] = request['seed'] | |
| payload.update(self.config.get('extra', {})) | |
| headers = {**self.config.get('headers', {})} | |
| if self.key: | |
| headers['Authorization'] = f'Bearer {self.key}' | |
| data, _ = _post(f'{base}/chat/completions', payload, headers, self.timeout) | |
| return _chat_result(data) | |
| # -- OpenAI SDK ---------------------------------------------------------- | |
| def _openai_sdk(self, request): | |
| sdks = self.__dict__.setdefault('_sdks', {}) # one client per key, so a rotated key reaches the request | |
| if self.key not in sdks: | |
| try: | |
| import openai | |
| except ImportError: | |
| raise ProviderError('openai package missing; pip install openai') from None | |
| self._sdk_mod = openai | |
| sdks[self.key] = openai.OpenAI(base_url=self.config.get('base_url'), api_key=self.key or 'not-needed', | |
| timeout=self.timeout, max_retries=0, | |
| default_headers=self.config.get('headers') or None) | |
| sdk = sdks[self.key] | |
| messages = [] | |
| if request.get('system'): | |
| messages.append({'role': 'system', 'content': request['system']}) | |
| messages.append({'role': 'user', 'content': self._openai_content(request['parts'])}) | |
| kwargs = {'model': self.model, 'messages': messages, | |
| self.config.get('max_tokens_field', 'max_tokens'): request.get('max_tokens', 1024)} | |
| temperature = self._temperature(request) | |
| if temperature is not None: | |
| kwargs['temperature'] = temperature | |
| if request.get('seed') is not None and self.config.get('send_seed', True): | |
| kwargs['seed'] = request['seed'] | |
| extra = self.config.get('extra') or {} | |
| if extra: | |
| kwargs['extra_body'] = extra | |
| err = self._sdk_mod | |
| try: | |
| completion = sdk.chat.completions.create(**kwargs) | |
| except (err.RateLimitError, err.APITimeoutError, err.APIConnectionError, err.InternalServerError) as exc: | |
| raise ProviderError(f'{type(exc).__name__}: {exc}', getattr(exc, 'status_code', None), | |
| retryable=True) from None | |
| except err.APIStatusError as exc: | |
| raise ProviderError(f'HTTP {exc.status_code}: {str(exc)[:300]}', exc.status_code, | |
| retryable=exc.status_code in RETRY_STATUS) from None | |
| return _chat_result(completion.model_dump()) | |
| # -- google.generativeai SDK ---------------------------------------------- | |
| def _google_genai(self, request): | |
| if not hasattr(self, '_genai'): | |
| try: | |
| import warnings | |
| with warnings.catch_warnings(): | |
| warnings.simplefilter('ignore', FutureWarning) | |
| import google.generativeai as genai | |
| except ImportError: | |
| raise ProviderError('google-generativeai missing; pip install google-generativeai') from None | |
| # REST honours the request timeout; the default gRPC transport can | |
| # hang without error when the Google endpoint is unreachable. | |
| options = {'api_key': self.key, 'transport': self.config.get('transport', 'rest')} | |
| if self.config.get('base_url'): | |
| options['client_options'] = {'api_endpoint': self.config['base_url']} | |
| genai.configure(**options) | |
| # The SDK's REST session does not pass request timeouts to the TCP | |
| # connect; bound it process-wide so unreachable endpoints fail. | |
| import socket | |
| if socket.getdefaulttimeout() is None: | |
| socket.setdefaulttimeout(self.timeout) | |
| self._genai = genai | |
| genai = self._genai | |
| contents = [] | |
| for part in request['parts']: | |
| if part['type'] == 'text': | |
| contents.append(part['text']) | |
| elif part['type'] == 'image': | |
| contents.append({'mime_type': _mime(part, 'image/jpeg'), 'data': Path(part['path']).read_bytes()}) | |
| elif part['type'] == 'video' and part.get('path'): | |
| contents.append(self._genai_upload(part)) | |
| else: | |
| for frame in expand_video([part]): | |
| contents.append({'mime_type': _mime(frame, 'image/jpeg'), | |
| 'data': Path(frame['path']).read_bytes()}) | |
| generation = {'max_output_tokens': request.get('max_tokens', 1024)} | |
| if request.get('temperature') is not None: | |
| generation['temperature'] = request['temperature'] | |
| generation.update(self.config.get('extra', {}).get('generation_config', {})) | |
| model = genai.GenerativeModel(self.model, system_instruction=request.get('system') or None) | |
| try: | |
| response = model.generate_content(contents, generation_config=generation, | |
| request_options={'timeout': self.timeout, 'retry': None}) | |
| except Exception as exc: # google.api_core exceptions vary by transport | |
| code = getattr(exc, 'code', None) | |
| code = code if isinstance(code, int) else None | |
| name = type(exc).__name__ | |
| retry = code in RETRY_STATUS or name in {'ResourceExhausted', 'ServiceUnavailable', | |
| 'DeadlineExceeded', 'InternalServerError'} | |
| raise ProviderError(f'{name}: {str(exc)[:300]}', code, retryable=retry) from None | |
| texts, finish = [], None | |
| for cand in (response.candidates or [])[:1]: | |
| finish = getattr(cand.finish_reason, 'name', str(cand.finish_reason)) | |
| for p in cand.content.parts: | |
| if getattr(p, 'text', None) and not getattr(p, 'thought', False): | |
| texts.append(p.text) | |
| meta = getattr(response, 'usage_metadata', None) | |
| usage = {k: getattr(meta, k) for k in ('prompt_token_count', 'candidates_token_count', | |
| 'total_token_count') if meta is not None and hasattr(meta, k)} | |
| return {'text': ''.join(texts), 'finish_reason': finish, 'usage': usage, 'raw': {}} | |
| def _genai_upload(self, part): | |
| cache = getattr(self, '_uploads', None) | |
| if cache is None: | |
| cache = self._uploads = {} | |
| key = (part['path'], Path(part['path']).stat().st_mtime_ns) | |
| if key in cache: | |
| return cache[key] | |
| genai = self._genai | |
| try: | |
| handle = genai.upload_file(part['path'], mime_type=_mime(part, 'video/mp4')) | |
| deadline = time.monotonic() + self.timeout | |
| while getattr(handle.state, 'name', '') == 'PROCESSING': | |
| if time.monotonic() > deadline: | |
| raise ProviderError('uploaded video still processing', retryable=True) | |
| time.sleep(2) | |
| handle = genai.get_file(handle.name) | |
| except ProviderError: | |
| raise | |
| except Exception as exc: | |
| raise ProviderError(f'upload {type(exc).__name__}: {str(exc)[:300]}', retryable=True) from None | |
| if getattr(handle.state, 'name', 'ACTIVE') != 'ACTIVE': | |
| raise ProviderError(f'uploaded video state {handle.state}') | |
| cache[key] = handle | |
| return handle | |
| # -- Gemini -------------------------------------------------------------- | |
| def _gemini_upload(self, path, mime): | |
| base = self.config.get('upload_url', 'https://generativelanguage.googleapis.com/upload/v1beta/files') | |
| size = Path(path).stat().st_size | |
| start = urllib.request.Request( | |
| f'{base}?key={urllib.parse.quote(self.key)}', method='POST', | |
| data=json.dumps({'file': {'display_name': Path(path).name}}).encode(), | |
| headers={'X-Goog-Upload-Protocol': 'resumable', 'X-Goog-Upload-Command': 'start', | |
| 'X-Goog-Upload-Header-Content-Length': str(size), | |
| 'X-Goog-Upload-Header-Content-Type': mime, 'Content-Type': 'application/json'}) | |
| try: | |
| with urllib.request.urlopen(start, timeout=self.timeout) as resp: | |
| upload_url = resp.headers['X-Goog-Upload-URL'] | |
| put = urllib.request.Request(upload_url, method='POST', data=Path(path).read_bytes(), | |
| headers={'X-Goog-Upload-Offset': '0', | |
| 'X-Goog-Upload-Command': 'upload, finalize'}) | |
| with urllib.request.urlopen(put, timeout=self.timeout) as resp: | |
| info = json.loads(resp.read().decode())['file'] | |
| except urllib.error.HTTPError as exc: | |
| raise ProviderError(f'upload HTTP {exc.code}', exc.code, retryable=exc.code in RETRY_STATUS) from None | |
| except (urllib.error.URLError, TimeoutError, ConnectionError) as exc: | |
| raise ProviderError(f'upload network error: {exc}', retryable=True) from None | |
| api = self.config.get('base_url', 'https://generativelanguage.googleapis.com/v1beta').rstrip('/') | |
| deadline = time.monotonic() + self.timeout | |
| while info.get('state') == 'PROCESSING': | |
| if time.monotonic() > deadline: | |
| raise ProviderError('uploaded video still processing', retryable=True) | |
| time.sleep(2) | |
| info = _get(f"{api}/{info['name']}?key={urllib.parse.quote(self.key)}", {}, self.timeout) | |
| if info.get('state') not in (None, 'ACTIVE'): | |
| raise ProviderError(f"uploaded video state {info.get('state')}") | |
| return {'file_data': {'mime_type': mime, 'file_uri': info['uri']}} | |
| def _gemini_parts(self, parts): | |
| limit = int(self.config.get('inline_limit_bytes', 18 * 1024 * 1024)) | |
| out = [] | |
| for part in parts: | |
| if part['type'] == 'text': | |
| out.append({'text': part['text']}) | |
| elif part['type'] == 'image': | |
| out.append({'inline_data': {'mime_type': _mime(part, 'image/jpeg'), | |
| 'data': _b64(part['path'])}}) | |
| elif part['type'] == 'video' and part.get('path'): | |
| mime = _mime(part, 'video/mp4') | |
| if Path(part['path']).stat().st_size <= limit: | |
| item = {'inline_data': {'mime_type': mime, 'data': _b64(part['path'])}} | |
| else: | |
| item = self._gemini_upload(part['path'], mime) | |
| if part.get('fps'): | |
| item['video_metadata'] = {'fps': part['fps']} | |
| out.append(item) | |
| else: | |
| out.extend(self._gemini_parts(expand_video([part]))) | |
| return out | |
| def _gemini(self, request): | |
| base = self.config.get('base_url', 'https://generativelanguage.googleapis.com/v1beta').rstrip('/') | |
| generation = {'maxOutputTokens': request.get('max_tokens', 1024)} | |
| if request.get('temperature') is not None: | |
| generation['temperature'] = request['temperature'] | |
| if request.get('seed') is not None: | |
| generation['seed'] = request['seed'] | |
| payload = {'contents': [{'role': 'user', 'parts': self._gemini_parts(request['parts'])}], | |
| 'generationConfig': generation} | |
| if request.get('system'): | |
| payload['systemInstruction'] = {'parts': [{'text': request['system']}]} | |
| extra = dict(self.config.get('extra', {})) | |
| payload['generationConfig'].update(extra.pop('generationConfig', {})) | |
| payload.update(extra) | |
| headers = {'x-goog-api-key': self.key, **self.config.get('headers', {})} | |
| data, _ = _post(f'{base}/models/{self.model}:generateContent', payload, headers, self.timeout) | |
| cand = (data.get('candidates') or [{}])[0] | |
| texts = [p.get('text', '') for p in cand.get('content', {}).get('parts', []) if not p.get('thought')] | |
| return {'text': ''.join(texts), 'finish_reason': cand.get('finishReason'), | |
| 'usage': data.get('usageMetadata', {}), 'raw': _trim(data)} | |
| # -- Anthropic ----------------------------------------------------------- | |
| def _anthropic(self, request): | |
| base = self.config.get('base_url', 'https://api.anthropic.com').rstrip('/') | |
| content = [] | |
| for part in expand_video(request['parts']): | |
| if part['type'] == 'text': | |
| content.append({'type': 'text', 'text': part['text']}) | |
| else: | |
| content.append({'type': 'image', 'source': { | |
| 'type': 'base64', 'media_type': _mime(part, 'image/jpeg'), 'data': _b64(part['path'])}}) | |
| payload = {'model': self.model, 'max_tokens': request.get('max_tokens', 1024), | |
| 'messages': [{'role': 'user', 'content': content}]} | |
| if request.get('system'): | |
| payload['system'] = request['system'] | |
| temperature = self._temperature(request) | |
| if temperature is not None: | |
| payload['temperature'] = temperature | |
| payload.update(self.config.get('extra', {})) | |
| headers = {'anthropic-version': self.config.get('api_version', '2023-06-01'), | |
| **self.config.get('headers', {})} | |
| if self.key: | |
| headers['x-api-key'] = self.key | |
| path = '/messages' if base.endswith('/v1') else '/v1/messages' | |
| data, _ = _post(f'{base}{path}', payload, headers, self.timeout) | |
| blocks = data.get('content', []) | |
| text = ''.join(b.get('text', '') for b in blocks if b.get('type') == 'text') | |
| thinking = ''.join(b.get('thinking', '') for b in blocks if b.get('type') == 'thinking') | |
| return {'text': text, 'finish_reason': data.get('stop_reason'), 'reasoning': thinking or None, | |
| 'model_reported': data.get('model'), 'usage': data.get('usage', {}), 'raw': _trim(data)} | |
| # -- Codex CLI ----------------------------------------------------------- | |
| def _codex(self, request): | |
| """Options: ``binary`` (default ``codex``), ``effort`` (reasoning effort, default high). | |
| Every call starts in a fresh empty directory with a read-only sandbox and no AGENTS.md, so the model gets the | |
| prompt and nothing of the repository or the answer files. Shell commands it still ran come back as | |
| ``tool_calls`` for audit.""" | |
| if any(p['type'] != 'text' for p in request['parts']): | |
| raise ProviderError('the codex protocol takes text-only requests') | |
| prompt = request['system'] + '\n\n' + '\n'.join(p['text'] for p in request['parts']) | |
| work = tempfile.mkdtemp(prefix='codex-blind-') | |
| last = os.path.join(work, 'last.txt') # written by the CLI after the turn, not by the sandboxed model | |
| cmd = [self.config.get('binary', 'codex'), 'exec', '-m', self.model, '-s', 'read-only', '-C', work, | |
| '--skip-git-repo-check', '--ephemeral', '--json', '-o', last, '-c', 'project_doc_max_bytes=0', | |
| '-c', f"model_reasoning_effort=\"{self.config.get('effort', 'high')}\"", '-'] | |
| try: | |
| proc = subprocess.run(cmd, input=prompt, capture_output=True, text=True, timeout=self.timeout) | |
| text = Path(last).read_text(encoding='utf-8') if os.path.exists(last) else '' | |
| except subprocess.TimeoutExpired: | |
| raise ProviderError(f'codex exec timed out after {self.timeout:.0f} s', retryable=True) | |
| finally: | |
| shutil.rmtree(work, ignore_errors=True) | |
| if proc.returncode != 0 or not text.strip(): | |
| raise ProviderError(f'codex exec rc={proc.returncode}: {proc.stderr.strip()[-300:]}') | |
| events = [json.loads(line) for line in proc.stdout.splitlines() if line.startswith('{')] | |
| usage = next((e.get('usage', {}) for e in reversed(events) if e.get('type') == 'turn.completed'), {}) | |
| commands = [e['item'].get('command') for e in events if e.get('type') == 'item.completed' | |
| and (e.get('item') or {}).get('type') == 'command_execution'] | |
| return {'text': text, 'finish_reason': 'stop', 'usage': usage, 'tool_calls': commands, 'raw': {}} | |
| # -- Mock ---------------------------------------------------------------- | |
| def _mock(self, request): | |
| images = sum(1 for p in expand_video_safe(request['parts']) if p['type'] == 'image') | |
| videos = sum(1 for p in request['parts'] if p['type'] == 'video' and not p.get('frames')) | |
| answer = self.config.get('reply', '{"answer": null}') | |
| return {'text': answer, 'finish_reason': 'stop', | |
| 'usage': {'images': images, 'videos': videos}, 'raw': {}} | |
| def expand_video_safe(parts): | |
| out = [] | |
| for part in parts: | |
| out.extend(part.get('frames') or [part] if part['type'] == 'video' else [part]) | |
| return out | |
| def _chat_result(data): | |
| """Response dict of a Chat Completions reply. | |
| Some gateways return the answer as ``tool_calls`` with empty ``content`` (Gemini behind the | |
| OpenAI-compatible proxy, 10-26: finish_reason ``tool_calls``, 12-40 answer tokens, no text). | |
| Their arguments then stand in for the text; ``text_source`` says so and the calls are kept. | |
| """ | |
| choice = (data.get('choices') or [{}])[0] | |
| message = choice.get('message') or {} | |
| text = message.get('content') or '' | |
| if isinstance(text, list): | |
| text = ''.join(p.get('text', '') for p in text if isinstance(p, dict)) | |
| calls = message.get('tool_calls') or [] | |
| out = {'finish_reason': choice.get('finish_reason'), 'reasoning': _reasoning(message), | |
| 'model_reported': data.get('model'), 'usage': data.get('usage') or {}, 'raw': _trim(data)} | |
| if calls: | |
| out['tool_calls'] = calls | |
| if not text.strip() and calls: | |
| text = '\n'.join(str(((c or {}).get('function') or {}).get('arguments') or '') for c in calls).strip() | |
| out['text_source'] = 'tool_calls' | |
| return {'text': text, **out} | |
| def _trim(data): | |
| """Keep provider metadata without echoing large payloads.""" | |
| text = json.dumps(data) | |
| return data if len(text) <= 20000 else {'truncated': True, 'size': len(text)} | |