0


AI全栈大模型工程师(九)Function Calling 的机制

文章目录

Function Calling 的机制

Function Calling 示例 1:加法计算器

需求:用户输入任意可以用加法解决的问题,都能得到计算结果。


# 加载环境变量

import openai
import os
import json

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())  # 读取本地 .env 文件,里面定义了 OPENAI_API_KEY

openai.api_key = os.getenv('OPENAI_API_KEY')

def get_completion(messages, model="gpt-3.5-turbo"):
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0,  # 模型输出的随机性,0 表示随机性最小
        functions=[{  # 用 JSON 描述函数。可以定义多个,但是只有一个会被调用,也可能都不会被调用
            "name": "sum",
            "description": "计算数组中所有数字的和",
            "parameters": {
                "type": "object",
                "properties": {
                    "numbers": {
                        "type": "array",
                        "items": {
                            "type": "number"
                        }
                    }
                }
            },
        }],
    )
    return response.choices[0].message

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

prompt = "桌上有 2 个苹果,四个桃子和 3 本书,一共有几个水果?"
#prompt = "1+2+3+4+...+99+100=?"
messages = [
    {"role": "system", "content": "你是一个小学数学老师,你要教学生加法"},
    {"role": "user", "content": prompt}
]
response = get_completion(messages)
messages.append(response)  # 把大模型的回复加入到对话中
print(response)

# 如果返回的是函数调用结果,则打印出来

if (response.get("function_call")):

    # 是否要调用 sum

​    if (response["function_call"]["name"] == "sum"):
​        args = json.loads(response["function_call"]["arguments"])
​        result = sum(args["numbers"])
​        print(result)
​        messages.append(
​            {"role": "function", "name": "sum", "content": str(result)})  # 整数 result,必须转成字符串
​        print(get_completion(messages).content)

Function Calling 实例 2:四则混合运算计算器

def get_completion(messages, model="gpt-4"):
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0,  # 模型输出的随机性,0 表示随机性最小
        functions=[  # 用 JSON 描述函数。可以定义多个,但是只有一个会被调用,也可能都不会被调用
            {
                "name": "sum",
                "description": "计算数组中所有数字的和",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "numbers": {
                            "type": "array",
                            "items": {
                                "type": "number",
                                "description": "必须是数值类型"
                            }
                        }
                    }
                },
            },
            {
                "name": "subtract",
                "description": "计算 a - b 的值",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "a": {
                            "type": "number",
                            "description": "被减数,必须是数值类型"
                        },
                        "b": {
                            "type": "number",
                            "description": "减数,必须是数值类型"
                        }
                    }
                },
            },
            {
                "name": "multiply",
                "description": "计算数组中所有数字的积",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "numbers": {
                            "type": "array",
                            "items": {
                                "type": "number",
                                "description": "必须是数值类型"
                            }
                        }
                    }
                },
            },
            {
                "name": "divide",
                "description": "计算 a/b 的值",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "a": {
                            "type": "number",
                            "description": "被除数,必须是数值类型"
                        },
                        "b": {
                            "type": "number",
                            "description": "除数,必须是数值类型"
                        }
                    }
                },
            }
        ],
    )
    return response.choices[0].message

prompt = "6 * 3 / (4+2) = ?"

# prompt = "桌上有 2 个苹果,四个桃子和 3 本书,水果比书多多少?"

# prompt = """

# 让我们一步步计算:小明在一家水果店买水果。他买了X斤苹果,每斤10元;4斤香蕉,每斤5元;

# 和3斤橙子,每斤8元。他手头有100元。请问小明买完这些水果后,他还剩下多少钱?

#"""

messages = [
    {"role": "system", "content": "你是一个小学数学老师,你要教学生四则混合运算"},
    {"role": "user", "content": prompt}
]

response = get_completion(messages)
messages.append(response)  # 把大模型的回复加入到对话中。非常重要!
print(response)
while (response.get("function_call")):
    # 是否要调用 sum
    args = json.loads(response["function_call"]["arguments"])
    function_name = response["function_call"]["name"]

    if (function_name == "sum"):
        result = sum(args["numbers"])
    elif (function_name == "subtract"):
        result = args["a"] - args["b"]
    elif (function_name == "multiply"):
        result = 1
        for number in args["numbers"]:
            result *= number
    elif (function_name == "divide"):
        result = args["a"] / args["b"]
    else:
        result = "Unknown function"
    
    print(result)
    messages.append(
        {"role": "function", "name": function_name, "content": str(result)})
    response = get_completion(messages)
    messages.append(response)  # 把大模型的回复加入到对话中
    print(response)

print(response.content)

后记

📢博客主页:https://manor.blog.csdn.net

📢欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正!
📢本文由 Maynor 原创,首发于 CSDN博客🙉
📢不能老盯着手机屏幕,要不时地抬起头,看看老板的位置⭐
📢专栏持续更新,欢迎订阅:https://blog.csdn.net/xianyu120/category_12471942.html


本文转载自: https://blog.csdn.net/xianyu120/article/details/133947230
版权归原作者 AI_Maynor 所有, 如有侵权,请联系我们删除。

“AI全栈大模型工程师(九)Function Calling 的机制”的评论:

还没有评论