forked from linkong/planet
1575 lines
67 KiB
Python
1575 lines
67 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from collections.abc import AsyncIterator
|
|
import json
|
|
from typing import Any
|
|
from uuid import NAMESPACE_URL, uuid4, uuid5
|
|
|
|
import httpx
|
|
from fastapi import HTTPException, status
|
|
|
|
from aiprovider.config import settings
|
|
from aiprovider.schemas import (
|
|
AIContentBlock,
|
|
AIProviderStatusResponse,
|
|
SituationalAnalysisRequest,
|
|
SituationalAnalysisResponse,
|
|
ToolCallRecord,
|
|
)
|
|
|
|
def _normalize_provider(value: str) -> str:
|
|
return (value or "disabled").strip().lower()
|
|
|
|
|
|
def _normalize_provider_api(value: str) -> str:
|
|
return (value or "auto").strip().lower().replace("_", "-")
|
|
|
|
|
|
def _resolve_provider_api(provider: str, configured_api: str) -> str:
|
|
if configured_api and configured_api != "auto":
|
|
return configured_api
|
|
|
|
if provider in {
|
|
"openai",
|
|
"openai-compatible",
|
|
"openai_compatible",
|
|
"deepseek",
|
|
"alibaba",
|
|
"moonshotai",
|
|
"glm",
|
|
"zhipuai",
|
|
"meta",
|
|
"gemini",
|
|
"google",
|
|
"grok",
|
|
"xai",
|
|
"openrouter",
|
|
"opencode-go",
|
|
}:
|
|
return "openai-completions"
|
|
if provider in {
|
|
"anthropic",
|
|
"anthropic-compatible",
|
|
"anthropic_compatible",
|
|
"claude-compatible",
|
|
"claude_compatible",
|
|
"minimax",
|
|
"kimi-coding",
|
|
"moonshot-anthropic",
|
|
}:
|
|
return "anthropic-messages"
|
|
if provider == "ollama":
|
|
return "ollama-generate"
|
|
return "disabled"
|
|
|
|
|
|
class ProviderService:
|
|
def __init__(self, overrides: dict[str, Any] | None = None) -> None:
|
|
overrides = overrides or {}
|
|
self.provider = _normalize_provider(overrides.get("provider") or settings.AI_PROVIDER)
|
|
self.provider_api = _resolve_provider_api(
|
|
self.provider,
|
|
_normalize_provider_api(overrides.get("provider_api") or settings.AI_PROVIDER_API),
|
|
)
|
|
self.base_url = str(overrides.get("base_url") or settings.AI_BASE_URL).rstrip("/")
|
|
self.api_key = str(overrides.get("api_key") or settings.AI_API_KEY)
|
|
self.default_model = str(overrides.get("model") or settings.AI_MODEL)
|
|
self.timeout = settings.AI_TIMEOUT_SECONDS
|
|
self.http_retry_attempts = max(settings.AI_HTTP_RETRY_ATTEMPTS, 1)
|
|
self.max_tokens = int(overrides.get("max_tokens") or settings.AI_MAX_TOKENS)
|
|
self.anthropic_version = str(
|
|
overrides.get("anthropic_version") or settings.AI_ANTHROPIC_VERSION
|
|
)
|
|
self.model_provider_apis = self._parse_model_provider_apis(
|
|
overrides.get("model_provider_apis")
|
|
)
|
|
self.session_id = str(uuid4())
|
|
|
|
def get_status(self) -> AIProviderStatusResponse:
|
|
enabled = self.provider != "disabled"
|
|
has_credentials = bool(self.api_key) if self._requires_api_key() else True
|
|
configured = enabled and bool(self.base_url and has_credentials and self.default_model)
|
|
return AIProviderStatusResponse(
|
|
provider=self.provider,
|
|
api=self.provider_api if enabled else None,
|
|
enabled=enabled,
|
|
configured=configured,
|
|
model=self.default_model or None,
|
|
base_url=self.base_url if enabled else None,
|
|
)
|
|
|
|
async def analyze(self, payload: SituationalAnalysisRequest) -> SituationalAnalysisResponse:
|
|
if self.provider == "disabled":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail="AI provider is disabled. Configure AI_PROVIDER in .env to enable analysis.",
|
|
)
|
|
|
|
model = payload.preferred_model or self.default_model
|
|
has_credentials = bool(self.api_key) if self._requires_api_key() else True
|
|
if not self.base_url or not has_credentials or not model:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail="AI provider is not fully configured. Check AI_BASE_URL, AI_API_KEY, and AI_MODEL.",
|
|
)
|
|
|
|
prompt = self._build_prompt(payload)
|
|
conversation_messages = self._build_conversation_messages(payload, prompt)
|
|
if payload.context.get("session_id") is not None:
|
|
self.session_id = str(uuid5(NAMESPACE_URL, f"planet:{payload.context['session_id']}"))
|
|
|
|
provider_api = self._resolve_model_provider_api(model)
|
|
tools = getattr(payload, "tools", None)
|
|
tool_choice = getattr(payload, "tool_choice", None)
|
|
response_format = getattr(payload, "response_format", None)
|
|
native_web_search = bool(getattr(payload, "native_web_search", False))
|
|
images = self._normalize_images(getattr(payload, "images", None))
|
|
tool_calls: list[ToolCallRecord] = []
|
|
citation_urls: list[str] = []
|
|
stop_reason: str | None = None
|
|
|
|
if provider_api == "openai-completions":
|
|
data = await self._request_openai_compatible(
|
|
model,
|
|
prompt,
|
|
payload.system_prompt,
|
|
conversation_messages=conversation_messages,
|
|
tools=tools,
|
|
tool_choice=tool_choice,
|
|
response_format=response_format,
|
|
images=images,
|
|
)
|
|
content = self._extract_openai_content(data)
|
|
content_blocks = self._extract_openai_blocks(data)
|
|
tool_calls = self._extract_openai_tool_calls(data)
|
|
choices = data.get("choices") or []
|
|
if choices and isinstance(choices[0], dict):
|
|
stop_reason = choices[0].get("finish_reason")
|
|
elif provider_api == "openai-responses":
|
|
data = await self._request_openai_responses(
|
|
model,
|
|
prompt,
|
|
payload.system_prompt,
|
|
conversation_messages=conversation_messages,
|
|
tools=tools,
|
|
tool_choice=tool_choice,
|
|
response_format=response_format,
|
|
native_web_search=native_web_search,
|
|
images=images,
|
|
)
|
|
content_blocks = self._extract_responses_blocks(data)
|
|
content = "".join(block.text for block in content_blocks if block.text)
|
|
tool_calls = self._extract_responses_tool_calls(data)
|
|
citation_urls = self._extract_responses_citations(data)
|
|
stop_reason = str(data.get("status") or "") or None
|
|
elif provider_api == "anthropic-messages":
|
|
data = await self._request_anthropic_messages(
|
|
model,
|
|
prompt,
|
|
payload.thinking,
|
|
payload.system_prompt,
|
|
conversation_messages=conversation_messages,
|
|
tools=tools,
|
|
tool_choice=tool_choice,
|
|
response_format=response_format,
|
|
native_web_search=native_web_search,
|
|
images=images,
|
|
)
|
|
content = self._extract_anthropic_content(data)
|
|
content_blocks = self._extract_anthropic_blocks(data)
|
|
tool_calls = self._extract_anthropic_tool_calls(data)
|
|
citation_urls = self._extract_anthropic_citations(data)
|
|
stop_reason = str(data.get("stop_reason") or "") or None
|
|
elif provider_api == "ollama-generate":
|
|
data = await self._request_ollama(
|
|
model,
|
|
prompt,
|
|
payload.system_prompt,
|
|
conversation_messages=conversation_messages,
|
|
response_format=response_format,
|
|
images=images,
|
|
)
|
|
content = self._extract_ollama_content(data)
|
|
content_blocks = self._extract_ollama_blocks(data)
|
|
stop_reason = "stop" if data.get("done") else None
|
|
else:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"Unsupported AI provider API: {self.provider_api}",
|
|
)
|
|
|
|
text_blocks = [block.text for block in content_blocks if block.text]
|
|
thinking_blocks = [block.thinking for block in content_blocks if block.thinking]
|
|
|
|
return SituationalAnalysisResponse(
|
|
provider=self.provider,
|
|
model=model,
|
|
content=content,
|
|
content_blocks=content_blocks,
|
|
text_blocks=text_blocks,
|
|
thinking_blocks=thinking_blocks,
|
|
tool_calls=tool_calls,
|
|
citation_urls=citation_urls,
|
|
stop_reason=stop_reason,
|
|
raw_response=data,
|
|
)
|
|
|
|
async def stream_analyze(
|
|
self,
|
|
payload: SituationalAnalysisRequest,
|
|
) -> AsyncIterator[dict[str, Any]]:
|
|
if self.provider == "disabled":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail="AI provider is disabled. Configure AI_PROVIDER in .env to enable analysis.",
|
|
)
|
|
|
|
model = payload.preferred_model or self.default_model
|
|
has_credentials = bool(self.api_key) if self._requires_api_key() else True
|
|
if not self.base_url or not has_credentials or not model:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail="AI provider is not fully configured. Check AI_BASE_URL, AI_API_KEY, and AI_MODEL.",
|
|
)
|
|
|
|
prompt = self._build_prompt(payload)
|
|
conversation_messages = self._build_conversation_messages(payload, prompt)
|
|
if payload.context.get("session_id") is not None:
|
|
self.session_id = str(uuid5(NAMESPACE_URL, f"planet:{payload.context['session_id']}"))
|
|
|
|
provider_api = self._resolve_model_provider_api(model)
|
|
images = self._normalize_images(getattr(payload, "images", None))
|
|
yield {"event": "start", "provider": self.provider, "model": model}
|
|
|
|
if provider_api == "anthropic-messages":
|
|
async for item in self._stream_anthropic_messages(
|
|
model,
|
|
prompt,
|
|
payload.thinking,
|
|
payload.system_prompt,
|
|
conversation_messages=conversation_messages,
|
|
images=images,
|
|
):
|
|
yield item
|
|
return
|
|
if provider_api == "openai-completions":
|
|
async for item in self._stream_openai_compatible(
|
|
model,
|
|
prompt,
|
|
payload.system_prompt,
|
|
conversation_messages=conversation_messages,
|
|
images=images,
|
|
):
|
|
yield item
|
|
return
|
|
if provider_api == "openai-responses":
|
|
async for item in self._stream_openai_responses(
|
|
model,
|
|
prompt,
|
|
payload.system_prompt,
|
|
conversation_messages=conversation_messages,
|
|
images=images,
|
|
):
|
|
yield item
|
|
return
|
|
if provider_api == "ollama-generate":
|
|
async for item in self._stream_ollama(
|
|
model,
|
|
prompt,
|
|
payload.system_prompt,
|
|
conversation_messages=conversation_messages,
|
|
images=images,
|
|
):
|
|
yield item
|
|
return
|
|
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"Unsupported AI provider API: {self.provider_api}",
|
|
)
|
|
|
|
def _outbound_headers(self, headers: dict[str, str]) -> dict[str, str]:
|
|
merged = {"User-Agent": "Planet/1.0", **headers}
|
|
if self.provider == "opencode-go":
|
|
merged["x-opencode-session"] = self.session_id
|
|
return merged
|
|
|
|
async def _iter_sse_events(
|
|
self,
|
|
response: httpx.Response,
|
|
) -> AsyncIterator[tuple[str, str]]:
|
|
event_name = ""
|
|
data_lines: list[str] = []
|
|
async for raw_line in response.aiter_lines():
|
|
line = raw_line.rstrip("\r")
|
|
if line == "":
|
|
if data_lines:
|
|
yield event_name, "\n".join(data_lines)
|
|
event_name = ""
|
|
data_lines = []
|
|
continue
|
|
if line.startswith(":"):
|
|
continue
|
|
if line.startswith("event:"):
|
|
event_name = line[6:].strip()
|
|
elif line.startswith("data:"):
|
|
data_lines.append(line[5:].lstrip())
|
|
if data_lines:
|
|
yield event_name, "\n".join(data_lines)
|
|
|
|
def _build_anthropic_request(
|
|
self,
|
|
model: str,
|
|
prompt: str,
|
|
thinking: dict[str, Any] | None = None,
|
|
system_prompt: str | None = None,
|
|
*,
|
|
stream: bool = False,
|
|
conversation_messages: list[dict[str, Any]] | None = None,
|
|
tools: list[dict[str, Any]] | None = None,
|
|
tool_choice: str | dict[str, Any] | None = None,
|
|
response_format: dict[str, Any] | None = None,
|
|
native_web_search: bool = False,
|
|
images: list[dict[str, str]] | None = None,
|
|
) -> tuple[str, dict[str, str], dict[str, Any]]:
|
|
anthropic_messages: list[dict[str, Any]] = []
|
|
source_messages = (
|
|
conversation_messages
|
|
if (
|
|
conversation_messages
|
|
and (
|
|
len(conversation_messages) > 1
|
|
or bool(tools)
|
|
or any(
|
|
m.get("role") == "tool" or m.get("tool_calls") or m.get("thinking_blocks")
|
|
for m in conversation_messages
|
|
)
|
|
)
|
|
)
|
|
else [{"role": "user", "content": prompt}]
|
|
)
|
|
for msg in source_messages:
|
|
role = msg.get("role")
|
|
if role == "tool":
|
|
block = {
|
|
"type": "tool_result",
|
|
"tool_use_id": str(msg.get("tool_call_id") or ""),
|
|
"content": str(msg.get("content") or ""),
|
|
}
|
|
if (
|
|
anthropic_messages
|
|
and anthropic_messages[-1]["role"] == "user"
|
|
and isinstance(anthropic_messages[-1]["content"], list)
|
|
and anthropic_messages[-1]["content"]
|
|
and anthropic_messages[-1]["content"][0].get("type") == "tool_result"
|
|
):
|
|
anthropic_messages[-1]["content"].append(block)
|
|
else:
|
|
anthropic_messages.append({"role": "user", "content": [block]})
|
|
continue
|
|
if role == "assistant" and (msg.get("tool_calls") or msg.get("thinking_blocks")):
|
|
blocks: list[dict[str, Any]] = []
|
|
for tb in msg.get("thinking_blocks") or []:
|
|
if not isinstance(tb, dict):
|
|
continue
|
|
t_text = str(tb.get("thinking") or "")
|
|
sig = str(tb.get("signature") or "")
|
|
if t_text and sig:
|
|
blocks.append({"type": "thinking", "thinking": t_text, "signature": sig})
|
|
text = str(msg.get("content") or "").strip()
|
|
if text:
|
|
blocks.append({"type": "text", "text": text})
|
|
for tc in msg.get("tool_calls") or []:
|
|
if not isinstance(tc, dict):
|
|
continue
|
|
blocks.append(
|
|
{
|
|
"type": "tool_use",
|
|
"id": str(tc.get("id") or ""),
|
|
"name": str(tc.get("name") or ""),
|
|
"input": tc.get("arguments") if isinstance(tc.get("arguments"), dict) else {},
|
|
}
|
|
)
|
|
if blocks:
|
|
anthropic_messages.append({"role": "assistant", "content": blocks})
|
|
continue
|
|
anthropic_messages.append(
|
|
{"role": role or "user", "content": [{"type": "text", "text": str(msg.get("content") or "")}]}
|
|
)
|
|
|
|
self._apply_images_to_messages(anthropic_messages, images or [], "anthropic")
|
|
|
|
resolved_thinking, resolved_output_config = self._resolve_anthropic_thinking(thinking, model)
|
|
thinking_active = bool(
|
|
resolved_thinking
|
|
and str(resolved_thinking.get("type") or "").lower() in {"enabled", "adaptive"}
|
|
)
|
|
max_tokens = self.max_tokens
|
|
if resolved_thinking and isinstance(resolved_thinking.get("budget_tokens"), (int, float)):
|
|
budget_tokens = int(resolved_thinking["budget_tokens"])
|
|
if budget_tokens >= max_tokens:
|
|
max_tokens = budget_tokens + 1024
|
|
|
|
request_body: dict[str, Any] = {
|
|
"model": model,
|
|
"messages": anthropic_messages,
|
|
"max_tokens": max_tokens,
|
|
}
|
|
if not thinking_active:
|
|
request_body["temperature"] = 0.2
|
|
if stream:
|
|
request_body["stream"] = True
|
|
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
|
if resolved_system_prompt:
|
|
request_body["system"] = resolved_system_prompt
|
|
if resolved_thinking:
|
|
request_body["thinking"] = resolved_thinking
|
|
if resolved_output_config:
|
|
request_body["output_config"] = resolved_output_config
|
|
elif (
|
|
self.provider == "anthropic"
|
|
and isinstance(response_format, dict)
|
|
and isinstance(response_format.get("json_schema"), dict)
|
|
):
|
|
schema_cfg = response_format["json_schema"]
|
|
schema_obj = schema_cfg.get("schema") if isinstance(schema_cfg.get("schema"), dict) else schema_cfg
|
|
request_body["output_config"] = {
|
|
"format": {
|
|
"type": "json_schema",
|
|
"schema": schema_obj,
|
|
}
|
|
}
|
|
|
|
anthropic_tools: list[dict[str, Any]] = []
|
|
for tool in tools or []:
|
|
if not isinstance(tool, dict) or not tool.get("name"):
|
|
continue
|
|
tool_name = str(tool["name"])
|
|
if native_web_search and tool_name == "web_search":
|
|
continue
|
|
anthropic_tools.append(
|
|
{
|
|
"name": tool_name,
|
|
"description": str(tool.get("description") or ""),
|
|
"input_schema": tool.get("parameters") or {"type": "object", "properties": {}},
|
|
}
|
|
)
|
|
if native_web_search:
|
|
anthropic_tools.append({"type": "web_search_20250305", "name": "web_search", "max_uses": 3})
|
|
if anthropic_tools:
|
|
request_body["tools"] = anthropic_tools
|
|
if isinstance(tool_choice, str):
|
|
if tool_choice == "required":
|
|
request_body["tool_choice"] = {"type": "auto"} if thinking_active else {"type": "any"}
|
|
elif tool_choice == "auto":
|
|
request_body["tool_choice"] = {"type": "auto"}
|
|
elif tool_choice not in {"none", ""}:
|
|
request_body["tool_choice"] = {"type": "auto"} if thinking_active else {"type": "tool", "name": tool_choice}
|
|
elif isinstance(tool_choice, dict) and tool_choice.get("name"):
|
|
request_body["tool_choice"] = (
|
|
{"type": "auto"} if thinking_active else {"type": "tool", "name": str(tool_choice["name"])}
|
|
)
|
|
|
|
path = "/v1/messages" if self.provider == "minimax" and self.base_url.endswith("/anthropic") else "/messages"
|
|
headers = {
|
|
"x-api-key": self.api_key,
|
|
"anthropic-version": self.anthropic_version,
|
|
"Content-Type": "application/json",
|
|
}
|
|
return path, headers, request_body
|
|
|
|
async def _stream_anthropic_messages(
|
|
self,
|
|
model: str,
|
|
prompt: str,
|
|
thinking: dict[str, Any] | None = None,
|
|
system_prompt: str | None = None,
|
|
*,
|
|
conversation_messages: list[dict[str, Any]] | None = None,
|
|
images: list[dict[str, str]] | None = None,
|
|
) -> AsyncIterator[dict[str, Any]]:
|
|
path, headers, request_body = self._build_anthropic_request(
|
|
model,
|
|
prompt,
|
|
thinking,
|
|
system_prompt,
|
|
stream=True,
|
|
conversation_messages=conversation_messages,
|
|
images=images,
|
|
)
|
|
resolved_model = model
|
|
usage: dict[str, Any] = {}
|
|
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
async with client.stream(
|
|
"POST",
|
|
f"{self.base_url}{path}",
|
|
headers=self._outbound_headers(headers),
|
|
json=request_body,
|
|
) as response:
|
|
if response.status_code >= 400:
|
|
detail = (await response.aread()).decode("utf-8", errors="replace")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
|
detail=f"AI provider request failed: {detail or response.status_code}",
|
|
)
|
|
async for event_name, data_str in self._iter_sse_events(response):
|
|
if data_str == "[DONE]":
|
|
continue
|
|
try:
|
|
chunk = json.loads(data_str)
|
|
except json.JSONDecodeError:
|
|
continue
|
|
if not isinstance(chunk, dict):
|
|
continue
|
|
msg_type = str(chunk.get("type") or event_name or "")
|
|
if msg_type == "error":
|
|
err = chunk.get("error") if isinstance(chunk.get("error"), dict) else {}
|
|
raise HTTPException(
|
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
|
detail=str(err.get("message") or chunk.get("message") or "Upstream stream error"),
|
|
)
|
|
if msg_type == "message_start":
|
|
message = chunk.get("message") if isinstance(chunk.get("message"), dict) else {}
|
|
if isinstance(message.get("model"), str) and message["model"]:
|
|
resolved_model = message["model"]
|
|
if isinstance(message.get("usage"), dict):
|
|
usage.update(message["usage"])
|
|
elif msg_type == "message_delta":
|
|
if isinstance(chunk.get("usage"), dict):
|
|
usage.update(chunk["usage"])
|
|
elif msg_type == "content_block_start":
|
|
block = chunk.get("content_block") if isinstance(chunk.get("content_block"), dict) else {}
|
|
if block.get("type") == "thinking" and isinstance(block.get("thinking"), str) and block["thinking"]:
|
|
yield {"event": "reasoning", "delta": block["thinking"]}
|
|
elif block.get("type") == "text" and isinstance(block.get("text"), str) and block["text"]:
|
|
yield {"event": "text", "delta": block["text"]}
|
|
elif msg_type == "content_block_delta":
|
|
delta = chunk.get("delta") if isinstance(chunk.get("delta"), dict) else {}
|
|
delta_type = str(delta.get("type") or "")
|
|
if delta_type == "thinking_delta" and isinstance(delta.get("thinking"), str) and delta["thinking"]:
|
|
yield {"event": "reasoning", "delta": delta["thinking"]}
|
|
elif delta_type == "text_delta" and isinstance(delta.get("text"), str) and delta["text"]:
|
|
yield {"event": "text", "delta": delta["text"]}
|
|
yield {"event": "done", "provider": self.provider, "model": resolved_model, "usage": usage}
|
|
|
|
async def _stream_openai_compatible(
|
|
self,
|
|
model: str,
|
|
prompt: str,
|
|
system_prompt: str | None = None,
|
|
*,
|
|
conversation_messages: list[dict[str, Any]] | None = None,
|
|
images: list[dict[str, str]] | None = None,
|
|
) -> AsyncIterator[dict[str, Any]]:
|
|
messages: list[dict[str, Any]] = []
|
|
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
|
if resolved_system_prompt:
|
|
messages.append({"role": "system", "content": resolved_system_prompt})
|
|
if conversation_messages and len(conversation_messages) > 1:
|
|
messages.extend(dict(m) for m in conversation_messages)
|
|
else:
|
|
messages.append({"role": "user", "content": prompt})
|
|
self._apply_images_to_messages(messages, images or [], "openai-completions")
|
|
request_body = {
|
|
"model": model,
|
|
"messages": messages,
|
|
"temperature": 0.2,
|
|
"max_tokens": self.max_tokens,
|
|
"stream": True,
|
|
"stream_options": {"include_usage": True},
|
|
}
|
|
resolved_model = model
|
|
usage: dict[str, Any] = {}
|
|
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
async with client.stream(
|
|
"POST",
|
|
f"{self.base_url}/chat/completions",
|
|
headers=self._outbound_headers(
|
|
{"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
|
|
),
|
|
json=request_body,
|
|
) as response:
|
|
if response.status_code >= 400:
|
|
detail = (await response.aread()).decode("utf-8", errors="replace")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
|
detail=f"AI provider request failed: {detail or response.status_code}",
|
|
)
|
|
async for _, data_str in self._iter_sse_events(response):
|
|
if data_str == "[DONE]":
|
|
break
|
|
try:
|
|
chunk = json.loads(data_str)
|
|
except json.JSONDecodeError:
|
|
continue
|
|
if not isinstance(chunk, dict):
|
|
continue
|
|
if isinstance(chunk.get("model"), str) and chunk["model"]:
|
|
resolved_model = chunk["model"]
|
|
if isinstance(chunk.get("usage"), dict):
|
|
usage.update(chunk["usage"])
|
|
choices = chunk.get("choices") or []
|
|
if not choices or not isinstance(choices[0], dict):
|
|
continue
|
|
delta = choices[0].get("delta") if isinstance(choices[0].get("delta"), dict) else {}
|
|
for r_key in ("reasoning_content", "reasoning", "thinking"):
|
|
r_val = delta.get(r_key)
|
|
if isinstance(r_val, str) and r_val:
|
|
yield {"event": "reasoning", "delta": r_val}
|
|
break
|
|
text_val = delta.get("content")
|
|
if isinstance(text_val, str) and text_val:
|
|
yield {"event": "text", "delta": text_val}
|
|
yield {"event": "done", "provider": self.provider, "model": resolved_model, "usage": usage}
|
|
|
|
async def _stream_openai_responses(
|
|
self,
|
|
model: str,
|
|
prompt: str,
|
|
system_prompt: str | None = None,
|
|
*,
|
|
conversation_messages: list[dict[str, Any]] | None = None,
|
|
images: list[dict[str, str]] | None = None,
|
|
) -> AsyncIterator[dict[str, Any]]:
|
|
responses_input: Any = (
|
|
[{"role": m["role"], "content": m["content"]} for m in conversation_messages]
|
|
if (conversation_messages and len(conversation_messages) > 1)
|
|
else prompt
|
|
)
|
|
responses_input = self._apply_images_to_responses_input(responses_input, images or [])
|
|
request_body: dict[str, Any] = {
|
|
"model": model,
|
|
"input": responses_input,
|
|
"max_output_tokens": self.max_tokens,
|
|
"store": False,
|
|
"stream": True,
|
|
}
|
|
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
|
if resolved_system_prompt:
|
|
request_body["instructions"] = resolved_system_prompt
|
|
resolved_model = model
|
|
usage: dict[str, Any] = {}
|
|
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
async with client.stream(
|
|
"POST",
|
|
f"{self.base_url}/responses",
|
|
headers=self._outbound_headers(
|
|
{"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
|
|
),
|
|
json=request_body,
|
|
) as response:
|
|
if response.status_code >= 400:
|
|
detail = (await response.aread()).decode("utf-8", errors="replace")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
|
detail=f"AI provider request failed: {detail or response.status_code}",
|
|
)
|
|
async for event_name, data_str in self._iter_sse_events(response):
|
|
if data_str == "[DONE]":
|
|
break
|
|
try:
|
|
chunk = json.loads(data_str)
|
|
except json.JSONDecodeError:
|
|
continue
|
|
if not isinstance(chunk, dict):
|
|
continue
|
|
ev_type = str(chunk.get("type") or event_name or "")
|
|
if ev_type == "response.output_text.delta" and isinstance(chunk.get("delta"), str) and chunk["delta"]:
|
|
yield {"event": "text", "delta": chunk["delta"]}
|
|
elif ("reasoning" in ev_type or "thinking" in ev_type) and isinstance(chunk.get("delta"), str) and chunk["delta"]:
|
|
yield {"event": "reasoning", "delta": chunk["delta"]}
|
|
elif ev_type == "response.completed":
|
|
resp_obj = chunk.get("response") if isinstance(chunk.get("response"), dict) else {}
|
|
if isinstance(resp_obj.get("model"), str) and resp_obj["model"]:
|
|
resolved_model = resp_obj["model"]
|
|
if isinstance(resp_obj.get("usage"), dict):
|
|
usage.update(resp_obj["usage"])
|
|
yield {"event": "done", "provider": self.provider, "model": resolved_model, "usage": usage}
|
|
|
|
async def _stream_ollama(
|
|
self,
|
|
model: str,
|
|
prompt: str,
|
|
system_prompt: str | None = None,
|
|
*,
|
|
conversation_messages: list[dict[str, Any]] | None = None,
|
|
images: list[dict[str, str]] | None = None,
|
|
) -> AsyncIterator[dict[str, Any]]:
|
|
ollama_prompt = self._format_ollama_prompt(prompt, conversation_messages)
|
|
request_body: dict[str, Any] = {
|
|
"model": model,
|
|
"stream": True,
|
|
"prompt": ollama_prompt,
|
|
"options": {"temperature": 0.2, "num_predict": self.max_tokens},
|
|
}
|
|
if images:
|
|
request_body["images"] = [img["data_base64"] for img in images if img.get("data_base64")]
|
|
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
|
if resolved_system_prompt:
|
|
request_body["system"] = resolved_system_prompt
|
|
usage: dict[str, Any] = {}
|
|
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
async with client.stream(
|
|
"POST",
|
|
f"{self.base_url}/api/generate",
|
|
headers=self._outbound_headers({"Content-Type": "application/json"}),
|
|
json=request_body,
|
|
) as response:
|
|
if response.status_code >= 400:
|
|
detail = (await response.aread()).decode("utf-8", errors="replace")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
|
detail=f"AI provider request failed: {detail or response.status_code}",
|
|
)
|
|
async for line in response.aiter_lines():
|
|
if not line.strip():
|
|
continue
|
|
try:
|
|
chunk = json.loads(line)
|
|
except json.JSONDecodeError:
|
|
continue
|
|
if isinstance(chunk.get("thinking"), str) and chunk["thinking"]:
|
|
yield {"event": "reasoning", "delta": chunk["thinking"]}
|
|
if isinstance(chunk.get("response"), str) and chunk["response"]:
|
|
yield {"event": "text", "delta": chunk["response"]}
|
|
yield {"event": "done", "provider": self.provider, "model": model, "usage": usage}
|
|
|
|
def _requires_api_key(self) -> bool:
|
|
return self.provider_api != "ollama-generate"
|
|
|
|
def _resolve_model_provider_api(self, model: str) -> str:
|
|
return self.model_provider_apis.get(model) or self.provider_api
|
|
|
|
def _parse_model_provider_apis(self, value: Any) -> dict[str, str]:
|
|
if isinstance(value, dict):
|
|
raw = value
|
|
elif isinstance(value, str) and value.strip():
|
|
try:
|
|
parsed = json.loads(value)
|
|
except json.JSONDecodeError:
|
|
return {}
|
|
raw = parsed if isinstance(parsed, dict) else {}
|
|
else:
|
|
raw = {}
|
|
return {
|
|
str(model): _normalize_provider_api(str(provider_api))
|
|
for model, provider_api in raw.items()
|
|
if model and provider_api
|
|
}
|
|
|
|
def _build_conversation_messages(
|
|
self,
|
|
payload: SituationalAnalysisRequest,
|
|
final_prompt: str,
|
|
) -> list[dict[str, Any]]:
|
|
"""Normalize multi-turn history + current prompt (including tool turns) into messages."""
|
|
raw_items = getattr(payload, "messages", None) or []
|
|
has_tool_turns = any(
|
|
(
|
|
str(
|
|
getattr(item, "role", None)
|
|
or (item.get("role") if isinstance(item, dict) else "")
|
|
).strip().lower()
|
|
== "tool"
|
|
or bool(
|
|
getattr(item, "tool_calls", None)
|
|
if not isinstance(item, dict)
|
|
else item.get("tool_calls")
|
|
)
|
|
or bool(
|
|
getattr(item, "thinking_blocks", None)
|
|
if not isinstance(item, dict)
|
|
else item.get("thinking_blocks")
|
|
)
|
|
)
|
|
for item in raw_items
|
|
)
|
|
if raw_items and (has_tool_turns or getattr(payload, "tools", None)):
|
|
preserved: list[dict[str, Any]] = []
|
|
for item in raw_items:
|
|
if isinstance(item, dict):
|
|
role = str(item.get("role") or "").strip().lower()
|
|
content = str(item.get("content") or "")
|
|
tool_call_id = item.get("tool_call_id")
|
|
name = item.get("name")
|
|
tool_calls = item.get("tool_calls")
|
|
thinking_blocks = item.get("thinking_blocks")
|
|
else:
|
|
role = str(getattr(item, "role", "") or "").strip().lower()
|
|
content = str(getattr(item, "content", "") or "")
|
|
tool_call_id = getattr(item, "tool_call_id", None)
|
|
name = getattr(item, "name", None)
|
|
tool_calls = getattr(item, "tool_calls", None)
|
|
thinking_blocks = getattr(item, "thinking_blocks", None)
|
|
if role not in {"user", "assistant", "tool"}:
|
|
continue
|
|
entry: dict[str, Any] = {"role": role, "content": content}
|
|
if tool_call_id:
|
|
entry["tool_call_id"] = str(tool_call_id)
|
|
if name:
|
|
entry["name"] = str(name)
|
|
if tool_calls:
|
|
entry["tool_calls"] = list(tool_calls)
|
|
if thinking_blocks:
|
|
entry["thinking_blocks"] = list(thinking_blocks)
|
|
preserved.append(entry)
|
|
return preserved or [{"role": "user", "content": final_prompt}]
|
|
|
|
normalized: list[dict[str, Any]] = []
|
|
for item in raw_items:
|
|
role = str(getattr(item, "role", None) or (item.get("role") if isinstance(item, dict) else "")).strip().lower()
|
|
content = str(getattr(item, "content", None) or (item.get("content") if isinstance(item, dict) else "")).strip()
|
|
if role not in {"user", "assistant"} or not content:
|
|
continue
|
|
if not normalized and role == "assistant":
|
|
continue
|
|
if normalized and normalized[-1]["role"] == role:
|
|
normalized[-1]["content"] = f"{normalized[-1]['content']}\n\n{content}"
|
|
else:
|
|
normalized.append({"role": role, "content": content})
|
|
|
|
if normalized and normalized[-1]["role"] == "user":
|
|
normalized[-1]["content"] = f"{normalized[-1]['content']}\n\n{final_prompt}"
|
|
else:
|
|
normalized.append({"role": "user", "content": final_prompt})
|
|
return normalized
|
|
|
|
@staticmethod
|
|
def _format_ollama_prompt(
|
|
prompt: str,
|
|
conversation_messages: list[dict[str, Any]] | None,
|
|
) -> str:
|
|
if not conversation_messages or len(conversation_messages) <= 1:
|
|
return prompt
|
|
history_lines = []
|
|
for m in conversation_messages[:-1]:
|
|
prefix = "用户" if m.get("role") == "user" else "助手"
|
|
history_lines.append(f"{prefix}: {m.get('content', '')}")
|
|
return "历史对话:\n" + "\n".join(history_lines) + f"\n\n当前任务:\n{conversation_messages[-1].get('content', prompt)}"
|
|
|
|
def _build_prompt(self, payload: SituationalAnalysisRequest) -> str:
|
|
sections = [
|
|
f"任务标题:\n{payload.title}",
|
|
f"分析目标:\n{payload.objective}",
|
|
]
|
|
if payload.observations:
|
|
sections.append("观测事实:\n" + "\n".join(f"- {item}" for item in payload.observations))
|
|
if payload.constraints:
|
|
sections.append("约束条件:\n" + "\n".join(f"- {item}" for item in payload.constraints))
|
|
if payload.context:
|
|
context_json = json.dumps(payload.context, ensure_ascii=False, default=str)
|
|
sections.append(f"附加上下文:\n{context_json}")
|
|
return "\n\n".join(sections)
|
|
|
|
@staticmethod
|
|
def _normalize_images(images: list[Any] | None) -> list[dict[str, str]]:
|
|
normalized: list[dict[str, str]] = []
|
|
for raw in images or []:
|
|
if isinstance(raw, dict):
|
|
mime = str(raw.get("mime_type") or "").strip().lower()
|
|
data = str(raw.get("data_base64") or "").strip()
|
|
name = str(raw.get("name") or "").strip()
|
|
else:
|
|
mime = str(getattr(raw, "mime_type", "") or "").strip().lower()
|
|
data = str(getattr(raw, "data_base64", "") or "").strip()
|
|
name = str(getattr(raw, "name", "") or "").strip()
|
|
if mime == "image/jpg":
|
|
mime = "image/jpeg"
|
|
if not mime.startswith("image/") or not data:
|
|
continue
|
|
normalized.append({"mime_type": mime, "data_base64": data, "name": name})
|
|
if len(normalized) >= 8:
|
|
break
|
|
return normalized
|
|
|
|
@staticmethod
|
|
def _apply_images_to_messages(
|
|
messages: list[dict[str, Any]],
|
|
images: list[dict[str, str]],
|
|
api_style: str,
|
|
) -> None:
|
|
"""Attach base64 images onto the final user turn for Anthropic or OpenAI chat payloads."""
|
|
if not images or not messages:
|
|
return
|
|
for idx in range(len(messages) - 1, -1, -1):
|
|
if messages[idx].get("role") != "user":
|
|
continue
|
|
if api_style == "anthropic":
|
|
content = messages[idx].get("content")
|
|
blocks = list(content) if isinstance(content, list) else [{"type": "text", "text": str(content or "")}]
|
|
for img in images:
|
|
blocks.append(
|
|
{
|
|
"type": "image",
|
|
"source": {
|
|
"type": "base64",
|
|
"media_type": img["mime_type"],
|
|
"data": img["data_base64"],
|
|
},
|
|
}
|
|
)
|
|
messages[idx]["content"] = blocks
|
|
else:
|
|
text = str(messages[idx].get("content") or "")
|
|
blocks = [{"type": "text", "text": text}]
|
|
for img in images:
|
|
blocks.append(
|
|
{
|
|
"type": "image_url",
|
|
"image_url": {"url": f"data:{img['mime_type']};base64,{img['data_base64']}"},
|
|
}
|
|
)
|
|
messages[idx]["content"] = blocks
|
|
break
|
|
|
|
@staticmethod
|
|
def _apply_images_to_responses_input(
|
|
responses_input: Any,
|
|
images: list[dict[str, str]],
|
|
) -> Any:
|
|
"""Attach base64 images onto OpenAI Responses API input items."""
|
|
if not images:
|
|
return responses_input
|
|
image_blocks = [
|
|
{
|
|
"type": "input_image",
|
|
"image_url": f"data:{img['mime_type']};base64,{img['data_base64']}",
|
|
}
|
|
for img in images
|
|
]
|
|
if isinstance(responses_input, str):
|
|
return [
|
|
{
|
|
"role": "user",
|
|
"content": [{"type": "input_text", "text": responses_input}, *image_blocks],
|
|
}
|
|
]
|
|
if isinstance(responses_input, list):
|
|
items = [dict(item) if isinstance(item, dict) else item for item in responses_input]
|
|
for idx in range(len(items) - 1, -1, -1):
|
|
item = items[idx]
|
|
if isinstance(item, dict) and item.get("role") == "user":
|
|
text = str(item.get("content") or "")
|
|
item["content"] = [{"type": "input_text", "text": text}, *image_blocks]
|
|
break
|
|
return items
|
|
return responses_input
|
|
|
|
def _resolve_system_prompt(self, system_prompt: str | None) -> str | None:
|
|
resolved = str(system_prompt or "").strip()
|
|
return resolved or None
|
|
|
|
async def _request_openai_compatible(
|
|
self,
|
|
model: str,
|
|
prompt: str,
|
|
system_prompt: str | None = None,
|
|
*,
|
|
conversation_messages: list[dict[str, Any]] | None = None,
|
|
tools: list[dict[str, Any]] | None = None,
|
|
tool_choice: str | dict[str, Any] | None = None,
|
|
response_format: dict[str, Any] | None = None,
|
|
images: list[dict[str, str]] | None = None,
|
|
) -> dict[str, Any]:
|
|
messages: list[dict[str, Any]] = []
|
|
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
|
if resolved_system_prompt:
|
|
messages.append({"role": "system", "content": resolved_system_prompt})
|
|
source_messages = (
|
|
conversation_messages
|
|
if (
|
|
conversation_messages
|
|
and (
|
|
len(conversation_messages) > 1
|
|
or bool(tools)
|
|
or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages)
|
|
)
|
|
)
|
|
else [{"role": "user", "content": prompt}]
|
|
)
|
|
for msg in source_messages:
|
|
role = msg.get("role") or "user"
|
|
if role == "tool":
|
|
messages.append(
|
|
{
|
|
"role": "tool",
|
|
"tool_call_id": str(msg.get("tool_call_id") or ""),
|
|
"content": str(msg.get("content") or ""),
|
|
}
|
|
)
|
|
elif role == "assistant" and msg.get("tool_calls"):
|
|
openai_tcs = []
|
|
for tc in msg.get("tool_calls") or []:
|
|
if not isinstance(tc, dict):
|
|
continue
|
|
args = tc.get("arguments")
|
|
args_str = args if isinstance(args, str) else json.dumps(args or {}, ensure_ascii=False)
|
|
openai_tcs.append(
|
|
{
|
|
"id": str(tc.get("id") or ""),
|
|
"type": "function",
|
|
"function": {
|
|
"name": str(tc.get("name") or ""),
|
|
"arguments": args_str,
|
|
},
|
|
}
|
|
)
|
|
messages.append(
|
|
{
|
|
"role": "assistant",
|
|
"content": msg.get("content") or "",
|
|
"tool_calls": openai_tcs,
|
|
}
|
|
)
|
|
else:
|
|
messages.append({"role": role, "content": str(msg.get("content") or "")})
|
|
|
|
self._apply_images_to_messages(messages, images or [], "openai-completions")
|
|
|
|
request_body: dict[str, Any] = {
|
|
"model": model,
|
|
"messages": messages,
|
|
"temperature": 0.2,
|
|
"max_tokens": self.max_tokens,
|
|
}
|
|
if tools:
|
|
request_body["tools"] = [
|
|
{
|
|
"type": "function",
|
|
"function": {
|
|
"name": str(t["name"]),
|
|
"description": str(t.get("description") or ""),
|
|
"parameters": t.get("parameters") or {"type": "object", "properties": {}},
|
|
},
|
|
}
|
|
for t in tools
|
|
if isinstance(t, dict) and t.get("name")
|
|
]
|
|
if tool_choice:
|
|
if isinstance(tool_choice, str) and tool_choice in {"auto", "required", "none"}:
|
|
request_body["tool_choice"] = tool_choice
|
|
elif isinstance(tool_choice, dict) and tool_choice.get("name"):
|
|
request_body["tool_choice"] = {
|
|
"type": "function",
|
|
"function": {"name": str(tool_choice["name"])},
|
|
}
|
|
elif isinstance(tool_choice, str):
|
|
request_body["tool_choice"] = {
|
|
"type": "function",
|
|
"function": {"name": tool_choice},
|
|
}
|
|
if isinstance(response_format, dict) and response_format:
|
|
request_body["response_format"] = response_format
|
|
|
|
return await self._post(
|
|
path="/chat/completions",
|
|
headers={
|
|
"Authorization": f"Bearer {self.api_key}",
|
|
"Content-Type": "application/json",
|
|
},
|
|
request_body=request_body,
|
|
)
|
|
|
|
async def _request_openai_responses(
|
|
self,
|
|
model: str,
|
|
prompt: str,
|
|
system_prompt: str | None = None,
|
|
*,
|
|
conversation_messages: list[dict[str, Any]] | None = None,
|
|
tools: list[dict[str, Any]] | None = None,
|
|
tool_choice: str | dict[str, Any] | None = None,
|
|
response_format: dict[str, Any] | None = None,
|
|
native_web_search: bool = False,
|
|
images: list[dict[str, str]] | None = None,
|
|
) -> dict[str, Any]:
|
|
has_multi_or_tools = bool(
|
|
conversation_messages
|
|
and (
|
|
len(conversation_messages) > 1
|
|
or bool(tools)
|
|
or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages)
|
|
)
|
|
)
|
|
if has_multi_or_tools and conversation_messages:
|
|
responses_items: list[dict[str, Any]] = []
|
|
for msg in conversation_messages:
|
|
role = msg.get("role") or "user"
|
|
if role == "tool":
|
|
responses_items.append(
|
|
{
|
|
"type": "function_call_output",
|
|
"call_id": str(msg.get("tool_call_id") or ""),
|
|
"output": str(msg.get("content") or ""),
|
|
}
|
|
)
|
|
elif role == "assistant" and msg.get("tool_calls"):
|
|
text_val = str(msg.get("content") or "").strip()
|
|
if text_val:
|
|
responses_items.append({"role": "assistant", "content": text_val})
|
|
for tc in msg.get("tool_calls") or []:
|
|
if not isinstance(tc, dict):
|
|
continue
|
|
args = tc.get("arguments")
|
|
args_str = args if isinstance(args, str) else json.dumps(args or {}, ensure_ascii=False)
|
|
responses_items.append(
|
|
{
|
|
"type": "function_call",
|
|
"call_id": str(tc.get("id") or ""),
|
|
"name": str(tc.get("name") or ""),
|
|
"arguments": args_str,
|
|
}
|
|
)
|
|
else:
|
|
responses_items.append({"role": role, "content": str(msg.get("content") or "")})
|
|
responses_input: Any = responses_items
|
|
else:
|
|
responses_input = prompt
|
|
|
|
responses_input = self._apply_images_to_responses_input(responses_input, images or [])
|
|
|
|
request_body: dict[str, Any] = {
|
|
"model": model,
|
|
"input": responses_input,
|
|
"max_output_tokens": self.max_tokens,
|
|
"store": False,
|
|
}
|
|
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
|
if resolved_system_prompt:
|
|
request_body["instructions"] = resolved_system_prompt
|
|
|
|
responses_tools: list[dict[str, Any]] = []
|
|
if native_web_search:
|
|
responses_tools.append({"type": "web_search"})
|
|
for t in tools or []:
|
|
if not isinstance(t, dict) or not t.get("name"):
|
|
continue
|
|
responses_tools.append(
|
|
{
|
|
"type": "function",
|
|
"name": str(t["name"]),
|
|
"description": str(t.get("description") or ""),
|
|
"parameters": t.get("parameters") or {"type": "object", "properties": {}},
|
|
}
|
|
)
|
|
if responses_tools:
|
|
request_body["tools"] = responses_tools
|
|
if isinstance(tool_choice, str) and tool_choice:
|
|
if tool_choice in {"auto", "required", "none"}:
|
|
request_body["tool_choice"] = tool_choice
|
|
else:
|
|
request_body["tool_choice"] = {"type": "function", "name": tool_choice}
|
|
elif isinstance(tool_choice, dict) and tool_choice.get("name"):
|
|
request_body["tool_choice"] = {"type": "function", "name": str(tool_choice["name"])}
|
|
|
|
if isinstance(response_format, dict) and response_format:
|
|
rf_type = str(response_format.get("type") or "").strip()
|
|
if rf_type == "json_schema" and isinstance(response_format.get("json_schema"), dict):
|
|
js = response_format["json_schema"]
|
|
request_body["text"] = {
|
|
"format": {
|
|
"type": "json_schema",
|
|
"name": str(js.get("name") or "structured_output"),
|
|
"schema": js.get("schema") if isinstance(js.get("schema"), dict) else js,
|
|
"strict": bool(js.get("strict", True)),
|
|
}
|
|
}
|
|
elif rf_type == "json_object":
|
|
request_body["text"] = {"format": {"type": "json_object"}}
|
|
|
|
return await self._post(
|
|
path="/responses",
|
|
headers={"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"},
|
|
request_body=request_body,
|
|
)
|
|
|
|
def _extract_responses_blocks(self, payload: dict[str, Any]) -> list[AIContentBlock]:
|
|
blocks: list[AIContentBlock] = []
|
|
for item in payload.get("output") or []:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
if item.get("type") == "message":
|
|
for part in item.get("content") or []:
|
|
if not isinstance(part, dict):
|
|
continue
|
|
text = part.get("text") or part.get("refusal")
|
|
if isinstance(text, str) and text:
|
|
blocks.append(AIContentBlock(type="text", text=text))
|
|
elif item.get("type") == "reasoning":
|
|
for part in item.get("summary") or []:
|
|
if isinstance(part, dict) and isinstance(part.get("text"), str):
|
|
blocks.append(AIContentBlock(type="thinking", thinking=part["text"]))
|
|
return blocks
|
|
|
|
async def _request_anthropic_messages(
|
|
self,
|
|
model: str,
|
|
prompt: str,
|
|
thinking: dict[str, Any] | None = None,
|
|
system_prompt: str | None = None,
|
|
*,
|
|
conversation_messages: list[dict[str, Any]] | None = None,
|
|
tools: list[dict[str, Any]] | None = None,
|
|
tool_choice: str | dict[str, Any] | None = None,
|
|
response_format: dict[str, Any] | None = None,
|
|
native_web_search: bool = False,
|
|
images: list[dict[str, str]] | None = None,
|
|
) -> dict[str, Any]:
|
|
path, headers, request_body = self._build_anthropic_request(
|
|
model,
|
|
prompt,
|
|
thinking,
|
|
system_prompt,
|
|
stream=False,
|
|
conversation_messages=conversation_messages,
|
|
tools=tools,
|
|
tool_choice=tool_choice,
|
|
response_format=response_format,
|
|
native_web_search=native_web_search,
|
|
images=images,
|
|
)
|
|
return await self._post(
|
|
path=path,
|
|
headers=headers,
|
|
request_body=request_body,
|
|
)
|
|
|
|
def _resolve_anthropic_thinking(
|
|
self,
|
|
thinking: dict[str, Any] | None,
|
|
model: str,
|
|
) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
|
|
normalized_model = (model or "").casefold()
|
|
is_minimax_m3 = normalized_model.startswith("minimax-m3")
|
|
is_minimax_m31 = "m3.1" in normalized_model and is_minimax_m3
|
|
|
|
if thinking:
|
|
thinking_body = dict(thinking)
|
|
effort = thinking_body.pop("effort", None)
|
|
if is_minimax_m3 and thinking_body.get("type") in {"enabled", "disabled", None}:
|
|
thinking_body["type"] = "adaptive"
|
|
if not effort and is_minimax_m31 and self.max_tokens <= 4096:
|
|
effort = "low"
|
|
output_config = {"effort": str(effort)} if effort else None
|
|
return (thinking_body or None), output_config
|
|
|
|
if is_minimax_m3:
|
|
output_config = {"effort": "low"} if is_minimax_m31 else None
|
|
return {"type": "adaptive"}, output_config
|
|
|
|
# OpenClaw treats MiniMax's Anthropic-compatible path specially:
|
|
# disable thinking by default on non-M3 models unless the caller explicitly opts in.
|
|
if self.provider == "minimax":
|
|
return {"type": "disabled"}, None
|
|
|
|
return None, None
|
|
|
|
async def _request_anthropic_compatible(
|
|
self,
|
|
model: str,
|
|
prompt: str,
|
|
thinking: dict[str, Any] | None = None,
|
|
system_prompt: str | None = None,
|
|
) -> dict[str, Any]:
|
|
return await self._request_anthropic_messages(model, prompt, thinking, system_prompt)
|
|
|
|
async def _request_ollama(
|
|
self,
|
|
model: str,
|
|
prompt: str,
|
|
system_prompt: str | None = None,
|
|
*,
|
|
conversation_messages: list[dict[str, Any]] | None = None,
|
|
response_format: dict[str, Any] | None = None,
|
|
images: list[dict[str, str]] | None = None,
|
|
) -> dict[str, Any]:
|
|
request_body: dict[str, Any] = {
|
|
"model": model,
|
|
"stream": False,
|
|
"prompt": self._format_ollama_prompt(prompt, conversation_messages),
|
|
"options": {
|
|
"temperature": 0.2,
|
|
"num_predict": self.max_tokens,
|
|
},
|
|
}
|
|
if images:
|
|
request_body["images"] = [img["data_base64"] for img in images if img.get("data_base64")]
|
|
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
|
if resolved_system_prompt:
|
|
request_body["system"] = resolved_system_prompt
|
|
if isinstance(response_format, dict) and response_format:
|
|
if isinstance(response_format.get("json_schema"), dict):
|
|
js = response_format["json_schema"]
|
|
request_body["format"] = js.get("schema") if isinstance(js.get("schema"), dict) else "json"
|
|
else:
|
|
request_body["format"] = "json"
|
|
return await self._post(
|
|
path="/api/generate",
|
|
headers={
|
|
"Content-Type": "application/json",
|
|
},
|
|
request_body=request_body,
|
|
)
|
|
|
|
async def _post(
|
|
self,
|
|
path: str,
|
|
headers: dict[str, str],
|
|
request_body: dict[str, Any],
|
|
) -> dict[str, Any]:
|
|
headers = {"User-Agent": "Planet/1.0", **headers}
|
|
if self.provider == "opencode-go":
|
|
headers["x-opencode-session"] = self.session_id
|
|
last_error: Exception | None = None
|
|
for attempt in range(1, self.http_retry_attempts + 1):
|
|
try:
|
|
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
response = await client.post(
|
|
f"{self.base_url}{path}",
|
|
headers=headers,
|
|
json=request_body,
|
|
)
|
|
response.raise_for_status()
|
|
return response.json()
|
|
except httpx.HTTPStatusError as exc:
|
|
last_error = exc
|
|
if attempt < self.http_retry_attempts and exc.response.status_code >= 500:
|
|
await asyncio.sleep(0.3 * attempt)
|
|
continue
|
|
detail = exc.response.text or "AI provider returned an error"
|
|
raise HTTPException(
|
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
|
detail=f"AI provider request failed: {detail}",
|
|
) from exc
|
|
except httpx.HTTPError as exc:
|
|
last_error = exc
|
|
if attempt < self.http_retry_attempts:
|
|
await asyncio.sleep(0.3 * attempt)
|
|
continue
|
|
raise HTTPException(
|
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
|
detail=f"Failed to reach AI provider: {exc}",
|
|
) from exc
|
|
|
|
raise HTTPException(
|
|
status_code=status.HTTP_502_BAD_GATEWAY,
|
|
detail=f"AI provider request failed: {last_error}",
|
|
)
|
|
|
|
def _extract_openai_content(self, payload: dict[str, Any]) -> str:
|
|
choices = payload.get("choices") or []
|
|
if not choices:
|
|
return ""
|
|
|
|
message = choices[0].get("message") or {}
|
|
content = message.get("content")
|
|
if isinstance(content, str):
|
|
if content:
|
|
return content
|
|
reasoning_content = message.get("reasoning_content")
|
|
return reasoning_content if isinstance(reasoning_content, str) else ""
|
|
if isinstance(content, list):
|
|
return "".join(
|
|
item.get("text", "")
|
|
for item in content
|
|
if isinstance(item, dict)
|
|
)
|
|
reasoning_content = message.get("reasoning_content")
|
|
if isinstance(reasoning_content, str):
|
|
return reasoning_content
|
|
return ""
|
|
|
|
def _extract_openai_blocks(self, payload: dict[str, Any]) -> list[AIContentBlock]:
|
|
choices = payload.get("choices") or []
|
|
if not choices:
|
|
return []
|
|
|
|
message = choices[0].get("message") or {}
|
|
content = message.get("content")
|
|
if isinstance(content, str):
|
|
blocks = [AIContentBlock(type="text", text=content)] if content else []
|
|
reasoning_content = message.get("reasoning_content")
|
|
if isinstance(reasoning_content, str) and reasoning_content:
|
|
blocks.append(AIContentBlock(type="thinking", thinking=reasoning_content))
|
|
return blocks
|
|
if not isinstance(content, list):
|
|
reasoning_content = message.get("reasoning_content")
|
|
return [AIContentBlock(type="thinking", thinking=reasoning_content)] if isinstance(reasoning_content, str) and reasoning_content else []
|
|
|
|
blocks: list[AIContentBlock] = []
|
|
for item in content:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
blocks.append(
|
|
AIContentBlock(
|
|
type=str(item.get("type", "text")),
|
|
text=item.get("text") if isinstance(item.get("text"), str) else None,
|
|
metadata={k: v for k, v in item.items() if k not in {"type", "text"}},
|
|
)
|
|
)
|
|
reasoning_content = message.get("reasoning_content")
|
|
if isinstance(reasoning_content, str) and reasoning_content:
|
|
blocks.append(AIContentBlock(type="thinking", thinking=reasoning_content))
|
|
return blocks
|
|
|
|
def _extract_anthropic_content(self, payload: dict[str, Any]) -> str:
|
|
content = payload.get("content")
|
|
if isinstance(content, str):
|
|
return content
|
|
if not isinstance(content, list):
|
|
return ""
|
|
|
|
fragments: list[str] = []
|
|
for item in content:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
if item.get("type") == "text" and isinstance(item.get("text"), str):
|
|
fragments.append(item["text"])
|
|
return "".join(fragments)
|
|
|
|
def _extract_anthropic_blocks(self, payload: dict[str, Any]) -> list[AIContentBlock]:
|
|
content = payload.get("content")
|
|
if not isinstance(content, list):
|
|
return []
|
|
|
|
blocks: list[AIContentBlock] = []
|
|
for item in content:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
blocks.append(
|
|
AIContentBlock(
|
|
type=str(item.get("type", "unknown")),
|
|
text=item.get("text") if isinstance(item.get("text"), str) else None,
|
|
thinking=item.get("thinking") if isinstance(item.get("thinking"), str) else None,
|
|
signature=item.get("signature") if isinstance(item.get("signature"), str) else None,
|
|
metadata={
|
|
k: v
|
|
for k, v in item.items()
|
|
if k not in {"type", "text", "thinking", "signature"}
|
|
},
|
|
)
|
|
)
|
|
return blocks
|
|
|
|
|
|
def _extract_ollama_content(self, payload: dict[str, Any]) -> str:
|
|
response = payload.get("response")
|
|
if isinstance(response, str):
|
|
return response
|
|
return ""
|
|
|
|
def _extract_ollama_blocks(self, payload: dict[str, Any]) -> list[AIContentBlock]:
|
|
response = payload.get("response")
|
|
if isinstance(response, str) and response:
|
|
return [AIContentBlock(type="text", text=response)]
|
|
return []
|
|
|
|
@staticmethod
|
|
def _parse_tool_arguments(raw: Any) -> dict[str, Any]:
|
|
if isinstance(raw, dict):
|
|
return raw
|
|
if isinstance(raw, str) and raw.strip():
|
|
try:
|
|
parsed = json.loads(raw)
|
|
return parsed if isinstance(parsed, dict) else {"value": parsed}
|
|
except json.JSONDecodeError:
|
|
return {"raw": raw}
|
|
return {}
|
|
|
|
def _extract_openai_tool_calls(self, payload: dict[str, Any]) -> list[ToolCallRecord]:
|
|
choices = payload.get("choices") or []
|
|
if not choices or not isinstance(choices[0], dict):
|
|
return []
|
|
message = choices[0].get("message") or {}
|
|
records: list[ToolCallRecord] = []
|
|
for idx, tc in enumerate(message.get("tool_calls") or []):
|
|
if not isinstance(tc, dict):
|
|
continue
|
|
fn = tc.get("function") or {}
|
|
name = str(fn.get("name") or tc.get("name") or "").strip()
|
|
if not name:
|
|
continue
|
|
call_id = str(tc.get("id") or f"call_{idx + 1}")
|
|
args = self._parse_tool_arguments(fn.get("arguments") if fn else tc.get("arguments"))
|
|
records.append(ToolCallRecord(id=call_id, name=name, arguments=args))
|
|
return records
|
|
|
|
def _extract_responses_tool_calls(self, payload: dict[str, Any]) -> list[ToolCallRecord]:
|
|
records: list[ToolCallRecord] = []
|
|
for idx, item in enumerate(payload.get("output") or []):
|
|
if not isinstance(item, dict) or item.get("type") != "function_call":
|
|
continue
|
|
name = str(item.get("name") or "").strip()
|
|
if not name:
|
|
continue
|
|
call_id = str(item.get("call_id") or item.get("id") or f"call_{idx + 1}")
|
|
args = self._parse_tool_arguments(item.get("arguments"))
|
|
records.append(ToolCallRecord(id=call_id, name=name, arguments=args))
|
|
return records
|
|
|
|
def _extract_anthropic_tool_calls(self, payload: dict[str, Any]) -> list[ToolCallRecord]:
|
|
content = payload.get("content")
|
|
if not isinstance(content, list):
|
|
return []
|
|
records: list[ToolCallRecord] = []
|
|
for idx, item in enumerate(content):
|
|
if not isinstance(item, dict) or item.get("type") != "tool_use":
|
|
continue
|
|
name = str(item.get("name") or "").strip()
|
|
if not name:
|
|
continue
|
|
call_id = str(item.get("id") or f"call_{idx + 1}")
|
|
args = self._parse_tool_arguments(item.get("input"))
|
|
records.append(ToolCallRecord(id=call_id, name=name, arguments=args))
|
|
return records
|
|
|
|
@staticmethod
|
|
def _dedupe_urls(urls: list[str]) -> list[str]:
|
|
seen: set[str] = set()
|
|
out: list[str] = []
|
|
for raw in urls:
|
|
url = str(raw or "").strip()
|
|
if url.startswith(("http://", "https://")) and url not in seen:
|
|
seen.add(url)
|
|
out.append(url)
|
|
return out
|
|
|
|
def _extract_responses_citations(self, payload: dict[str, Any]) -> list[str]:
|
|
urls: list[str] = []
|
|
for item in payload.get("output") or []:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
if item.get("type") == "message":
|
|
for part in item.get("content") or []:
|
|
if not isinstance(part, dict):
|
|
continue
|
|
for ann in part.get("annotations") or []:
|
|
if isinstance(ann, dict) and ann.get("type") == "url_citation" and ann.get("url"):
|
|
urls.append(str(ann["url"]))
|
|
elif item.get("type") == "web_search_call":
|
|
action = item.get("action") if isinstance(item.get("action"), dict) else {}
|
|
for src in action.get("sources") or []:
|
|
if isinstance(src, dict) and src.get("url"):
|
|
urls.append(str(src["url"]))
|
|
return self._dedupe_urls(urls)
|
|
|
|
def _extract_anthropic_citations(self, payload: dict[str, Any]) -> list[str]:
|
|
content = payload.get("content")
|
|
if not isinstance(content, list):
|
|
return []
|
|
urls: list[str] = []
|
|
for item in content:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
item_type = str(item.get("type") or "")
|
|
if item_type == "web_search_tool_result":
|
|
for res in item.get("content") or []:
|
|
if isinstance(res, dict) and res.get("url"):
|
|
urls.append(str(res["url"]))
|
|
elif item_type == "text":
|
|
for cite in item.get("citations") or []:
|
|
if isinstance(cite, dict) and cite.get("url"):
|
|
urls.append(str(cite["url"]))
|
|
return self._dedupe_urls(urls)
|