OpenAI代理:指定强制函数调用¶
如果您在colab上打开这个笔记本,您可能需要安装LlamaIndex 🦙。
In [ ]:
Copied!
%pip install llama-index-agent-openai
%pip install llama-index-llms-openai
%pip install llama-index-agent-openai
%pip install llama-index-llms-openai
In [ ]:
Copied!
!pip install llama-index
!pip install llama-index
In [ ]:
Copied!
import json
from typing import Sequence, List
from llama_index.llms.openai import OpenAI
from llama_index.core.llms import ChatMessage
from llama_index.core.tools import BaseTool, FunctionTool
from llama_index.agent.openai import OpenAIAgent
import json
from typing import Sequence, List
from llama_index.llms.openai import OpenAI
from llama_index.core.llms import ChatMessage
from llama_index.core.tools import BaseTool, FunctionTool
from llama_index.agent.openai import OpenAIAgent
In [ ]:
Copied!
def add(a: int, b: int) -> int: """对两个整数进行相加,并返回结果整数""" return a + badd_tool = FunctionTool.from_defaults(fn=add)def useless_tool() -> int: """这是一个无用的工具。""" return "这是一个无用的输出。"useless_tool = FunctionTool.from_defaults(fn=useless_tool)
def add(a: int, b: int) -> int: """对两个整数进行相加,并返回结果整数""" return a + badd_tool = FunctionTool.from_defaults(fn=add)def useless_tool() -> int: """这是一个无用的工具。""" return "这是一个无用的输出。"useless_tool = FunctionTool.from_defaults(fn=useless_tool)
In [ ]:
Copied!
llm = OpenAI(model="gpt-3.5-turbo-0613")
agent = OpenAIAgent.from_tools([useless_tool, add_tool], llm=llm, verbose=True)
llm = OpenAI(model="gpt-3.5-turbo-0613")
agent = OpenAIAgent.from_tools([useless_tool, add_tool], llm=llm, verbose=True)
"自动" 函数调用¶
该代理程序会自动选择有用的“添加”工具。
In [ ]:
Copied!
response = agent.chat( "5 + 2是多少?", tool_choice="auto") # 注意:function_call参数已被弃用# 使用tool_choice代替
response = agent.chat( "5 + 2是多少?", tool_choice="auto") # 注意:function_call参数已被弃用# 使用tool_choice代替
STARTING TURN 1 --------------- === Calling Function === Calling function: add with args: { "a": 5, "b": 2 } Got output: 7 ======================== STARTING TURN 2 ---------------
In [ ]:
Copied!
print(response)
print(response)
The sum of 5 and 2 is 7.
强制函数调用¶
代理被迫在选择“添加”工具之前调用“无用工具”。
In [ ]:
Copied!
response = agent.chat("What is 5 * 2?", tool_choice="useless_tool")
response = agent.chat("What is 5 * 2?", tool_choice="useless_tool")
STARTING TURN 1 --------------- === Calling Function === Calling function: useless_tool with args: {} Got output: This is a uselss output. ======================== STARTING TURN 2 --------------- === Calling Function === Calling function: add with args: { "a": 5, "b": 2 } Got output: 7 ======================== STARTING TURN 3 ---------------
In [ ]:
Copied!
print(response)
print(response)
The product of 5 and 2 is 10.
"None"函数调用¶
代理人被迫不使用工具
In [ ]:
Copied!
response = agent.chat("What is 5 * 2?", tool_choice="none")
response = agent.chat("What is 5 * 2?", tool_choice="none")
STARTING TURN 1 ---------------
In [ ]:
Copied!
print(response)
print(response)
The product of 5 and 2 is 10.