"""Validated routing and bounded tool loops; model text is never executed."""
from copy import deepcopy
from http.client import HTTPConnection
import argparse
import json
from pathlib import Path
from time import monotonic
CATEGORIES=("chat","coding","search")
SCHEMA=dict(type="object",properties=dict(category=dict(type="string",enum=list(CATEGORIES)),
reason=dict(type="string",minLength=1,maxLength=200)),required=["category","reason"],additionalProperties=False)
TOOLS=[
dict(type="function",function=dict(name="web_search",description="Search the configured provider",
parameters=dict(type="object",properties=dict(query=dict(type="string")),required=["query"],additionalProperties=False))),
dict(type="function",function=dict(name="web_fetch",description="Fetch an allowed result URL",
parameters=dict(type="object",properties=dict(url=dict(type="string")),required=["url"],additionalProperties=False)))]
def unique_object(pairs):
result={}
for key,value in pairs:
if key in result:
raise ValueError("duplicate JSON field")
result[key]=value
return result
def route_from_text(text):
result=json.loads(text,object_pairs_hook=unique_object)
if not isinstance(result,dict) or set(result)!={"category","reason"}:
raise ValueError("route fields")
if result["category"] not in CATEGORIES or not isinstance(result["reason"],str) or not 1<=len(result["reason"])<=200 or not result["reason"].strip():
raise ValueError("route values")
return result
class Native:
def __init__(self,port,timeout=25):
self.port,self.timeout=port,timeout
def __call__(self,model,messages,*,format=None,tools=None,options=None):
body=dict(model=model,messages=messages,stream=False,options=options or {})
if format is not None:body["format"]=format
if tools is not None:body["tools"]=tools
connection=HTTPConnection("127.0.0.1",self.port,timeout=self.timeout)
try:
connection.request("POST","/api/chat",json.dumps(body).encode(),{"Content-Type":"application/json"})
response=connection.getresponse()
data=json.loads(response.read())
if response.status!=200 or data.get("error"):
raise RuntimeError("native API: "+str(response.status))
if data.get("done") is not True or not isinstance(data.get("message"),dict):
raise ValueError("incomplete native reply")
return data["message"]
finally:
connection.close()
def classify(question,complete,config):
if not isinstance(question,str) or not 1<=len(question.strip())<=4000:
raise ValueError("invalid question")
message=complete(config["router"],[dict(role="user",content=question)],format=SCHEMA,
options=dict(temperature=0,num_ctx=4096,num_predict=128))
return route_from_text(message["content"])
def choose_model(category,config,*,prefer_cloud=False,allow_cloud=False):
if category not in CATEGORIES:
raise ValueError("unknown category")
if prefer_cloud:
if not allow_cloud:
raise PermissionError("cloud use is disabled")
if not config.get("cloud"):
raise ValueError("cloud model is not configured")
return config["cloud"]
return config[category]
def run_tools(question,model,complete,tools,*,rounds=3,calls_per_round=2,max_chars=2000,seconds=20,clock=monotonic):
if type(rounds) is not int or not 1<=rounds<=10 or type(calls_per_round) is not int or not 1<=calls_per_round<=4:
raise ValueError("invalid loop budget")
if type(max_chars) is not int or max_chars<1 or seconds<=0:
raise ValueError("invalid output or time budget")
messages=[dict(role="user",content=question)]
deadline=clock()+seconds
for step in range(rounds):
if clock()>deadline:raise TimeoutError("workflow deadline")
response=complete(model,deepcopy(messages),tools=TOOLS,options=dict(temperature=0,num_ctx=4096,num_predict=256))
if clock()>deadline:raise TimeoutError("workflow deadline")
if response.get("role")!="assistant":
raise ValueError("expected assistant")
calls=response.get("tool_calls") or []
if not isinstance(calls,list) or len(calls)>calls_per_round:
raise ValueError("too many tool calls")
messages.append(deepcopy(response))
if not calls:
answer=response.get("content")
if not isinstance(answer,str) or not answer.strip():raise ValueError("empty final answer")
return dict(answer=answer,rounds=step+1,messages=messages)
for call in calls:
if clock()>deadline:raise TimeoutError("workflow deadline")
if not isinstance(call,dict) or not isinstance(call.get("function"),dict):
raise ValueError("invalid tool envelope")
function=call["function"]
name,arguments=function.get("name"),function.get("arguments")
if name not in ("web_search","web_fetch") or name not in tools:
raise ValueError("unknown tool")
field="query" if name=="web_search" else "url"
if not isinstance(arguments,dict) or set(arguments)!={field} or not isinstance(arguments[field],str) or not 1<=len(arguments[field])<=500:
raise ValueError("invalid tool arguments")
try:
result=tools[name](**arguments)
text=result if isinstance(result,str) else json.dumps(result,ensure_ascii=False)
content=dict(ok=True,text=text[:max_chars],truncated=len(text)>max_chars)
except Exception as error:
content=dict(ok=False,error=type(error).__name__)
if clock()>deadline:raise TimeoutError("workflow deadline")
messages.append(dict(role="tool",tool_name=name,content=json.dumps(content,ensure_ascii=False)))
raise RuntimeError("round budget exhausted")
def ask(question,complete,config,tools,*,prefer_cloud=False,allow_cloud=False):
route=classify(question,complete,config)
model=choose_model(route["category"],config,prefer_cloud=prefer_cloud,allow_cloud=allow_cloud)
if route["category"]=="search":
result=run_tools(question,model,complete,tools)
answer=result["answer"]
else:
options=dict(temperature=.2,num_ctx=65536) if route["category"]=="coding" else dict(temperature=0,num_ctx=4096)
message=complete(model,[dict(role="user",content=question)],options=options)
answer=message.get("content")
if not isinstance(answer,str) or not answer.strip():
raise ValueError("empty answer")
return dict(route=route,model=model,answer=answer)
if __name__=="__main__":
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument("question")
parser.add_argument("--port",type=int,default=11434)
parser.add_argument("--config",type=Path,default=Path(__file__).with_name("models.json"))
args=parser.parse_args()
config=json.loads(args.config.read_bytes().decode("utf8"))
# No live search adapters or cloud credentials are enabled by this entry.
print(json.dumps(ask(args.question,Native(args.port),config,tools={}),ensure_ascii=False))
本例需在 Windows、CPython 3.12、Ollama 0.40.15。协议夹具与真实模型质量分别记录;无云端或实时搜索调用。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、CPython 3.12、Ollama 0.40.15。协议夹具与真实模型质量分别记录;无云端或实时搜索调用。
入口文件:projects/ollama-agent/router.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
router.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、CPython 3.12、Ollama 0.40.15。协议夹具与真实模型质量分别记录;无云端或实时搜索调用。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a217.zip
课程关联工程包(登记关联2章) · 含当前章节或实例 · mbskycom202612a216.zip