"""Exercise local Ollama REST protocols with explicitly imported test fixtures."""
import argparse
from contextlib import contextmanager
from http.client import HTTPConnection
import json
from math import sqrt
from uuid import uuid4
@contextmanager
def response(port,method,path,body=None,headers=None):
connection=HTTPConnection("127.0.0.1",port,timeout=25)
try:
if isinstance(body,dict):
body=json.dumps(body,ensure_ascii=False).encode("utf8")
fields={"Content-Type":"application/json"} if body is not None else {}
fields.update(headers or {})
connection.request(method,path,body=body,headers=fields)
yield connection.getresponse()
finally:
connection.close()
def json_result(port,method,path,body=None,headers=None,expected=200):
with response(port,method,path,body,headers) as reply:
data=json.loads(reply.read())
if reply.status!=expected:
raise ValueError(f"{path} returned {reply.status}: {data}")
return data
def run(port,text,embedding):
def get(path):
return json_result(port,"GET",path)
def post(path,data,headers=None):
return json_result(port,"POST",path,data,headers)
options=dict(num_ctx=128,num_gpu=0,num_predict=2,temperature=0)
version=get("/api/version")["version"]
inventory={row["name"]:row for row in get("/api/tags")["models"]}
if not {text,embedding}.issubset(inventory):
raise ValueError("Import both local tutorial models before using this client.")
pre=post("/api/generate",dict(model=text,keep_alive="1m",stream=False,options=options))
active=next(row for row in get("/api/ps")["models"] if row["name"]==text)
native=post("/api/generate",dict(model=text,prompt="ping",raw=True,stream=False,options=options))
stat_keys=("total_duration","load_duration","prompt_eval_count","prompt_eval_duration","eval_count","eval_duration")
statistics={key:native[key] for key in stat_keys}
schema=dict(type="string",enum=["pong"])
structured=post("/api/generate",dict(model=text,prompt="ping",raw=True,stream=False,
options=dict(options,num_predict=8),format=schema))
prompts=[dict(role="system",content="A local transport check."),dict(role="user",content="ping")]
chat=post("/api/chat",dict(model=text,messages=prompts,stream=False,options=options))
stream=[]
with response(port,"POST","/api/generate",dict(model=text,prompt="ping",raw=True,
options=dict(options,num_predict=3),stream=True)) as wire:
if wire.status!=200 or wire.getheader("Content-Type","").split(";",1)[0]!="application/x-ndjson":
raise ValueError("Expected a native successful NDJSON response.")
for row in wire:
if not row.strip():
continue
event=json.loads(row)
if event.get("error"):
raise RuntimeError(event["error"])
stream.append(event)
if not stream or not stream[-1]["done"] or any(row["done"] for row in stream[:-1]):
raise ValueError("Stream did not finish normally.")
unloaded=post("/api/generate",dict(model=text,keep_alive=0,stream=False,options=options))
loaded_after=[row["name"] for row in get("/api/ps")["models"]]
vectors=post("/api/embed",dict(model=embedding,input=["ping","pong"],truncate=False))["embeddings"]
short=post("/api/embed",dict(model=embedding,input="ping",dimensions=8,truncate=False))["embeddings"]
normalized=[round(sqrt(sum(v*v for v in vector)),8) for vector in (*vectors,*short)]
error_shapes=[]
for path,data,status in (
("/api/generate",b"{",400),("/api/show",{"model":"missing-"+uuid4().hex},404),
):
value=json_result(port,"POST",path,data,expected=status)
error_shapes.append([status,type(value.get("error")).__name__])
alias=f"mbsky-api-copy:{uuid4().hex}"
with response(port,"POST","/api/copy",{"source":text,"destination":alias}) as copy:
copy.read()
if copy.status!=200:
raise ValueError(f"Copy returned {copy.status}")
try:
copied=next(row for row in get("/api/tags")["models"] if row["name"]==alias)
shown=post("/api/show",dict(model=alias))
finally:
with response(port,"DELETE","/api/delete",{"model":alias}) as reply:
reply.read()
delete_status=reply.status
common=[dict(role="user",content="ping")]
cc=post("/v1/chat/completions",dict(model=text,messages=common,max_tokens=1,temperature=0,stream=False))
completion=post("/v1/completions",dict(model=text,prompt="ping",max_tokens=1,temperature=0,stream=False))
outputs=post("/v1/responses",dict(model=text,input="ping",max_output_tokens=1,temperature=0,stream=False))
embeddings=post("/v1/embeddings",dict(model=embedding,input=["ping","pong"]))
anth=post("/v1/messages",dict(model=text,messages=common,max_tokens=1,temperature=0),{"anthropic-version":"2023-06-01"})
compatible=sorted(row["id"] for row in get("/v1/models")["data"])
return dict(version=version,preload=pre["done_reason"],active=active["name"],unload=unloaded["done_reason"],
active_after=loaded_after,native=native["response"],statistics=statistics,structured=json.loads(structured["response"]),
chat=[chat["message"]["role"],chat["message"]["content"]],
stream=[[row["response"] for row in stream[:-1]],stream[-1]["done_reason"],stream[-1]["eval_count"]],
embeddings=[list(map(len,vectors)),list(map(len,short)),normalized,vectors[0]==vectors[1]],
errors=error_shapes,management=[copied["digest"]==inventory[text]["digest"],shown["details"]["family"],delete_status,
alias not in {row["name"] for row in get("/api/tags")["models"]}],
compatible=[cc["choices"][0]["message"]["content"],completion["choices"][0]["text"],
outputs["output"][0]["content"][0]["text"],outputs["store"],[len(row["embedding"]) for row in embeddings["data"]],
anth["content"][0]["text"],compatible])
if __name__=="__main__":
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument("--port",type=int,default=11434)
parser.add_argument("--text",default="mbsky-api:text")
parser.add_argument("--embedding",default="mbsky-api:embedding")
args=parser.parse_args()
print(json.dumps(run(args.port,args.text,args.embedding),ensure_ascii=False))
本例需在 Windows、Python 3.12。各实验所需工具和版本见下载包 README。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。
入口文件:projects/ollama-rest/api_probe.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
api_probe.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a217.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a230.zip