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

用真实 SDK 完成两次相关联的工具结果

PYTHONCPython 3.12、OpenAI SDK 3.46.0、httpx2 2.16.0、jsonschema 4.26.0 与 Edge。function_calls.py
function_calls.py168 行
"""Validate tool calls and return their correlated results via a local SDK transport."""
import json

import httpx2 as httpx
from jsonschema import Draft202012Validator
import openai

from lab_tools import run_exercise


WEATHER_SCHEMA = {
    "type": "object",
    "properties": {
        "city": {"type":"string","enum":["潮湾","山城"]},
        "day": {"type":"string","enum":["今天","明天"],"default":"今天"},
        "unit": {"type":"string","enum":["celsius","fahrenheit"],"default":"celsius"},
    },
    "required": ["city"],
    "additionalProperties": False,
}
CATALOG_SCHEMA = {
    "type":"object",
    "properties":{
        "query":{"type":"string","minLength":1,"maxLength":40},
        "limit":{"type":"integer","minimum":1,"maximum":3,"default":2},
    },
    "required":["query"],
    "additionalProperties":False,
}
SCHEMAS = {"weather_card": WEATHER_SCHEMA, "catalog_search": CATALOG_SCHEMA}
DOCS = {"weather_card":"Read a local forecast card for one listed city and day.",
        "catalog_search":"Find matching titles in the small local harbor catalog."}
TOOLS = [{"type":"function","function":{"name":name,"description":DOCS[name],"parameters":schema}}
         for name,schema in SCHEMAS.items()]


