蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

词频交互与本机 SDK 响应实验

PYTHONCPython 3.12,OpenAI SDK 3.46.0,httpx2 2.16.0;图片练习另用 Pillow 13.0.0llm_contract.py
llm_contract.py92 行
"""Run the real SDK through strictly local request and response fixtures."""
import json

import httpx2 as httpx
import openai

from lab_tools import run_exercise


RESPONSES="https://api.openai.com/v1"
DEEPSEEK="https://api.deepseek.com"
QWEN="https://dashscope.aliyuncs.com/compatible-mode/v1"


def exercise(checks, _):
    requests=[]
    base={"id":"site-chunk","object":"chat.completion.chunk","created":1,"model":"qwen-example"}

    def handler(request):
        assert request.headers["Authorization"]=="Bearer fixture-key"
        body=json.loads(request.content)
        requests.append({"host":request.url.host,"path":request.url.path,"body":body})
        if request.url.host=="api.openai.com":
            assert request.url.path=="/v1/responses"
            return httpx.Response(200,json={"id":"site-response","object":"response","created_at":1,
                "model":body["model"],"status":"completed","output":[{"id":"site-msg","type":"message",
                "role":"assistant","status":"completed","content":[{"type":"output_text","text":"Local result","annotations":[]}]}]})
        if not body.get("stream",False):
            return httpx.Response(200,json={"id":"site-chat","object":"chat.completion","created":1,
                "model":body["model"],"choices":[{"index":0,"message":{"role":"assistant","content":"Fixture reply"},
                "finish_reason":"stop"}]})
        events=[
            dict(base,choices=[{"index":0,"delta":{"content":"Harbor"},"finish_reason":None}]),
            dict(base,choices=[{"index":0,"delta":{"content":" ready"},"finish_reason":"stop"}]),
            dict(base,choices=[],usage={"prompt_tokens":4,"completion_tokens":2,"total_tokens":6}),
        ]
        stream="".join("data: "+json.dumps(event)+"\n\n" for event in events)+"data: [DONE]\n\n"
        return httpx.Response(200,headers={"Content-Type":"text/event-stream"},content=stream.encode("ascii"))

    def client(endpoint):
        return openai.OpenAI(api_key="fixture-key",base_url=endpoint,max_retries=0,
            http_client=httpx.Client(transport=httpx.MockTransport(handler),trust_env=False))

    msg=[{"role":"user","content":"Read the local fixture"}]
    expect=checks.expect
    with client(RESPONSES) as api:
        result=api.responses.create(model="response-fixture",instructions="Use the supplied fixture",input="Read the result")
    expect("llm_responses",RESPONSES,"Serialize a Responses request and read output_text from the fixture",
        ["/v1/responses","Local result","Use the supplied fixture"],
        [requests[-1]["path"],result.output_text,requests[-1]["body"]["instructions"]])

    with client(DEEPSEEK) as api:
        result=api.chat.completions.create(model="deepseek-flash",messages=msg,stream=False,
            extra_body={"thinking":{"type":"disabled"}})
    expect("llm_flash_chat",DEEPSEEK,"Serialize current Flash with independent thinking toggle and read a local response",
        ["/chat/completions","deepseek-flash",{"type":"disabled"},"Fixture reply"],
        [requests[-1]["path"],requests[-1]["body"]["model"],requests[-1]["body"]["thinking"],result.choices[0].message.content])
    with client(DEEPSEEK+"/v1") as api:
        api.chat.completions.create(model="deepseek-v4-flash",messages=msg)
        api.chat.completions.create(model="deepseek-v4-pro",messages=msg,extra_body={"thinking":{"type":"enabled"}})
    expect("llm_model_fields",DEEPSEEK+"/v1","Verify serialization for legacy Flash identifier and Pro",
        [["/v1/chat/completions","deepseek-v4-flash",None],["/v1/chat/completions","deepseek-v4-pro",{"type":"enabled"}]],
        [[row["path"],row["body"]["model"],row["body"].get("thinking")] for row in requests[-2:]])

    with client(QWEN) as api:
        completion=api.chat.completions.create(model="qwen-example",messages=msg,stream=False)
        expect("llm_qwen_chat",QWEN,"Parse a nonstream Chat message with a compatible endpoint prefix",
            ["/compatible-mode/v1/chat/completions","Fixture reply"],
            [requests[-1]["path"],completion.choices[0].message.content])
        with api.chat.completions.create(model="qwen-example",messages=msg,stream=True,
                stream_options={"include_usage":True}) as events:
            texts=[]
            usage=None
            sizes=[]
            for event in events:
                sizes.append(len(event.choices))
                if event.choices and event.choices[0].delta.content is not None:
                    texts.append(event.choices[0].delta.content)
                if event.usage is not None:
                    usage=event.usage.total_tokens
    expect("llm_qwen_sse",QWEN,"Consume the two text deltas and trailing usage-only event",
        ["Harbor ready",[1,1,0],6,{"include_usage":True}],
        ["".join(texts),sizes,usage,requests[-1]["body"]["stream_options"]])
    expect("llm_fixture_auth",len(requests),"Check all fixture routes used an explicit dummy key",
        6,len(requests))
    expect("llm_sdk_available","installed isolated SDK and transport","Read actual versions",
        ["3.46.0","2.16.0"],[openai.__version__,httpx.__version__])


if __name__=="__main__":
    run_exercise(exercise)
本例需在 CPython 3.12,OpenAI SDK 3.46.0,httpx2 2.16.0;图片练习另用 Pillow 13.0.0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12,OpenAI SDK 3.46.0,httpx2 2.16.0;图片练习另用 Pillow 13.0.0

入口文件:projects/ai-agent-llm-modal/llm_contract.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 llm_contract.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12,OpenAI SDK 3.46.0,httpx2 2.16.0;图片练习另用 Pillow 13.0.0。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联2章) · 含当前章节或实例 · mbskycom202612a3089.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习