"""Observe SDK contracts and grounded retrieval using a strictly local transport."""
from hashlib import sha1, sha256
import json
from math import sqrt
import os
from pathlib import Path
import httpx2 as httpx
from openai import OpenAI
import openai
import tiktoken
from lab_tools import run_exercise
VOCABULARY="https://openaipublic.blob.core.windows.net/encodings/o200k_base.tiktoken"
HASH="446a9538cb6c348e3516120d7c08b09f57c36495e2acfffe59a5bf8b0cfb1a2d"
MODEL="gpt-4o-mini"
EMBEDDING="text-embedding-3-small"
DOCS={"inventory":"Pier A has 4 demo crates.","schedule":"The demo ferry leaves at 09:00."}
VECTORS={DOCS["inventory"]:[1,0,0],DOCS["schedule"]:[0,1,0],
"How many crates?":[1,0,0],"Is the cafe open?":[0,0,1]}
STOCK={"A":4,"B":0}
TOOLS=[{"type":"function","function":{"name":"read_crates","description":"Read the count of demo crates.",
"parameters":{"type":"object","properties":{"pier":{"type":"string"}},"required":["pier"],
"additionalProperties":False},"strict":True}}]
def choose_evidence(documents, vectors, question):
qnorm=sqrt(sum(v*v for v in question))
if not qnorm:
return None
ranked=[]
for key,row in zip(documents,vectors,strict=True):
norm=sqrt(sum(v*v for v in row))
score=sum(a*b for a,b in zip(row,question,strict=True))/(norm*qnorm) if norm else 0.0
ranked.append((score,key))
return max(ranked)[1] if ranked and max(ranked)[0]>=0.5 else None
def complete(model,message,usage=None,finish="stop"):
return {"id":"local-fixture","object":"chat.completion","created":1,"model":model,
"choices":[{"index":0,"message":dict(role="assistant",**message),"finish_reason":finish}],
"usage":usage or {"prompt_tokens":17,"completion_tokens":4,"total_tokens":21}}
def exercise(checks,workspace):
cache=Path(os.environ["TIKTOKEN_CACHE_DIR"])
path=cache/sha1(VOCABULARY.encode()).hexdigest()
assert sha256(path.read_bytes()).hexdigest()==HASH
encoding=tiktoken.encoding_for_model(MODEL)
example="Hello world"
ids=encoding.encode(example)
expect=checks.expect
expect("ai_llm_tokenization",example,"Use the actual model encoding and decode each ASCII token",
["o200k_base",2,["Hello"," world"]],[encoding.name,len(ids),[encoding.decode([i]) for i in ids]])
text="码头🪁"
bits=[encoding.decode_single_token_bytes(i) for i in encoding.encode(text)]
expect("ai_llm_token_bytes",text,"Join token bytes before decoding multibyte text",
text,b"".join(bits).decode("utf8"))
requests=[]
applied=[]
def mock(request):
assert request.url.host=="api.openai.com" and request.headers["Authorization"]=="Bearer fixture-key"
body=json.loads(request.content)
requests.append((request.url.path,body))
if request.url.path=="/v1/embeddings":
data=body["input"]
values=[data] if isinstance(data,str) else data
return httpx.Response(200,json={"object":"list","model":body["model"],
"data":[{"object":"embedding","index":i,"embedding":VECTORS[value]}
for i,value in reversed(list(enumerate(values)))],"usage":{"prompt_tokens":5,"total_tokens":5}})
assert request.url.path=="/v1/chat/completions"
messages=body["messages"]
if messages[-1]["role"]=="tool":
records=[json.loads(msg["content"]) for msg in messages if msg["role"]=="tool"]
return httpx.Response(200,json=complete(body["model"],{"content":f"Demo counts: {records[0]['count']}, {records[1]['count']}."}))
if "tools" in body:
calls=[{"id":f"local_{pier}","type":"function","function":{"name":"read_crates",
"arguments":json.dumps({"pier":pier})}} for pier in ("A","B")]
return httpx.Response(200,json=complete(body["model"],{"content":None,"tool_calls":calls},finish="tool_calls"))
content="Pier A has 4 demo crates. [inventory]" if "[inventory]" in messages[-1]["content"] else "Fixture reply"
return httpx.Response(200,json=complete(body["model"],{"content":content}))
def local_call(call):
if call.function.name!="read_crates":
return {"error":"unknown_tool"}
try:
args=json.loads(call.function.arguments)
except json.JSONDecodeError:
return {"error":"invalid_json"}
if not isinstance(args,dict) or set(args)!={"pier"} or not isinstance(args["pier"],str) or args["pier"] not in STOCK:
return {"error":"unknown_pier"}
applied.append(args["pier"])
return {"count":STOCK[args["pier"]]}
with OpenAI(api_key="fixture-key",base_url="https://api.openai.com/v1",max_retries=0,
http_client=httpx.Client(transport=httpx.MockTransport(mock),trust_env=False)) as api:
messages=[{"role":"system","content":"Reply from the local fixture."},{"role":"user","content":"Describe the demo."}]
chat=api.chat.completions.create(model=MODEL,messages=messages,temperature=0.4)
expect("ai_llm_chat_usage",messages,"Verify SDK request roles and temperature, and parse usage and response",
["/v1/chat/completions",0.4,["system","user"],"Fixture reply",[17,4,21]],
[requests[-1][0],requests[-1][1]["temperature"],[x["role"] for x in requests[-1][1]["messages"]],
chat.choices[0].message.content,[chat.usage.prompt_tokens,chat.usage.completion_tokens,chat.usage.total_tokens]])
def embedded(values):
reply=api.embeddings.create(model=EMBEDDING,input=values,encoding_format="float")
return [v.embedding for v in sorted(reply.data,key=lambda v:v.index)]
keys=list(DOCS)
stored=embedded(list(DOCS.values()))
match=choose_evidence(keys,stored,embedded("How many crates?")[0])
missed=choose_evidence(keys,stored,embedded("Is the cafe open?")[0])
expect("ai_llm_retrieval",["How many crates?","Is the cafe open?"],"Order embedding rows by index, rank by cosine and keep no-match",
["inventory",None],[match,missed])
prompt=f"[{match}] {DOCS[match]}\nQuestion: How many crates?"
grounded=api.chat.completions.create(model=MODEL,messages=[{"role":"user","content":prompt}])
expect("ai_llm_grounded_result",prompt,"Send selected source and inspect local response and citation",
["Pier A has 4 demo crates. [inventory]",True],
[grounded.choices[0].message.content,"[inventory]" in requests[-1][1]["messages"][0]["content"]])
messages=[{"role":"user","content":"Check both piers."}]
step=api.chat.completions.create(model=MODEL,messages=messages,tools=TOOLS)
choice=step.choices[0].message
replies=[{"role":"tool","tool_call_id":call.id,"content":json.dumps(local_call(call))}
for call in choice.tool_calls]
assistant=choice.model_dump(exclude_none=True)
result=api.chat.completions.create(model=MODEL,messages=[*messages,assistant,*replies],tools=TOOLS)
expect("ai_llm_tool_roundtrip","Check both piers.","Validate arguments, run both local functions and return matching tool IDs",
[["A","B"],["local_A","local_B"],[4,0],"Demo counts: 4, 0."],
[applied,[r["tool_call_id"] for r in requests[-1][1]["messages"] if r["role"]=="tool"],
[json.loads(r["content"])["count"] for r in replies],result.choices[0].message.content])
refused=choice.tool_calls[0].model_copy(deep=True)
refused.function.arguments='{"pier":"Z"}'
expect("ai_llm_tool_rejected","Z","Reject unapproved argument without another tool execution",
[{"error":"unknown_pier"},["A","B"]],[local_call(refused),applied])
expect("ai_llm_sdk_versions","package versions","Read exact SDK and transport versions",
["3.46.0","2.16.0"],[openai.__version__,httpx.__version__])
if __name__=="__main__":
run_exercise(exercise)
本例需在 Python 3.12.14,tiktoken 0.14.0,OpenAI SDK 3.46.0,httpx2 2.16.0。本机固定回包。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Python 3.12.14,tiktoken 0.14.0,OpenAI SDK 3.46.0,httpx2 2.16.0。本机固定回包。
入口文件:projects/ai-llm-concepts/llm_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
llm_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Python 3.12.14,tiktoken 0.14.0,OpenAI SDK 3.46.0,httpx2 2.16.0。本机固定回包。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a16.zip