Files
computer/cptr/utils/ai.py
T
2026-06-11 13:38:55 +01:00

566 lines
22 KiB
Python

"""Provider streaming and completion functions: raw httpx.
Each streaming function takes a ChatCompletionForm + url + key.
All yield normalized events: text_delta, tool_call, usage, done.
chat_completion() provides a simple non-streaming call for lightweight tasks
(title generation, summarization, etc.).
"""
from __future__ import annotations
import asyncio
import json
import logging
from collections.abc import AsyncIterator
from typing import Dict, List
import httpx
from pydantic import BaseModel
from cptr.env import (
STREAM_CONNECT_TIMEOUT_SECONDS,
STREAM_READ_TIMEOUT_SECONDS,
STREAM_WRITE_TIMEOUT_SECONDS,
)
logger = logging.getLogger(__name__)
_STREAM_RETRY_ATTEMPTS = 3
_STREAM_TIMEOUT = httpx.Timeout(
STREAM_CONNECT_TIMEOUT_SECONDS,
read=STREAM_READ_TIMEOUT_SECONDS,
write=STREAM_WRITE_TIMEOUT_SECONDS,
)
_STREAM_RETRY_ERRORS = (
httpx.ConnectError,
httpx.ConnectTimeout,
httpx.ReadError,
httpx.ReadTimeout,
httpx.RemoteProtocolError,
httpx.WriteTimeout,
)
class ChatCompletionForm(BaseModel):
"""Mirrors OpenAI Responses API request shape."""
model: str
messages: List[Dict]
instructions: str = ""
tools: List[Dict] = []
# ── Non-streaming completion ────────────────────────────────
async def chat_completion(
provider: str,
base_url: str,
api_key: str,
model: str,
messages: list[dict],
system: str = "",
max_tokens: int = 100,
api_type: str = "chat_completions",
request_params: dict | None = None,
) -> str:
"""Simple non-streaming chat completion. Returns the text content.
Works with Anthropic, OpenAI Chat Completions, and OpenAI Responses API.
Useful for lightweight tasks like title/summary generation.
"""
async with httpx.AsyncClient(timeout=httpx.Timeout(15)) as client:
if provider == "anthropic":
body: dict = {
"model": model,
"messages": messages,
"max_tokens": max_tokens,
}
if system:
body["system"] = system
if request_params:
body.update(request_params)
resp = await client.post(
f"{base_url}/messages",
json=body,
headers={
"x-api-key": api_key,
"anthropic-version": "2023-06-01",
},
)
elif api_type == "responses":
# OpenAI Responses API
body_r: dict = {
"model": model,
"input": messages,
"max_output_tokens": max_tokens,
}
if system:
body_r["instructions"] = system
if request_params:
body_r.update(request_params)
resp = await client.post(
f"{base_url}/responses",
json=body_r,
headers={"Authorization": f"Bearer {api_key}"},
)
else:
# OpenAI Chat Completions (default)
all_messages = messages[:]
if system:
all_messages.insert(0, {"role": "system", "content": system})
body_cc: dict = {
"model": model,
"messages": all_messages,
"max_completion_tokens": max_tokens,
}
if request_params:
body_cc.update(request_params)
resp = await client.post(
f"{base_url}/chat/completions",
json=body_cc,
headers={"Authorization": f"Bearer {api_key}"},
)
if resp.status_code >= 400:
logger.debug(
"[chat_completion] %s %s → %s: %s",
provider,
model,
resp.status_code,
resp.text[:500],
)
resp.raise_for_status()
data = resp.json()
if provider == "anthropic":
return data.get("content", [{}])[0].get("text", "")
if api_type == "responses":
# Responses API: output is a list of items
for item in data.get("output", []):
if item.get("type") == "message":
for c in item.get("content", []):
if c.get("type") == "output_text":
return c.get("text", "")
return ""
return data.get("choices", [{}])[0].get("message", {}).get("content", "")
# ── Anthropic ────────────────────────────────────────────────
def _to_anthropic_messages(messages: list[dict]) -> list[dict]:
"""Canonical messages → Anthropic format."""
result = []
for m in messages:
role = m["role"]
if role == "system":
continue # system goes in body.system
content = m.get("content", "")
if isinstance(content, list):
formatted_content = []
for block in content:
if block.get("type") == "text":
formatted_content.append({"type": "text", "text": block.get("text", "")})
elif block.get("type") == "image":
formatted_content.append({
"type": "image",
"source": {
"type": "base64",
"media_type": block.get("media_type", "image/jpeg"),
"data": block.get("base64", "")
}
})
content = formatted_content
if role == "tool":
# tool result → Anthropic tool_result block
result.append(
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": m.get("tool_call_id", ""),
"content": content,
}
],
}
)
elif role == "assistant" and m.get("tool_calls"):
# assistant with tool calls → Anthropic tool_use blocks
blocks: list[dict] = []
if content:
blocks.append({"type": "text", "text": content})
for tc in m["tool_calls"]:
blocks.append(
{
"type": "tool_use",
"id": tc.get("id", ""),
"name": tc["function"]["name"],
"input": json.loads(tc["function"].get("arguments", "{}")),
}
)
result.append({"role": "assistant", "content": blocks})
else:
result.append({"role": role, "content": content})
return result
async def stream_anthropic(
form_data: ChatCompletionForm, url: str, key: str, *, request_params: dict | None = None
) -> AsyncIterator[dict]:
tools = [
{
"name": t["name"],
"description": t["description"],
"input_schema": t["parameters"],
}
for t in form_data.tools
]
body = {
"model": form_data.model,
"system": form_data.instructions,
"messages": _to_anthropic_messages(form_data.messages),
"tools": tools if tools else None,
"stream": True,
"max_tokens": 4096,
}
if request_params:
body.update(request_params)
# Remove None values
body = {k: v for k, v in body.items() if v is not None}
headers = {"x-api-key": key, "anthropic-version": "2023-06-01"}
emitted = False
for attempt in range(_STREAM_RETRY_ATTEMPTS):
try:
async with httpx.AsyncClient(timeout=_STREAM_TIMEOUT) as client:
logger.info("[stream] anthropic POST %s/messages model=%s", url, form_data.model)
async with client.stream(
"POST", f"{url}/messages", json=body, headers=headers
) as resp:
logger.info("[stream] anthropic status=%s", resp.status_code)
resp.raise_for_status()
current_block: dict = {}
usage_data: dict = {}
async for line in resp.aiter_lines():
if not line.startswith("data: "):
continue
event = json.loads(line[6:])
etype = event.get("type")
if etype == "message_start":
msg_usage = event.get("message", {}).get("usage", {})
if msg_usage:
usage_data["input_tokens"] = msg_usage.get("input_tokens", 0)
for cache_key in ("cache_read_input_tokens", "cache_creation_input_tokens"):
if msg_usage.get(cache_key):
usage_data[cache_key] = msg_usage[cache_key]
if etype == "content_block_start":
block = event["content_block"]
current_block = {"type": block["type"], "index": event["index"]}
if block["type"] == "tool_use":
current_block["id"] = block["id"]
current_block["name"] = block["name"]
current_block["input_json"] = ""
elif etype == "content_block_delta":
delta = event["delta"]
if delta["type"] == "text_delta":
emitted = True
yield {"type": "text_delta", "content": delta["text"]}
elif delta["type"] == "input_json_delta":
current_block["input_json"] += delta["partial_json"]
elif etype == "content_block_stop":
if current_block.get("type") == "tool_use":
emitted = True
yield {
"type": "tool_call",
"call_id": current_block["id"],
"name": current_block["name"],
"arguments": json.loads(current_block["input_json"]),
}
elif etype == "message_delta":
delta_usage = event.get("usage", {})
if delta_usage:
usage_data["output_tokens"] = delta_usage.get("output_tokens", 0)
emitted = True
yield {"type": "usage", **usage_data}
elif etype == "message_stop":
emitted = True
yield {"type": "done"}
return
except _STREAM_RETRY_ERRORS:
if emitted or attempt == _STREAM_RETRY_ATTEMPTS - 1:
raise
logger.warning(
"[stream] anthropic transient stream failure before first event; retrying (%s/%s)",
attempt + 1,
_STREAM_RETRY_ATTEMPTS,
exc_info=True,
)
await asyncio.sleep(0.5 * (attempt + 1))
# ── OpenAI Chat Completions ──────────────────────────────────
def _to_openai_messages(messages: list[dict], instructions: str) -> list[dict]:
"""Canonical messages → OpenAI Chat Completions format."""
result = []
if instructions:
result.append({"role": "system", "content": instructions})
for m in messages:
if m["role"] == "system":
continue
content = m.get("content", "")
if isinstance(content, list):
formatted_content = []
for block in content:
if block.get("type") == "text":
formatted_content.append({"type": "text", "text": block.get("text", "")})
elif block.get("type") == "image":
data_uri = f"data:{block.get('media_type', 'image/jpeg')};base64,{block.get('base64', '')}"
formatted_content.append({
"type": "image_url",
"image_url": {"url": data_uri}
})
new_m = dict(m)
new_m["content"] = formatted_content
result.append(new_m)
else:
result.append(m)
return result
async def stream_openai_completions(
form_data: ChatCompletionForm, url: str, key: str, *, request_params: dict | None = None
) -> AsyncIterator[dict]:
tools = [
{
"type": "function",
"function": {
"name": t["name"],
"description": t["description"],
"parameters": t["parameters"],
},
}
for t in form_data.tools
]
body: dict = {
"model": form_data.model,
"messages": _to_openai_messages(form_data.messages, form_data.instructions),
"stream": True,
"stream_options": {"include_usage": True},
}
if tools:
body["tools"] = tools
if request_params:
body.update(request_params)
headers = {"Authorization": f"Bearer {key}"}
emitted = False
for attempt in range(_STREAM_RETRY_ATTEMPTS):
try:
async with httpx.AsyncClient(timeout=_STREAM_TIMEOUT) as client:
logger.info(
"[stream] openai completions POST %s/chat/completions model=%s",
url,
form_data.model,
)
async with client.stream(
"POST", f"{url}/chat/completions", json=body, headers=headers
) as resp:
logger.info("[stream] openai completions status=%s", resp.status_code)
resp.raise_for_status()
tool_calls: dict[int, dict] = {}
async for line in resp.aiter_lines():
if not line.startswith("data: ") or line == "data: [DONE]":
continue
chunk = json.loads(line[6:])
choices = chunk.get("choices", [])
delta = choices[0].get("delta", {}) if choices else {}
if delta.get("content"):
emitted = True
yield {"type": "text_delta", "content": delta["content"]}
for tc in delta.get("tool_calls", []):
idx = tc["index"]
if idx not in tool_calls:
tool_calls[idx] = {
"id": tc["id"],
"name": tc["function"]["name"],
"arguments_json": "",
}
tool_calls[idx]["arguments_json"] += tc["function"].get("arguments", "")
if choices and choices[0].get("finish_reason") == "tool_calls":
for tc in tool_calls.values():
emitted = True
yield {
"type": "tool_call",
"call_id": tc["id"],
"name": tc["name"],
"arguments": json.loads(tc["arguments_json"]),
}
if chunk.get("usage"):
raw = chunk["usage"]
emitted = True
yield {
"type": "usage",
"input_tokens": raw.get("prompt_tokens", 0),
"output_tokens": raw.get("completion_tokens", 0),
}
emitted = True
yield {"type": "done"}
return
except _STREAM_RETRY_ERRORS:
if emitted or attempt == _STREAM_RETRY_ATTEMPTS - 1:
raise
logger.warning(
"[stream] openai completions transient stream failure before first event; retrying (%s/%s)",
attempt + 1,
_STREAM_RETRY_ATTEMPTS,
exc_info=True,
)
await asyncio.sleep(0.5 * (attempt + 1))
# ── OpenAI Responses API ─────────────────────────────────────
def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]:
"""Canonical messages → Responses API input items."""
items = []
for m in messages:
role = m["role"]
if role == "system":
continue
if role == "tool":
items.append(
{
"type": "function_call_output",
"call_id": m.get("tool_call_id", ""),
"output": m.get("content", ""),
}
)
elif role == "assistant" and m.get("tool_calls"):
for tc in m["tool_calls"]:
items.append(
{
"type": "function_call",
"id": tc.get("id", ""),
"call_id": tc.get("id", ""),
"name": tc["function"]["name"],
"arguments": tc["function"].get("arguments", "{}"),
}
)
else:
content = m.get("content", "")
if isinstance(content, list):
formatted_content = []
for block in content:
if block.get("type") == "text":
formatted_content.append({"type": "input_text", "text": block.get("text", "")})
elif block.get("type") == "image":
# Not all models support input_image, but this is the Responses API spec
data_uri = f"data:{block.get('media_type', 'image/jpeg')};base64,{block.get('base64', '')}"
formatted_content.append({
"type": "input_image",
"image_url": data_uri
})
items.append({"role": role, "content": formatted_content})
else:
items.append({"role": role, "content": content})
return items
async def stream_openai_responses(
form_data: ChatCompletionForm, url: str, key: str, *, request_params: dict | None = None
) -> AsyncIterator[dict]:
tools = [
{
"type": "function",
"name": t["name"],
"description": t["description"],
"parameters": t["parameters"],
}
for t in form_data.tools
]
body: dict = {
"model": form_data.model,
"input": _to_responses_input(form_data.messages, form_data.instructions),
"stream": True,
}
if form_data.instructions:
body["instructions"] = form_data.instructions
if tools:
body["tools"] = tools
if request_params:
body.update(request_params)
headers = {"Authorization": f"Bearer {key}"}
emitted = False
for attempt in range(_STREAM_RETRY_ATTEMPTS):
try:
async with httpx.AsyncClient(timeout=_STREAM_TIMEOUT) as client:
logger.info(
"[stream] openai responses POST %s/responses model=%s", url, form_data.model
)
async with client.stream(
"POST", f"{url}/responses", json=body, headers=headers
) as resp:
logger.info("[stream] openai responses status=%s", resp.status_code)
resp.raise_for_status()
async for line in resp.aiter_lines():
if not line.startswith("data: "):
continue
event = json.loads(line[6:])
etype = event.get("type")
if etype == "response.output_text.delta":
emitted = True
yield {"type": "text_delta", "content": event["delta"]}
elif etype == "response.output_item.done":
item = event["item"]
if item["type"] == "function_call":
emitted = True
yield {
"type": "tool_call",
"call_id": item["call_id"],
"name": item["name"],
"arguments": json.loads(item["arguments"]),
}
elif etype == "response.completed":
usage = event.get("response", {}).get("usage", {})
if usage:
emitted = True
yield {"type": "usage", **usage}
emitted = True
yield {"type": "done"}
return
except _STREAM_RETRY_ERRORS:
if emitted or attempt == _STREAM_RETRY_ATTEMPTS - 1:
raise
logger.warning(
"[stream] openai responses transient stream failure before first event; retrying (%s/%s)",
attempt + 1,
_STREAM_RETRY_ATTEMPTS,
exc_info=True,
)
await asyncio.sleep(0.5 * (attempt + 1))