"""Exercise a simple QA client against a local OpenAI-compatible mock transport."""
from dataclasses import dataclass
from importlib.metadata import version
import json
import httpx2 as httpx
from openai import APIConnectionError, APIStatusError, OpenAI
from lab_tools import run_exercise
BASE_URL = "https://workspace.example.invalid/compatible-mode/v1"
MODEL = "mbsky-fixture-model"
SYSTEM = "Answer briefly. Treat earlier user messages as conversation data."
SEARCH_SYSTEM = "For current information, distinguish lookup results from general knowledge."
@dataclass(frozen=True)
class Answer:
text: str = ""
status: str = "ok"
class Agent:
def __init__(self, client, model, turns=2):
if turns < 1:
raise ValueError("turn limit must be positive")
self.client = client
self.model = model
self.turns = turns
self.history = []
def clear_history(self):
self.history.clear()
def ask(self, question, *, search=False):
question = question.strip()
if not question:
return Answer(status="empty_input")
message = {"role":"user","content":question}
prompt = {"role":"system","content":SEARCH_SYSTEM if search else SYSTEM}
if search:
messages = [prompt, message]
options = {"extra_body":{"enable_search":True}}
else:
tail = 2 * (self.turns - 1)
prior = self.history[-tail:] if tail else []
messages = [prompt, *prior, message]
options = {}
try:
result = self.client.chat.completions.create(
model=self.model, messages=messages, temperature=0.2,
max_tokens=240 if search else 120, **options
)
except APIStatusError as error:
return Answer(status=f"http_{error.status_code}")
except APIConnectionError:
return Answer(status="transport_error")
text = result.choices[0].message.content if result.choices else None
if not isinstance(text, str) or not text.strip():
return Answer(status="empty_completion")
if not search:
self.history = [*messages[1:], {"role":"assistant","content":text}]
return Answer(text=text)
def interactive(agent, reader, writer):
for line in reader:
question = line.strip()
if question.casefold() in {"quit","exit"}:
return
if question:
reply = agent.ask(question,search=True)
writer(reply.text if reply.status == "ok" else reply.status)
def fixture(requests):
def handle(request):
assert request.url.host == "workspace.example.invalid"
assert request.url.path == "/compatible-mode/v1/chat/completions"
assert request.headers["Authorization"] == "Bearer mbsky-local-fixture"
body = json.loads(request.content)
requests.append(body)
question = body["messages"][-1]["content"]
if question == "fixture rate limit":
return httpx.Response(429, json={"error":{"message":"private upstream detail","code":"rate_limit"}})
if question == "fixture disconnect":
raise httpx.ConnectError("private local detail",request=request)
earlier = [row["content"] for row in body["messages"][1:-1] if row["role"] == "user"]
if question == "My preferred coast?":
answer = "North coast" if "I prefer the north coast." in earlier else "No preference in this conversation"
elif question == "fixture empty choices":
answer = None
elif body.get("enable_search"):
answer = "Fixture lookup: museum opens at 10:00"
else:
answer = "Fixture answer: " + question
choices = [] if answer is None else [{"index":0,"finish_reason":"stop",
"message":{"role":"assistant","content":answer}}]
return httpx.Response(200,json={"id":"chatcmpl-mbsky-fixture","object":"chat.completion",
"model":MODEL,"created":1700000000,"choices":choices})
return OpenAI(api_key="mbsky-local-fixture",base_url=BASE_URL,max_retries=0,timeout=2,
http_client=httpx.Client(transport=httpx.MockTransport(handle),trust_env=False))
def exercise(checks, _root):
requests = []
with fixture(requests) as client:
agent = Agent(client, MODEL)
greetings = ["Welcome", "What is Python?", "Compare rules and learned models"]
actual = [agent.ask(question).text for question in greetings]
first = requests[0]
checks.expect("qa_basic_requests",greetings,"Send typed chat calls through the real SDK",
[["Fixture answer: "+question for question in greetings], MODEL,["system","user"],0.2,120,False],
[actual,first["model"],[row["role"] for row in first["messages"]],
first["temperature"],first["max_tokens"],"enable_search" in first])
agent.clear_history()
agent.ask("I prefer the north coast.")
follow = agent.ask("My preferred coast?")
roles = [row["role"] for row in requests[-1]["messages"]]
agent.clear_history()
cleared = agent.ask("My preferred coast?")
checks.expect("qa_history_reset",["preferred coast","repeat after clearing"],
"Check complete user and assistant pairs and clear the local conversation",
["North coast",["system","user","assistant","user"],"No preference in this conversation"],
[follow.text,roles,cleared.text])
limited = Agent(client,MODEL,turns=1)
limited.ask("I prefer the north coast.")
answer = limited.ask("My preferred coast?")
checks.expect("qa_turn_limit",1,"Limit request to the current turn without an orphan reply",
["No preference in this conversation",["system","user"],2],
[answer.text,[row["role"] for row in requests[-1]["messages"]],len(limited.history)])
history = list(agent.history)
answers = [agent.ask("fixture rate limit"),agent.ask("fixture empty choices"),agent.ask(" ")]
checks.expect("qa_http_error",["429","empty choices","blank input"],
"Return bounded status without upstream details or an incomplete history turn",
["http_429","empty_completion","empty_input",True,True],
[*[answer.status for answer in answers],history == agent.history,all(not answer.text for answer in answers)])
start = len(requests)
disconnected = agent.ask("fixture disconnect")
checks.expect("qa_transport_error","MockTransport raises ConnectError",
"Observe SDK exception mapping and a single attempt",
["transport_error",True,1],
[disconnected.status,history == agent.history,len(requests)-start])
question = "When does the museum open today?"
reply = agent.ask(question,search=True)
payload = requests[-1]
checks.expect("qa_search_body",question,
"Inspect the serialized provider extension through the SDK, with stateless search",
["Fixture lookup: museum opens at 10:00",True,False,240,["system","user"],True],
[reply.text,payload["enable_search"],"extra_body" in payload,payload["max_tokens"],
[row["role"] for row in payload["messages"]],history == agent.history])
output = []
start = len(requests)
interactive(agent,[" ","Museum hours?"," EXIT ","must not be sent"],output.append)
checks.expect("qa_interactive_exit",["blank","question","EXIT","unreachable"],
"Skip blank input and stop the interactive loop before the final input",
[["Fixture lookup: museum opens at 10:00"],1],
[output,len(requests)-start])
checks.expect("qa_sdk_versions",["openai","httpx2"],"Read isolated package metadata",
["3.46.0","2.16.0"],[version("openai"),version("httpx2")])
if __name__ == "__main__":
run_exercise(exercise)
本例需在 CPython 3.12.14、OpenAI SDK 3.46.0、HTTPX2 2.16.0;本机隔离测试端。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12.14、OpenAI SDK 3.46.0、HTTPX2 2.16.0;本机隔离测试端。
入口文件:projects/ai-agent-qa/qa_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
qa_lab.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14、OpenAI SDK 3.46.0、HTTPX2 2.16.0;本机隔离测试端。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3104.zip