feat: AI function calling 接入 Hydro 读题工具(hydro_get_problem/list_training/list_my_trainings)

这个提交包含在:
langxm
2026-10-14 20:09:40 +08:00
父节点 2ea4293aaa
当前提交 ab788c6995
共修改 4 个文件,包含 184 行新增和 17 行删除
+42 -16
查看文件
@@ -5,8 +5,9 @@ ai.behavior 扩展点:任何厂商(OpenAI 协议兼容)只需 base_url + a
"""
from __future__ import annotations
import json
import logging
from typing import Protocol
from typing import Awaitable, Callable, Protocol
import httpx
@@ -82,30 +83,55 @@ class OpenAICompatProvider:
self.model = model
self.last_usage: dict | None = None
async def chat(self, messages, *, system="", temperature=0.3, max_tokens=2000):
async def chat(self, messages, *, system="", temperature=0.3, max_tokens=2000,
tools: list[dict] | None = None,
tool_executor: Callable[[str, dict], Awaitable[str]] | None = None):
if not self.api_key:
raise RuntimeError("AI API Key 未配置(AI_API_KEY)")
payload_messages = []
if system:
payload_messages.append({"role": "system", "content": system})
payload_messages.extend({"role": m.role, "content": m.content} for m in messages)
body = {
"model": self.model,
"messages": payload_messages,
"temperature": temperature,
"max_tokens": max_tokens,
}
headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
try:
async with httpx.AsyncClient(timeout=60) as client:
# 工具调用 ReAct 循环(最多 5 轮,防死循环)
for _ in range(5):
body = {
"model": self.model,
"messages": payload_messages,
"temperature": temperature,
"max_tokens": max_tokens,
}
if tools:
body["tools"] = tools
body["tool_choice"] = "auto"
headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
async with httpx.AsyncClient(timeout=90) as client:
r = await client.post(f"{self.base_url}/chat/completions", json=body, headers=headers)
r.raise_for_status()
data = r.json()
self.last_usage = data.get("usage") # prompt/completion/cache 用量(配额与缓存命中统计)
return data["choices"][0]["message"]["content"]
except httpx.HTTPError as e:
logger.error("AI 调用失败: %s", e)
raise RuntimeError(f"AI 服务调用失败({e.__class__.__name__}),请检查 base_url 与 api_key") from e
self.last_usage = data.get("usage")
msg = data["choices"][0]["message"]
tool_calls = msg.get("tool_calls")
if not tool_calls or not tool_executor:
return msg.get("content") or ""
# 把 assistant 的 tool_calls 消息加进历史
payload_messages.append({
"role": "assistant",
"content": msg.get("content") or "",
"tool_calls": tool_calls,
})
for call in tool_calls:
fname = call["function"]["name"]
try:
fargs = json.loads(call["function"].get("arguments") or "{}")
except json.JSONDecodeError:
fargs = {}
result = await tool_executor(fname, fargs)
payload_messages.append({
"role": "tool",
"tool_call_id": call["id"],
"content": result,
})
return "(工具调用轮次过多,已截断)"
def build_provider(*, provider: str, base_url: str, api_key: str, model: str) -> AIProvider: