RedSenior

导航

大概框架







这边列举一个简单的聊天案例:

点击查看代码
from langchain_openai import ChatOpenAI

def multiply(a: int, b: int) -> int:
    """Multiply a and b.

    Args:
        a: first int
        b: second int
    """
    return a * b

# This will be a tool
def add(a: int, b: int) -> int:
    """Adds a and b.

    Args:
        a: first int
        b: second int
    """
    return a + b

def divide(a: int, b: int) -> float:
    """Divide a and b.

    Args:
        a: first int
        b: second int
    """
    return a / b

tools = [add, multiply, divide]
llm = ChatOpenAI(model="gpt-3.5-turbo-0125",
                 openai_api_key="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")
llm_with_tools = llm.bind_tools(tools)

# 调用加法
response = llm_with_tools.invoke([{"role": "user", "content": "add 2 and 3"}])
print(response)

# 调用乘法
response = llm_with_tools.invoke([{"role": "user", "content": "multiply 4 and 5"}])
print(response)

# 调用除法
response = llm_with_tools.invoke([{"role": "user", "content": "divide 6 by 2"}])
print(response)

运行结果是这样的: ![](https://img2024.cnblogs.com/blog/3329340/202412/3329340-20241212230822456-26414787.png) 该程序定义了三个数学运算函数(加法、乘法、除法),并将它们作为工具绑定到 OpenAI 的聊天模型 ChatOpenAI

posted on 2024-12-12 23:11  RedLouie  阅读(2)  评论(0编辑  收藏  举报