# -*- coding: utf-8 -*- """Pure-python transport for OpenAI-compatible chat completion endpoints. Deliberately free of any ``odoo`` import so that it can be unit-tested offline and reused by cron jobs / CLI scripts. Two protocol translations happen here: 1. ``messages`` — our internal part-based format <-> OpenAI role messages. OpenAI requires tool results to be their own ``role: tool`` message, while our internal format keeps tool results inside the user turn. 2. ``tools`` — our ``{name, instructions, schema}`` <-> OpenAI ``{type: function, function: {...}}``. """ import base64 import json import logging import urllib.error import urllib.request _logger = logging.getLogger(__name__) DEFAULT_TIMEOUT = 120 PROVIDER_PRESETS = { 'deepseek': { 'label': 'DeepSeek', 'base_url': 'https://api.deepseek.com', # deepseek-chat / deepseek-reasoner were retired on 2026-07-24. # deepseek-flash (V4.1 Flash) is multimodal and supports the Files API. 'model': 'deepseek-flash', 'embedding_model': '', 'vision': True, # POST /files then reference by file_id. Documents (PDF/Word/PPT) # cannot be inlined — they must go through this endpoint. 'file_api': True, }, 'qwen': { 'label': 'Alibaba Qwen (DashScope)', 'base_url': 'https://dashscope.aliyuncs.com/compatible-mode', 'model': 'qwen-plus', 'embedding_model': 'text-embedding-v3', # qwen-plus is multimodal on DashScope's compatible mode. 'vision': True, 'file_api': False, }, 'openai': { 'label': 'OpenAI', 'base_url': 'https://api.openai.com', 'model': 'gpt-4o-mini', 'embedding_model': 'text-embedding-3-small', 'vision': True, 'file_api': False, }, 'ollama': { 'label': 'Ollama (local)', 'base_url': 'http://localhost:11434', 'model': 'qwen2.5', 'embedding_model': 'nomic-embed-text', # Depends on the pulled model, so let the admin decide. 'vision': False, 'file_api': False, }, 'custom': { 'label': 'Custom OpenAI-compatible endpoint', 'base_url': '', 'model': '', 'embedding_model': '', 'vision': False, 'file_api': False, }, } # --------------------------------------------------------------------------- # part <-> message conversion # --------------------------------------------------------------------------- def parts_text(parts, include_tool_results=True): """Flatten a content part list into plain text. ``inline_data`` parts have no textual representation: they are binary the model either consumes natively (see ``_attachment_content``) or cannot use at all. Reporting them as a placeholder is deliberate — dropping them silently makes the assistant answer as if no file had been attached. """ if isinstance(parts, str): return parts texts = [] for part in parts or []: if not isinstance(part, dict): continue if part.get('type') == 'text': texts.append(part.get('text') or '') elif part.get('type') == 'inline_data': texts.append(_attachment_caption(part)) elif include_tool_results and part.get('type') == 'tool_result': texts.append(parts_text(part.get('result'), include_tool_results)) return ''.join(texts) def _attachment_caption(part): """One-line description of a binary part, for text-only models.""" metadata = part.get('metadata') or {} name = metadata.get('name') mimetype = part.get('mimetype', 'binary') if name: return f"[attached file: {name} ({mimetype})]" return f"[attached file: {mimetype}]" def _attachment_content(part): """OpenAI multimodal content block for an ``inline_data`` part. Images travel as ``image_url`` data URLs, which every OpenAI-compatible vision endpoint accepts. Documents are *not* valid inline images — they must be uploaded first (see ``upload_file``) and referenced by ``file_id``. A document reaching this function means the provider has no file API, in which case ``ai_attachment_tools`` should already have converted it to text. """ mimetype = part.get('mimetype') or 'application/octet-stream' data = part.get('data') or '' return { 'type': 'image_url', 'image_url': {'url': f"data:{mimetype};base64,{data}"}, } def _multipart_file(fields, file_field, filename, content, content_type, boundary): """Build a multipart/form-data body with all ``fields`` before the file. DeepSeek's Files API requires ``purpose`` to appear before ``file``; the ordered dict keeps that guarantee regardless of caller ordering. """ chunks = [] for key, value in fields.items(): head = (f"--{boundary}\r\n" f'Content-Disposition: form-data; name="{key}"\r\n\r\n').encode('utf-8') chunks.append(head + str(value).encode('utf-8') + b'\r\n') chunks.append(( f"--{boundary}\r\n" f'Content-Disposition: form-data; name="{file_field}"; filename="{filename}"\r\n' f"Content-Type: {content_type}\r\n\r\n" ).encode('utf-8')) chunks.append(content) chunks.append(b'\r\n') chunks.append(f"--{boundary}--\r\n".encode('utf-8')) return b''.join(chunks) def upload_file(cfg, filename, data, purpose='user_data', timeout=DEFAULT_TIMEOUT): """Upload a file to the provider's Files API and return its ``file_id``. Documents (PDF/Word/PPT) need ``text_recognition`` or ``rich_layout_recognition``; images and plain text use ``user_data``. ``purpose`` is deliberately sent as the first form field — DeepSeek rejects the request if ``file`` comes first. """ base_url = (cfg.get('base_url') or '').rstrip('/') if not base_url: raise ProviderError("No base URL configured for the AI provider.") boundary = '----dnAIFileBoundary7d2a91f4' content_type = cfg.get('mimetype') or 'application/octet-stream' body = _multipart_file( {'purpose': purpose}, 'file', filename or 'file', data, content_type, boundary) headers = { 'Content-Type': f'multipart/form-data; boundary={boundary}', 'Content-Length': str(len(body)), } if cfg.get('api_key'): headers['Authorization'] = f"Bearer {cfg['api_key']}" url = f"{base_url}/files" request = urllib.request.Request(url, data=body, headers=headers, method='POST') try: with urllib.request.urlopen(request, timeout=timeout) as response: raw = response.read().decode('utf-8') except urllib.error.HTTPError as exc: detail = exc.read().decode('utf-8', errors='replace')[:800] raise ProviderError(f"HTTP {exc.code} uploading {filename}: {detail}") from exc except urllib.error.URLError as exc: raise ProviderError(f"Cannot reach {url}: {exc.reason}") from exc except TimeoutError as exc: raise ProviderError(f"Timeout after {timeout}s uploading {filename}") from exc try: result = json.loads(raw) except ValueError as exc: raise ProviderError(f"Invalid file-upload response: {raw[:300]}") from exc file_id = result.get('id') if not file_id: raise ProviderError(f"No file id in upload response: {raw[:300]}") return file_id def _file_content(part): """OpenAI-compatible content block referencing an uploaded file.""" block = {'type': 'file', 'file_id': part['file_id']} if part.get('filename'): block['filename'] = part['filename'] return block def _top_text(parts): return ''.join( part.get('text') or '' for part in (parts or []) if isinstance(part, dict) and part.get('type') == 'text' ) def _sanitize_tool_pairs(messages): """Enforce the strict ``tool_calls`` / ``tool`` pairing required by OpenAI. Our persisted history can legitimately contain broken pairs: a turn may be interrupted (the user sends a new message while a tool waits for confirmation, or the provider fails mid-loop) after the assistant ``tool_calls`` event was saved but before the matching results were. The provider then rejects the *whole* request with:: An assistant message with 'tool_calls' must be followed by tool messages responding to each 'tool_call_id'. Losing the conversation over that is unacceptable, so repair it here: * every ``tool_call_id`` of an assistant message gets exactly one ``tool`` message right after it (missing ones become an "aborted" result); * ``tool`` messages that no assistant message claims are dropped. """ cleaned = [] index = 0 total = len(messages) while index < total: message = messages[index] role = message.get('role') if role == 'tool': # Orphan tool message: no assistant turn claims it. index += 1 continue cleaned.append(message) if role != 'assistant' or not message.get('tool_calls'): index += 1 continue expected_ids = [call.get('id') for call in message['tool_calls']] # Collect the contiguous run of tool messages that follows. cursor = index + 1 found = {} while cursor < total and messages[cursor].get('role') == 'tool': call_id = messages[cursor].get('tool_call_id') if call_id in expected_ids and call_id not in found: found[call_id] = messages[cursor] cursor += 1 for call_id in expected_ids: cleaned.append(found.get(call_id) or { 'role': 'tool', 'tool_call_id': call_id, 'content': 'aborted: the tool was never executed', }) index = cursor return cleaned def to_provider_messages(messages, vision=True): """Our messages -> OpenAI style messages. Assistant tool calls become ``tool_calls``; our ``tool_result`` parts become standalone ``role: tool`` messages (required by the spec). ``vision`` decides what happens to ``inline_data`` parts: when true they are sent as multimodal content blocks, otherwise they collapse into a ``[attached file: ...]`` caption so a text-only model at least knows a file was there. Providers reject an unknown content-block type outright, so the two paths can never be mixed silently. """ out = [] for msg in messages or []: role = msg.get('role') content = msg.get('content') or [] if role == 'assistant': text = _top_text(content) tool_calls = [] for part in content: if not isinstance(part, dict) or part.get('type') != 'tool_call': continue args = part.get('args') if not isinstance(args, str): args = json.dumps(args or {}, ensure_ascii=False) tool_calls.append({ 'id': part.get('call_id'), 'type': 'function', 'function': {'name': part.get('name'), 'arguments': args}, }) entry = {'role': 'assistant'} # OpenAI rejects an assistant message whose content is empty and # which carries no tool_calls, so keep a placeholder. entry['content'] = text if text.strip() or not tool_calls else None if tool_calls: entry['tool_calls'] = tool_calls out.append(entry) # Tool results produced *by* this assistant turn travel as their own # messages; they live in the following user entry in our format, so # nothing to do here. continue # user turn: text and attachments form *one* message, in order; tool # results then follow as their own messages. blocks = [] has_attachment = False for part in content: if not isinstance(part, dict): continue if part.get('type') == 'text': text = part.get('text') or '' if text.strip(): blocks.append({'type': 'text', 'text': text}) elif part.get('type') == 'file': # Already uploaded through the provider's Files API. has_attachment = True blocks.append(_file_content(part)) elif part.get('type') == 'inline_data': has_attachment = True if vision: blocks.append(_attachment_content(part)) else: blocks.append({'type': 'text', 'text': _attachment_caption(part)}) if blocks: if has_attachment and (vision or any( b.get('type') == 'file' for b in blocks if isinstance(b, dict))): out.append({'role': 'user', 'content': blocks}) else: # Several parts are being flattened into one string, and each # file block starts with "Content of file ...": without a # separator the question and the first file, or two files, # would run together ("what do these say?Content of file ..."). # `len(blocks)` is what matters, not `has_attachment`: two text # files produce no `inline_data` at all. separator = '\n\n' if len(blocks) > 1 else '' out.append({ 'role': 'user', 'content': separator.join(block['text'] for block in blocks), }) for part in content: if not isinstance(part, dict): continue if part.get('type') == 'tool_result': out.append({ 'role': 'tool', # `tool_call_id` is what we persist; `call_id` is what the # protocol types use, so accept both. 'tool_call_id': part.get('tool_call_id') or part.get('call_id'), 'content': parts_text(part.get('result')) or ('success' if part.get('success', True) else 'failed'), }) return _sanitize_tool_pairs(out) def to_provider_tools(tools): out = [] for tool in tools or []: schema = tool.get('schema') or {'type': 'object', 'properties': {}, 'required': []} out.append({ 'type': 'function', 'function': { 'name': tool.get('name'), 'description': tool.get('instructions') or '', 'parameters': schema, }, }) return out def from_provider_message(message): """OpenAI assistant message -> our AssistantMessage (stable key order).""" content = [] text = message.get('content') if text: content.append({'type': 'text', 'text': text}) for call in message.get('tool_calls') or []: function = call.get('function') or {} raw = function.get('arguments', '{}') try: args = json.loads(raw) if isinstance(raw, str) else (raw or {}) except (ValueError, TypeError): args = {} content.append({ 'type': 'tool_call', 'name': function.get('name'), 'args': args, 'call_id': call.get('id'), }) return {'role': 'assistant', 'content': content} # --------------------------------------------------------------------------- # HTTP # --------------------------------------------------------------------------- class ProviderError(Exception): """Raised when the provider cannot be reached or returns an error.""" def _post_json(url, payload, headers, timeout): body = json.dumps(payload, ensure_ascii=False).encode('utf-8') request = urllib.request.Request(url, data=body, headers=headers, method='POST') try: with urllib.request.urlopen(request, timeout=timeout) as response: raw = response.read().decode('utf-8') except urllib.error.HTTPError as exc: detail = exc.read().decode('utf-8', errors='replace')[:800] raise ProviderError(f"HTTP {exc.code} from {url}: {detail}") from exc except urllib.error.URLError as exc: raise ProviderError(f"Cannot reach {url}: {exc.reason}") from exc except TimeoutError as exc: raise ProviderError(f"Timeout after {timeout}s calling {url}") from exc if not raw.strip(): return None try: return json.loads(raw) except ValueError as exc: raise ProviderError(f"Invalid JSON from {url}: {raw[:300]}") from exc def _headers(api_key): headers = {'Content-Type': 'application/json'} if api_key: headers['Authorization'] = f'Bearer {api_key}' return headers def _upload_inline_files(cfg, messages, timeout): """Replace uploadable ``inline_data`` parts with ``file`` references. Only providers declaring ``file_api`` in their preset reach here. Each image/PDF is posted to ``{base_url}/files`` and swapped for a ``file`` part carrying the returned id. Failures are logged and the original part is kept so a transient upload error does not lose the user's whole message — the provider will then receive the base64 block as a last resort. A fresh list of messages is returned; the caller's events stay untouched. """ try: from .ai_attachment_tools import guess_kind except ImportError: # loaded standalone (offline unit test) from ai_attachment_tools import guess_kind out = [] for message in messages or []: role = message.get('role') content = message.get('content') or [] if role != 'user' or not isinstance(content, list): out.append(message) continue parts = [] for part in content: if not isinstance(part, dict) or part.get('type') != 'inline_data': parts.append(part) continue mimetype = part.get('mimetype') or 'application/octet-stream' metadata = part.get('metadata') or {} name = metadata.get('name') or 'file' kind = guess_kind(mimetype, name) # Documents need OCR/layout parsing on the provider side; plain # images use user_data. Passing the wrong purpose returns HTTP 400. purpose = 'text_recognition' if kind in ('pdf', 'word', 'sheet', 'slide') else 'user_data' try: data = base64.b64decode(part.get('data') or '') file_cfg = dict(cfg, mimetype=mimetype) file_id = upload_file(file_cfg, name, data, purpose=purpose, timeout=timeout) parts.append({'type': 'file', 'file_id': file_id, 'filename': name}) except (ProviderError, ValueError) as exc: _logger.warning("File upload failed for %s: %s", name, exc) parts.append(part) out.append(dict(message, content=parts)) return out def _inline_pdfs_to_text(messages): """Turn PDF ``inline_data`` parts into extracted text for text-only models. Keeps images as inline data (they are either sent as vision blocks or degraded to a caption, both handled downstream). The caller's messages are not mutated. """ try: from .ai_attachment_tools import build_parts, guess_kind except ImportError: # loaded standalone (offline unit test) from ai_attachment_tools import build_parts, guess_kind out = [] for message in messages or []: content = message.get('content') or [] if not isinstance(content, list): out.append(message) continue parts = [] for part in content: if (isinstance(part, dict) and part.get('type') == 'inline_data' and (part.get('mimetype') or '').lower() == 'application/pdf'): metadata = part.get('metadata') or {} try: data = base64.b64decode(part.get('data') or '') parts.extend(build_parts(metadata.get('name') or 'document.pdf', 'application/pdf', data, pdf_as_text=True)) except (ValueError, TypeError) as exc: _logger.warning("PDF text extraction failed: %s", exc) parts.append(part) else: parts.append(part) out.append(dict(message, content=parts)) return out def _to_responses_input(messages, instructions=''): """Our messages -> Responses API ``input`` list. The Responses protocol is needed for documents: DeepSeek's Chat Completions accepts ``file`` blocks for images only and rejects OCR files ("uploaded for OCR and cannot be used as images"), whereas Responses has a dedicated ``input_file`` block. Text/images/tool calls map 1:1. """ entries = [] if instructions: entries.append({'role': 'system', 'content': instructions}) for msg in messages or []: role = msg.get('role') content = msg.get('content') or [] if role == 'assistant': text = _top_text(content) calls = [] for part in content: if isinstance(part, dict) and part.get('type') == 'tool_call': args = part.get('args') if not isinstance(args, str): args = json.dumps(args or {}, ensure_ascii=False) calls.append({ 'type': 'function_call', 'call_id': part.get('call_id'), 'name': part.get('name'), 'arguments': args, }) item = {'type': 'message', 'role': 'assistant', 'content': [{'type': 'output_text', 'text': text}]} entries.append(item) entries.extend(calls) continue if role == 'tool': entries.append({ 'type': 'function_call_output', 'call_id': msg.get('tool_call_id'), 'output': msg.get('content') or '', }) continue # user turn: text/attachments build one message, but tool results must # be standalone function_call_output items (like the chat protocol). blocks = [] for part in content: if not isinstance(part, dict): continue if part.get('type') == 'text': if (part.get('text') or '').strip(): blocks.append({'type': 'input_text', 'text': part['text']}) elif part.get('type') == 'file': blocks.append({'type': 'input_file', 'file_id': part['file_id']}) elif part.get('type') == 'tool_result': call_id = part.get('call_id') or part.get('tool_call_id') result = part.get('result') if not isinstance(result, str): result = json.dumps(result or {}, ensure_ascii=False, default=str) entries.append({'type': 'function_call_output', 'call_id': call_id, 'output': result}) elif part.get('type') == 'inline_data': # Images are accepted inline as data urls in Responses too. mimetype = part.get('mimetype') or 'image/png' data = part.get('data') or '' blocks.append({'type': 'input_image', 'image_url': f"data:{mimetype};base64,{data}"}) if blocks: entries.append({'role': 'user', 'content': blocks}) return entries def _from_responses_output(data): """Responses API object -> our AssistantMessage dict.""" content = [] for item in data.get('output') or []: kind = item.get('type') if kind == 'function_call': try: args = json.loads(item.get('arguments') or '{}') except (ValueError, TypeError): args = {} content.append({'type': 'tool_call', 'name': item.get('name'), 'args': args, 'call_id': item.get('call_id')}) elif kind == 'message': for block in item.get('content') or []: if block.get('type') in ('output_text', 'text') and block.get('text'): content.append({'type': 'text', 'text': block['text']}) # Some endpoints put a plain string in `output_text`. if not content and isinstance(data.get('output_text'), str): content.append({'type': 'text', 'text': data['output_text']}) return {'role': 'assistant', 'content': content} def chat_completion_responses(cfg, messages, instructions='', tools=None, schema=None, timeout=DEFAULT_TIMEOUT): """Call ``/responses``; used when the request references uploaded documents.""" base_url = (cfg.get('base_url') or '').rstrip('/') model = cfg.get('model') if not base_url or not model: raise ProviderError("Provider base URL / model is not configured.") payload = {'model': model, 'input': _to_responses_input(messages, instructions)} if tools: payload['tools'] = [ {'type': 'function', 'name': t['name'], 'description': t.get('description') or t.get('instructions') or '', 'parameters': t.get('parameters') or t.get('schema') or {}, 'strict': False} for t in tools ] if cfg.get('temperature') is not None: payload['temperature'] = cfg['temperature'] if cfg.get('max_tokens'): payload['max_output_tokens'] = cfg['max_tokens'] if schema: payload['text'] = {'format': {'type': 'json_object'}} return _from_responses_output(_post_json( f"{base_url}/v1/responses", payload, _headers(cfg.get('api_key')), timeout)) def chat_completion(cfg, messages, instructions='', tools=None, schema=None, timeout=DEFAULT_TIMEOUT, vision=True): """Call ``/chat/completions`` and return our AssistantMessage. :param cfg: dict with ``base_url``, ``api_key``, ``model``, optional ``temperature`` and ``max_tokens``. :param vision: send ``inline_data`` parts as multimodal blocks. Turn it off for text-only models, which reject image content outright. :raises ProviderError: on transport or protocol failure. """ base_url = (cfg.get('base_url') or '').rstrip('/') model = cfg.get('model') if not base_url: raise ProviderError("No base URL configured for the AI provider.") if not model: raise ProviderError("No model configured for the AI provider.") # The caller may pass vision explicitly; otherwise `cfg['vision']` (derived # from the provider preset / setting) decides. if vision: vision = cfg.get('vision', True) # Providers with a Files API receive documents as uploaded references, # not as inline base64. Do this before the message conversion so the # `file` blocks are part of the same user turn as the question. file_blocks = False if cfg.get('file_api'): messages = _upload_inline_files(cfg, messages, timeout) file_blocks = any( isinstance(p, dict) and p.get('type') == 'file' for msg in messages for p in (msg.get('content') or []) if isinstance(msg.get('content'), list)) # DeepSeek's Chat Completions rejects OCR file_ids ("uploaded for OCR # and cannot be used as images"); documents must go through Responses. if file_blocks: return chat_completion_responses( cfg, messages, instructions=instructions, tools=tools, schema=schema, timeout=timeout) vision = True # No Files API and no vision: a PDF inline blob would be thrown away by # to_provider_messages (it degrades to a bare file name). Extract the # text locally instead so a text-only model still sees the document. if not cfg.get('file_api') and not vision: messages = _inline_pdfs_to_text(messages) payload = {'model': model} if instructions: payload['messages'] = [{'role': 'system', 'content': instructions}] else: payload['messages'] = [] payload['messages'] += to_provider_messages(messages, vision=vision) openai_tools = to_provider_tools(tools) if openai_tools: payload['tools'] = openai_tools payload['tool_choice'] = 'auto' if cfg.get('temperature') is not None: payload['temperature'] = cfg['temperature'] if cfg.get('max_tokens'): payload['max_tokens'] = cfg['max_tokens'] if schema: payload['response_format'] = {'type': 'json_object'} payload['messages'][0]['content'] = ( (payload['messages'][0]['content'] if payload['messages'] else '') + "\n\n[OUTPUT FORMAT] Reply with a single JSON object strictly " "conforming to this JSON schema:\n" + json.dumps(schema, ensure_ascii=False) ) data = _post_json(f"{base_url}/v1/chat/completions", payload, _headers(cfg.get('api_key')), timeout) try: return from_provider_message(data['choices'][0]['message']) except (KeyError, IndexError, TypeError) as exc: raise ProviderError(f"Unexpected response shape: {str(data)[:400]}") from exc def embeddings(cfg, inputs, model=None, timeout=DEFAULT_TIMEOUT): """Call ``/embeddings``; returns a list of float vectors in input order.""" base_url = (cfg.get('base_url') or '').rstrip('/') model = model or cfg.get('embedding_model') if not base_url or not model: raise ProviderError("Embeddings are not configured (base URL / model).") data = _post_json( f"{base_url}/v1/embeddings", {'model': model, 'input': inputs}, _headers(cfg.get('api_key')), timeout, ) try: rows = sorted(data['data'], key=lambda row: row.get('index', 0)) return [row['embedding'] for row in rows] except (KeyError, TypeError) as exc: raise ProviderError(f"Unexpected embeddings response: {str(data)[:300]}") from exc def probe(cfg, timeout=15): """Validate credentials with a minimal completion. Returns (ok, message).""" try: result = chat_completion(dict(cfg), [{'role': 'user', 'content': 'ping'}], instructions='Reply with the single word: pong', timeout=timeout) except ProviderError as exc: return False, str(exc) text = parts_text(result.get('content')) or '(empty)' return True, text.strip()[:200]