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

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

1. 手撕FunctionCall

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

思路:

任务:让openai调用sum方法,对加法进行求和

1.定义sum方法,给openAi接口

2.让大模型自动识别用户问题,解释参数,获取调用方法id、方法名称、方法参数

3.把第二步的结果,给大模型,让大模型调用函数,并返回结果

2.代码

c 复制代码
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 复制代码
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
复制代码
相关推荐
hfhf15313 分钟前
电脑突然没有声音的可能原因与应对方法
java
dreams_dream2 小时前
docker启动jenkins,jenkins中调用docker
java·docker·jenkins
计算机-秋大田2 小时前
基于Spring Boot的国产动漫网站的设计与实现(LW+源码+讲解)
java·vue.js·spring boot·后端·课程设计
站在墙头上3 小时前
java虚拟机(JVM)以及各种参数详解
java·开发语言·jvm
shangxianjiao5 小时前
Javaweb后端全局异常处理器
java·springboot
奋进的小暄5 小时前
贪心算法(5)(java)k次取反后最大化的数组和
java·算法·贪心算法
chenchihwen5 小时前
ITSM统计分析:提升IT服务管理效能 实施步骤与操作说明
java·前端·数据库
java技术小馆6 小时前
责任链模式如何减少模块之间的耦合
java·数据库·设计模式·责任链模式
大溪地C6 小时前
Spring Boot3整合Knife4j(4.5.0)
java·数据库·spring boot