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

function call学习之2

当然可以。我们将新增一个名为 is_legal_question 的函数来判断用户的问题是否与法律相关。如果问题是关于法律的,我们将调用 get_legal_answer 函数来获取答案。下面是完整的代码示例:
示例代码
import openai
import json

# 设置OpenAI API密钥
openai.api_key = "your-api-key"

def is_legal_question(question: str) -> bool:
    # 这里只是一个简单的示例,实际应用中应该使用更复杂的方法来判断
    keywords = ["law", "legal", "regulation", "rights", "court", "litigation"]
    return any(keyword in question.lower() for keyword in keywords)

def get_weather(city: str) -> dict:
    # 假设这是一个真实的天气API调用
    return {"city": city, "temperature": "20°C", "forecast": "sunny"}

def get_legal_answer(question: str) -> dict:
    # 这里只是一个示例,实际应用中应该调用真实的法律咨询API
    return {"question": question, "answer": "This is a sample legal answer."}

# 发送请求并处理响应
def process_request():
    # 用户输入
    user_input = input("Enter your query: ")

    # 判断是否询问天气
    if "weather" in user_input.lower():
        # 调用 get_weather 函数
        city = user_input.split(" ")[-1]  # 假设城市名是查询的最后一部分
        weather_info = get_weather(city)
        print(f"Weather Info: {weather_info['forecast']} in {weather_info['city']}, temperature is {weather_info['temperature']}.")

    # 判断是否为法律问题
    elif is_legal_question(user_input):
        # 调用 get_legal_answer 函数
        legal_answer = get_legal_answer(user_input)
        print(f"Legal Answer: {legal_answer['answer']}")

    else:
        # 构建请求数据
        request_data = {
            "model": "gpt-4",
            "messages": [
                {"role": "system", "content": "You are a helpful assistant that can call external functions. If the user asks about the weather, you should use the 'get_weather' function to retrieve the information. If the user asks a legal question, you should use the 'get_legal_answer' function to retrieve the information."},
                {"role": "user", "content": user_input}
            ],
            "functions": [
                {
                    "name": "get_weather",
                    "description": "Get the weather in a specific city.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "city": {
                                "type": "string",
                                "description": "The city name"
                            }
                        },
                        "required": ["city"]
                    }
                },
                {
                    "name": "get_legal_answer",
                    "description": "Get an answer to a legal question.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "question": {
                                "type": "string",
                                "description": "The legal question"
                            }
                        },
                        "required": ["question"]
                    }
                }
            ],
            "function_call": "auto"
        }

        # 发送请求
        response = openai.ChatCompletion.create(**request_data)

        # 获取函数调用的结果
        function_call = response.choices[0].message.function_call
        function_name = function_call.name
        function_args = json.loads(function_call.arguments)

        # 根据函数名称调用相应的函数
        if function_name == "get_weather":
            result = get_weather(function_args.get("city"))
        elif function_name == "get_legal_answer":
            result = get_legal_answer(function_args.get("question"))

        # 再次发送请求,这次是将函数调用的结果发送回去
        second_response = openai.ChatCompletion.create(
            model="gpt-4",
            messages=[
                *request_data["messages"],
                {"role": "assistant", "content": None, "function_call": {"name": function_name, "arguments": json.dumps(function_args)}},
                {"role": "function", "name": function_name, "content": json.dumps(result)}
            ]
        )

        # 输出最终的回复
        print(second_response.choices[0].message.content)

# 主函数
def main():
    while True:
        process_request()
        if input("Do you want to continue? (y/n): ").lower() != "y":
            break

if __name__ == "__main__":
    main()

说明:
1. 新增的函数:
•  is_legal_question: 用于判断用户的问题是否与法律相关。
•  get_legal_answer: 用于获取法律问题的答案。这里只是一个示例,实际应用中应该调用真实的法律咨询API。
2. 主流程:
•  用户输入问题。
•  程序先检查问题是否关于天气,如果是,则直接调用 get_weather 函数。
•  如果问题可能是关于法律的,程序调用 is_legal_question 函数进行判断。如果是法律问题,则调用 get_legal_answer 函数。
•  如果以上都不是,则构建请求数据并发送给GPT-4 API。
3. 请求数据:
•  包含了系统消息、用户消息、可调用的函数定义以及函数调用设置。
4. 处理响应:
•  根据API响应中的函数调用结果,调用相应的函数并获取结果。
•  再次发送请求,这次是将函数调用的结果发送回去。
•  输出最终的回复。
注意事项:
•  这个示例假设用户总是按照特定格式输入查询。实际应用中,你可能需要更复杂的逻辑来解析用户输入。
•  is_legal_question 函数使用了一个简单的关键词匹配方法来判断是否为法律问题。在实际应用中,你可能需要使用更复杂的自然语言处理技术来提高判断的准确性。
希望这个示例对你有所帮助!如果有任何疑问或需要进一步的帮助,请随时提问。


http://www.mrgr.cn/news/6820.html

相关文章:

  • 基于calico部署k8s集群k8s-1.23.6
  • JAVA之MAC详解以及子线程MDC传递
  • 探索厦门凯酷全科技有限公司抖音小店的实用魅力
  • Redis篇三:在Ubuntu下安装Redis
  • 用序列模型(GPT Bert Transformer等)进行图像处理的调研记录
  • 完美洗牌的秘密(四)——(反)完美洗牌第三定理
  • java nio AsynchronousChannel
  • Spring Boot 的 JDBC API 和 Spring Data JPA
  • 【超入門】用ComfyUI快速套用AnimateDiff工作流生成AI動畫
  • kubernetes k8s Secret 概述与配置讲解
  • 【docker综合篇】关于我用docker搭建了6个应用服务的事
  • Django后端架构开发:构建在线云媒资系统思路解析
  • 编译一个ROS包
  • Qt C++ 屏幕录制 保存mp4
  • DAMA CDGP:论述题真题解析之数据安全篇
  • python进阶语法---异常处理
  • 【访问者模式】设计模式系列:解锁复杂对象结构的秘密武器
  • UEFI 01记: 开发环境 在 ubuntu22 中搭建 edk2 开发环境并运行简单示例
  • 虚幻5|AI视力系统,听力系统,预测系统(2)听力系统
  • 《计算机组成原理》(第3版)考研真题