当前位置: 首页 > news >正文

【GPT入门】第11课 FunctionCall调用本地代码入门

【GPT入门】第11课 FunctionCall调用代码入门

  • 1. 手撕FunctionCall
  • 2.代码
  • 3.functionCall的结果

1. 手撕FunctionCall

为了了解,funcationCall底层,手写一个functionCall多方法,并调用,体验

思路:
任务:让openai调用sum方法,对加法进行求和
1.定义sum方法,给openAi接口
2.让大模型自动识别用户问题,解释参数,获取调用方法id、方法名称、方法参数
3.把第二步的结果,给大模型,让大模型调用函数,并返回结果

2.代码

from openai import OpenAI
from dotenv import load_dotenv, find_dotenv
import json

_ = load_dotenv(find_dotenv())

client = OpenAI()


def print_json(data):
    """
    打印参数。如果参数是有结构的(如字典或列表),则以格式化的 JSON 形式打印;
    否则,直接打印该值。
    """
    if hasattr(data, 'model_dump_json'):
        data = json.loads(data.model_dump_json())

    if (isinstance(data, (list))):
        for item in data:
            print_json(item)
    elif (isinstance(data, (dict))):
        print(json.dumps(
            data,
            indent=4,
            ensure_ascii=False
        ))
    else:
        print(data)


def get_completion(messages, model="gpt-4o-mini"):
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=0.7,
        tools=[{  # 用 JSON 描述函数。可以定义多个。由大模型决定调用谁。也可能都不调用
            "type": "function",
            "function": {
                "name": "sum",
                "description": "加法器,计算一组数的和",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "numbers": {
                            "type": "array",
                            "items": {
                                "type": "number"
                            }
                        }
                    }
                }
            }
        }],
    )
    print("response:")
    print(response)
    return response.choices[0].message

from math import *

prompt = "Tell me the sum of 1,2,3,4,5,6,7,8,9,10"


messages = [
    {"role": "system", "content": "你是一个数学家"},
    {"role": "user", "content": prompt}
]



response = get_completion(messages)

# 把大模型的回复加入到对话历史中。必须有
messages.append(response)
print("------function call-----")
print(response)

if (response.tool_calls is not None):
    # 是否要调用 sum
    tool_call = response.tool_calls[0]
    if(tool_call.function.name == 'sum'):
        args = json.loads(tool_call.function.arguments)
        result = sum(args["numbers"])

        #把函数调用结果加入到对话历史中
        messages.append(
            {
                "tool_call_id":tool_call.id, #用于表示函数调用Id
                "role":"tool",
                "name":"sum",
                "content":str(result) #数值 result 必须转为字符串
             }
        )

        #再次调用大模型
        response = get_completion(messages)
        messages.append(response)
        print("-------最终 GPT 回复-------")
        print(response.content)

print("---------对话历史----------")
print_json(messages)

3.functionCall的结果

C:\ProgramData\anaconda3\envs\gptLearning\python.exe E:\workspace\gptLearning\gptLearning\les03\Lesson01_functionCalling.py 
response:
ChatCompletion(id='chatcmpl-B8xbekE9Xfke8t1AkftFpEzpcdtho', choices=[Choice(finish_reason='tool_calls', index=0, logprobs=None, message=ChatCompletionMessage(content=None, refusal=None, role='assistant', audio=None, function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_CcEYaIPwl1Ru63XmMm6qSGFD', function=Function(arguments='{"numbers":[1,2,3,4,5,6,7,8,9,10]}', name='sum'), type='function')]), content_filter_results={})], created=1741475450, model='gpt-4o-mini-2024-07-18', object='chat.completion', service_tier=None, system_fingerprint='fp_b705f0c291', usage=CompletionUsage(completion_tokens=32, prompt_tokens=79, total_tokens=111, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0)), prompt_filter_results=[{'prompt_index': 0, 'content_filter_results': {'hate': {'filtered': False, 'severity': 'safe'}, 'jailbreak': {'filtered': False, 'detected': False}, 'self_harm': {'filtered': False, 'severity': 'safe'}, 'sexual': {'filtered': False, 'severity': 'safe'}, 'violence': {'filtered': False, 'severity': 'safe'}}}])
------function call-----
ChatCompletionMessage(content=None, refusal=None, role='assistant', audio=None, function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_CcEYaIPwl1Ru63XmMm6qSGFD', function=Function(arguments='{"numbers":[1,2,3,4,5,6,7,8,9,10]}', name='sum'), type='function')])
response:
ChatCompletion(id='chatcmpl-B8xbfvdhavJ9RTAVxfAk3SmkIjVOT', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='The sum of the numbers 1 through 10 is 55.', refusal=None, role='assistant', audio=None, function_call=None, tool_calls=None))], created=1741475451, model='gpt-4o-mini-2024-07-18', object='chat.completion', service_tier='default', system_fingerprint='fp_06737a9306', usage=CompletionUsage(completion_tokens=16, prompt_tokens=118, total_tokens=134, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0)))
-------最终 GPT 回复-------
The sum of the numbers 1 through 10 is 55.
---------对话历史----------
{
    "role": "system",
    "content": "你是一个数学家"
}
{
    "role": "user",
    "content": "Tell me the sum of 1,2,3,4,5,6,7,8,9,10"
}
{
    "content": null,
    "refusal": null,
    "role": "assistant",
    "audio": null,
    "function_call": null,
    "tool_calls": [
        {
            "id": "call_CcEYaIPwl1Ru63XmMm6qSGFD",
            "function": {
                "arguments": "{\"numbers\":[1,2,3,4,5,6,7,8,9,10]}",
                "name": "sum"
            },
            "type": "function"
        }
    ]
}
{
    "tool_call_id": "call_CcEYaIPwl1Ru63XmMm6qSGFD",
    "role": "tool",
    "name": "sum",
    "content": "55"
}
{
    "content": "The sum of the numbers 1 through 10 is 55.",
    "refusal": null,
    "role": "assistant",
    "audio": null,
    "function_call": null,
    "tool_calls": null
}

Process finished with exit code 0

相关文章:

  • k8s部署deepseek基于cpu的部署
  • 数字人系统源码---v10技术五大底层架构链路全局开发思路
  • Python中与字符串操作相关的30个常用函数及其示例
  • 每日一题——乘积最大子数组
  • 4.桥接模式
  • 逻辑回归机器学习
  • Java零基础入门笔记:多线程
  • 元脑服务器:浪潮信息引领AI基础设施的创新与发展
  • NVIDIA显卡30年:从加密矿潮到AI霸权
  • 1个基于 Three.js 的 Vue3 组件库
  • JavaScript 是什么?
  • yolov5训练自己数据集的全流程+踩过的坑
  • Mysql5.7-yum安装和更改mysql数据存放路径-2020年记录
  • JVM常见面试题
  • 跨越时空的对话:图灵与GPT-4聊AI的前世今生
  • nats jetstream server code 分析
  • 【2025年26期免费获取股票数据API接口】实例演示五种主流语言获取股票行情api接口之沪深A股涨停股池数据获取实例演示及接口API说明文档
  • Prompt engineering设计原则
  • 【芯片验证】verificationguide上的74道SystemVerilog面试题
  • Phi-4-multimodal:图、文、音频统一的多模态大模型架构、训练方法、数据细节
  • 盐山做网站/互联网销售平台
  • 做网站读什么专业/深圳网站建设推广优化公司
  • 淘宝网站推广方案/裤子seo关键词
  • ajs17网站建设/百度推广后台登录
  • 咸阳网站建设/seo整站优化外包公司
  • 西安公司团建活动好去处/成都网站seo厂家