AI Agent / 系统课时

创建模型客户端

创建模型客户端

本课把 HTTP 请求集中在 model_client.py,直接导入上一课的配置。示例只实现兼容 Chat Completions 的非流式文本请求,响应保留首个选项的文本、结束原因和用量。模型是否接受其他字段,应按供应商文档核对。

管理连接与错误边界

python
from dataclasses import dataclass
import httpx

from model_config import ModelConfig

class ModelClientError(RuntimeError):
    pass

class ModelTimeout(ModelClientError):
    pass

class ModelUnavailable(ModelClientError):
    pass

class ModelRateLimited(ModelUnavailable):
    pass

@dataclass(frozen=True)
class ChatReply:
    text: str | None
    finish_reason: str
    usage: dict
    refusal: str | None

class ModelClient:
    def __init__(self, config: ModelConfig, transport=None):
        self._config = config
        self._http = httpx.Client(
            base_url=config.base_url + "/",
            headers={"Authorization": f"Bearer {config.api_key}"},
            timeout=httpx.Timeout(connect=5, read=config.timeout_seconds, write=10, pool=5),
            follow_redirects=False,
            transport=transport,
        )

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self._http.close()

    def chat(self, messages):
        try:
            response = self._http.post("chat/completions", json={
                "model": self._config.model_name,
                "messages": messages,
            })
        except httpx.TimeoutException:
            raise ModelTimeout("模型请求超时") from None
        except httpx.RequestError:
            raise ModelUnavailable("模型服务连接或传输失败") from None

        status = response.status_code
        if status == 429:
            raise ModelRateLimited("模型服务返回 HTTP 429")
        if 500 <= status < 600:
            raise ModelUnavailable(f"模型服务暂时不可用,HTTP {status}")
        if not response.is_success:
            raise ModelClientError(f"模型请求失败,HTTP {status}")

        try:
            data = response.json()
            choice = data["choices"][0]
            message = choice["message"]
            text = message.get("content")
            refusal = message.get("refusal")
            finish = choice["finish_reason"]
            usage = data.get("usage")
        except (ValueError, KeyError, IndexError, TypeError, AttributeError):
            raise ModelClientError("模型响应结构不符合预期") from None
        if (not isinstance(finish, str) or not finish
                or (text is not None and not isinstance(text, str))
                or (refusal is not None and not isinstance(refusal, str))
                or (usage is not None and not isinstance(usage, dict))):
            raise ModelClientError("模型响应字段类型不符合预期")
        return ChatReply(text, finish, usage or {}, refusal)

客户端用上下文管理器关闭连接池。连接、读、写与等待连接池分别计时。HTTPX 的读取超时约束等待下一批数据的时间,整个 Agent 仍需单独的总时限。

服务端错误只记录分类与状态码,避免把服务回显的请求数据带进日志。429 既可能是短期限流,也可能是配额问题。先核对原因再决定是否退避。对于读取超时,服务器可能已经收到请求或产生计费,重试应纳入上层预算。下一课会用离线传输验证请求路径和结束分支。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

创建模型客户端

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通