大模型学习_zhipu_ai调用函数-demo

from zhipuai import ZhipuAI
client = ZhipuAI(api_key="#") 

# 定义的函数
def get_weatcher(cityname):
    return "天津今天的天气为阴天,局部地区可能会有小雨"
    
# 使用 Chat Completion 接口向模型描述外部函数    
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weatcher",
            "description": "根据用户提供的地点信息,查询该地点当前的天气情况",
            "parameters": {
                "type": "string",
                "properties": {
                    "cityname": {
                        "type": "string",
                        "description": "城市名称,如:北京,天津",
                    },                   
                },
                "required": ["cityname"],
            },
        }
    }
]    
#与模型交互,触发模型对函数的调用
response = client.chat.completions.create(
    model="glm-3-turbo",
    messages= [
        {
            "role": "user",
            "content": "帮我查询一下天津今天的天气?"
        },
        {
            "role":"assistant",
            "content":"好的,我可以帮你查询,请问你想要查询哪个城市的天气?"
        },
          {
            "role": "user",
            "content": "天津"
        },
    ],
    tools=tools,
    tool_choice="auto",
)

# 返回结果
# 模型返回的内容中,有效的部分其实是关于 工具调用传参的部分
#(model='glm-3-turbo', created=1713071474, choices=[CompletionChoice(index=0, finish_reason='tool_calls', message=CompletionMessage(content=None, role='assistant', tool_calls=[CompletionMessageToolCall(id='call_8563695846623001693', function=Function(arguments='{"cityname":"天津"}', name='get_weatcher'), type='function')]))], request_id='8563695846623001693', id='8563695846623001693', usage=CompletionUsage(prompt_tokens=170, completion_tokens=23, total_tokens=193))

# 定义一个解析和执行的函数
def extract_function_and_execute(llm_output, messages):
    name = llm_output.choices[0].message.tool_calls[0].function.name
    params = json.loads(llm_output.choices[0].message.tool_calls[0].function.arguments)
    function_to_call = globals().get(name)
    if not function_to_call:
        raise ValueError(f"Function '{name}' not found")

    messages.append(
        {
            "role": "tool",
            "content": str(function_to_call(**params))
        }
    )
    return messages

print(extract_function_and_execute(response,[]))

#[{'role': 'tool', 'content': '天津今天的天气为阴天,局部地区可能会有小雨'}]

上一篇:OR36 链表的回文结构


下一篇:JMeter 连接数据库报错信息整理