Skip to main content

OpenAI 函数

某些OpenAI模型(如gpt-3.5-turbo-0613和gpt-4-0613)已经过微调,可以检测何时应该调用一个函数,并响应应传递给该函数的输入。在API调用中,您可以描述函数,并让模型智能地选择输出一个包含调用这些函数的参数的JSON对象。OpenAI Function APIs的目标是比一般的文本补全或聊天API更可靠地返回有效和有用的函数调用。

OpenAI Functions Agent是为这些模型设计的。

在使用时,需要先安装openai和google-search-results包,因为langchain包在内部调用它们。

pip install openai google-search-results

from langchain import LLMMathChain, OpenAI, SerpAPIWrapper, SQLDatabase, SQLDatabaseChain
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI

llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")
search = SerpAPIWrapper()
llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True)
db = SQLDatabase.from_uri("sqlite:///../../../../../notebooks/Chinook.db")
db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True)
tools = [
Tool(
name = "Search",
func=search.run,
description="useful for when you need to answer questions about current events. You should ask targeted questions"
),
Tool(
name="Calculator",
func=llm_math_chain.run,
description="useful for when you need to answer questions about math"
),
Tool(
name="FooBar-DB",
func=db_chain.run,
description="useful for when you need to answer questions about FooBar. Input should be in the form of a question containing full context"
)
]
agent = initialize_agent(tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True)
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")

结果:

    > Entering new  chain...

Invoking: `Search` with `{'query': 'Leo DiCaprio girlfriend'}`


Amidst his casual romance with Gigi, Leo allegedly entered a relationship with 19-year old model, Eden Polani, in February 2023.
Invoking: `Calculator` with `{'expression': '19^0.43'}`


> Entering new chain...
19^0.43```text
19**0.43
```
...numexpr.evaluate("19**0.43")...

Answer: 3.547023357958959
> Finished chain.
Answer: 3.547023357958959Leo DiCaprio's girlfriend is reportedly Eden Polani. Her current age raised to the power of 0.43 is approximately 3.55.

> Finished chain.


"Leo DiCaprio's girlfriend is reportedly Eden Polani. Her current age raised to the power of 0.43 is approximately 3.55."