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

server/2025/3/10 5:46:46/

【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].messagefrom 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):# 是否要调用 sumtool_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

http://www.ppmy.cn/server/173861.html

相关文章

数据结构:八大排序(冒泡,堆,插入,选择,希尔,快排,归并,计数)详解

目录 一.冒泡排序 二.堆排序 三.插入排序 四.选择排序 五.希尔排序 六.快速排序 1.Lomuto版本(前后指针法) 2.Lomuto版本的非递归算法 3.hoare版本(左右指针法) 4.挖坑法找分界值: 七.归并排序 八.计数排序…

【Linux】冯诺依曼体系与操作系统理解

🌟🌟作者主页:ephemerals__ 🌟🌟所属专栏:Linux 目录 前言 一、冯诺依曼体系结构 二、操作系统 1. 操作系统的概念 2. 操作系统存在的意义 3. 操作系统的管理方式 4. 补充:理解系统调用…

【leetcode100】组合总和Ⅱ

1、题目描述 给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的每个数字在每个组合中只能使用 一次 。 注意:解集不能包含重复的组合。 示例 1: 输入: candidates…

QOJ9700 Ying’s Cup(拉格朗日插值优化卷积,背包,二项式反演)

题意 原题链接 简要题意: 给你一棵 n n n 个点的树,你需要将 1 ∼ n 1 \sim n 1∼n 的排列填到树上的节点中。定义一个点为 局部最小值 满足与它相邻的点上的数都比它大。你需要对 k 1 , 2 , . . . , n k 1,2,...,n k1,2,...,n 都输出恰好有 k k…

19723分布式队列

19723分布式队列 ⭐️难度:中等 🌟考点:模拟、2024省赛 📖 📚 import javax.sound.sampled.Line; import java.math.BigInteger;import java.util.Arrays; import java.util.Scanner;public class Main {static …

labelme的使用

labelme的使用 打开labelme 在anaconda prompt中输入 labelmelabelme打开界面 利用labelme获得json文件 打开目录文件 利用labelme标注 先绘制多边形在标注标签 然后保存这样就会得到我们的json文件 json文件的操作 json文件转numpy文件 下面这个代码可以将json文…

华为欧拉系统 Tomcat 安装详解

1. 安装或确认安装 Java Tomcat 需要 Java 环境(JDK 或 JRE)才能运行。如果系统尚未安装 Java,可以使用以下命令安装 OpenJDK: # 更新软件包索引 yum update -y# 安装 OpenJDK 21(可根据需求安装其他版本,如 8、11、17 等) yum install -y java-21-openjdk java-21-op…

【SpringBoot】统一功能处理

目录 一、什么是统一功能处理 二、统一用户登录权限验证 2.1 定义拦截器 2.2 制定拦截规则 2.3 创建请求 2.4 拦截器实现原理 三、统一异常处理 四、统一数据格式返回 一、什么是统一功能处理 SpringBoot 统一功能处理: 定义:指在SpringBoot应…