def unique_keys(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate_key")
        result[key] = value
    return result


def reject_constant(_):
    raise ValueError("invalid_json_constant")


def arguments(name, raw, schemas=SCHEMAS):
    if name not in schemas:
        raise ValueError("unregistered_tool")
    if not isinstance(raw, str) or len(raw) > 512:
        raise ValueError("arguments_too_long")
    try:
        item = json.loads(raw, object_pairs_hook=unique_keys, parse_constant=reject_constant)
    except (json.JSONDecodeError, RecursionError) as error:
        raise ValueError("invalid_json") from error
    schema = schemas[name]
    validator = Draft202012Validator(schema)
    errors = sorted({error.validator for error in validator.iter_errors(item)})
    if errors:
        raise ValueError(",".join(errors))
    defaults = {key:fields["default"] for key,fields in schema["properties"].items() if "default" in fields}
    normalized = {**defaults,**item}
    for key, value in normalized.items():
        if schema["properties"][key]["type"] == "integer":
            normalized[key] = int(value)
    return normalized


def weather_card(city, day, unit):
    celsius = {("潮湾","今天"):17,("潮湾","明天"):16,("山城","今天"):23,("山城","明天"):24}
    value = celsius[city,day]
    return dict(city=city,day=day,temperature=value if unit=="celsius" else round(32 + value * 9 / 5,1),unit=unit)


def catalog_search(query, limit):
    rows = ("北岸灯塔","旧城展馆","南岸灯塔")
    return [title for title in rows if query in title][:limit]


def dispatch(tool_call):
    name = tool_call.function.name
    try:
        kwargs = arguments(name, tool_call.function.arguments)
        output = {"value":{"weather_card":weather_card,"catalog_search":catalog_search}[name](**kwargs)}
    except ValueError as error:
        output = {"error":str(error)}
    return {"role":"tool","tool_call_id":tool_call.id,"content":json.dumps(output,ensure_ascii=False)}


def exercise(checks, _):
    expect = checks.expect
    for schema in SCHEMAS.values():
        Draft202012Validator.check_schema(schema)
    partial = {"city":"潮湾"}
    Draft202012Validator(WEATHER_SCHEMA).validate(partial)
    expect("call_defaults",partial,"Compare validation alone and the host's explicit defaults",
           [{"city":"潮湾"},{"city":"潮湾","day":"今天","unit":"celsius"}],
           [partial,arguments("weather_card",json.dumps(partial))])
    integral = arguments("catalog_search",'{"query":"灯塔","limit":1.0}')
    expect("call_integer_representation","1.0","Normalize a JSON Schema integer before slicing Python data",
           [True,["北岸灯塔"]],[type(integral["limit"]) is int,catalog_search(**integral)])
    inputs = [
        ("weather_card",'{}',"required"),
        ("weather_card",'{"city":null}',"enum,type"),
        ("weather_card",'{"city":"潮湾","day":"昨天"}',"enum"),
        ("weather_card",'{"city":"潮湾","unit":"Kelvin"}',"enum"),
        ("weather_card",'{"city":"潮湾","extra":1}',"additionalProperties"),
        ("weather_card",'{"city":"潮湾","city":"山城"}',"duplicate_key"),
        ("weather_card",'{',"invalid_json"),
        ("catalog_search",'{"query":"灯塔","limit":true}',"type"),
        ("catalog_search",'{"query":"灯塔","limit":NaN}',"invalid_json_constant"),
        ("catalog_search",'{"query":"灯塔","limit":0}',"minimum"),
        ("catalog_search",'{"query":"灯塔","limit":4}',"maximum"),
        ("catalog_search",'{"query":""}',"minLength"),
        ("missing",'{}',"unregistered_tool"),
    ]
    results = []
    for tool,raw,_ in inputs:
        try:
            arguments(tool,raw)
        except ValueError as error:
            results.append(str(error))
    expect("call_schema_boundaries",[[tool,raw] for tool,raw,_ in inputs],
           "Check missing, null, enum, extra, malformed, duplicate, boolean, range and unknown tool errors",
           [reason for _,_,reason in inputs],results)
    packets = []

    def transport(request):
        assert request.url.host=="function-calls.invalid" and request.url.path=="/v1/chat/completions"
        assert request.headers["authorization"]=="Bearer local-fixture"
        payload = json.loads(request.content)
        packets.append(payload)
        if len(packets)==1:
            assert payload["tools"]==TOOLS
            message = {"role":"assistant","content":None,"tool_calls":[
                {"id":"weather-1","type":"function","function":{"name":"weather_card","arguments":'{"city":"潮湾","day":"明天","unit":"fahrenheit"}'}},
                {"id":"catalog-1","type":"function","function":{"name":"catalog_search","arguments":'{"query":"灯塔","limit":1}'}},
            ]}
            finish = "tool_calls"
        else:
            assert [r["role"] for r in payload["messages"]]==["user","assistant","tool","tool"]
            assert [r["tool_call_id"] for r in payload["messages"][2:]]==["weather-1","catalog-1"]
            message, finish = {"role":"assistant","content":"本站回放:潮湾明日 60.8°F,北岸灯塔可供查询。"}, "stop"
        return httpx.Response(200,json={"id":"mbsky-tool-call","object":"chat.completion","created":1,"model":"local-fixture",
            "choices":[{"index":0,"message":message,"finish_reason":finish}]})

    with httpx.Client(transport=httpx.MockTransport(transport),trust_env=False) as http:
        with openai.OpenAI(base_url="https://function-calls.invalid/v1",api_key="local-fixture",http_client=http,max_retries=0) as api:
            messages = [{"role":"user","content":"看明天潮湾的华氏温度与一个灯塔条目"}]
            first = api.chat.completions.create(model="local-fixture",messages=messages,tools=TOOLS,tool_choice="auto")
            choice = first.choices[0]
            assert choice.finish_reason=="tool_calls" and choice.message.tool_calls
            original = choice.message.model_dump(exclude_none=True)
            outputs = [dispatch(item) for item in choice.message.tool_calls]
            result = api.chat.completions.create(model="local-fixture",messages=[*messages,original,*outputs])
            assert result.choices[0].finish_reason=="stop"
    expect("call_roundtrip",["weather_card","catalog_search"],"Use the actual SDK, validate two tool calls, execute local tools and return both call IDs",
           [["weather-1","catalog-1"],[{"value":{"city":"潮湾","day":"明天","temperature":60.8,"unit":"fahrenheit"}},
                {"value":["北岸灯塔"]}],"本站回放:潮湾明日 60.8°F,北岸灯塔可供查询。",2],
           [[r["tool_call_id"] for r in outputs],[json.loads(r["content"]) for r in outputs],result.choices[0].message.content,len(packets)])


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

运行环境:CPython 3.12、OpenAI SDK 3.46.0、httpx2 2.16.0、jsonschema 4.26.0 与 Edge。

入口文件:projects/ai-agent-function-calls/function_calls.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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