function calling实现


一、function calling介绍

大型模型如 GPT-4 被设计为能够与外部系统交互,比如通过 API 调用执行某些任务。例如,一个大型模型可能被编程为在需要时调用外部数据库查询函数、调用图像处理服务或执行其他外部功能。
在这里插入图片描述

二、chatglm3 function calling实现

import json
import requests
from transformers import AutoTokenizer, AutoModel, AutoConfig


model_path = "/code/ZhipuAI/chatglm3-6b"
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModel.from_pretrained(model_path, trust_remote_code=True).half().to("cuda:0")


def get_weather(loc):

    if loc == "北京" or loc == "beijing":
        return {"北京": "35"}
    else:
        return {"other": "25"}


weather_api_spec = [
    {
        'name': 'get_weather',
        'description': '输入城市名称,查询即时天气函数。',
        'parameters': {
            'type': 'object',
            'properties': {
                'loc': {
                    'description': '城市名称,中国城市要用对应城市的英文名称。',
                    'type': 'string',
                    'required': True
                }
            }
        }
    }
]

# 设定LLM身份
system_info = {
    "role": "system",
    "content": "尽可能最好地回答以下问题。你可以访问以下工具:",
    "tools": weather_api_spec
}


# 第一次调用LLM
prompt = "请问今天北京天气如何"
first_response, his = model.chat(tokenizer, prompt, history=[system_info])
print(first_response)

# 调用api
function_name = first_response.get("name")
parameters = first_response.get("parameters")
api_response = eval(f"{function_name}(**{parameters})")
print(api_response)

# 第二次调用LLM
prompt = {
        "role": "observation",  # 角色为observation,表示为外部函数发的消息
        "name": function_name,
        "content": api_response
    }

final_response, his = model.chat(tokenizer, str(prompt), history=his)
print(final_response)

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大虾飞哥哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值