Skip to main content

使用带有OpenAI功能的工具包

本笔记本展示了如何使用带有任意工具包的OpenAI功能代理。

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
from langchain.agents.agent_toolkits import SQLDatabaseToolkit
from langchain.schema import SystemMessage

API参考:

加载工具包

db = SQLDatabase.from_uri("sqlite:///../../../../../notebooks/Chinook.db")
toolkit = SQLDatabaseToolkit(llm=ChatOpenAI(), db=db)

设置特定于该工具包的系统消息

agent_kwargs = {
"system_message": SystemMessage(content="You are an expert SQL data analyst.")
}
llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")
agent = initialize_agent(
toolkit.get_tools(),
llm,
agent=AgentType.OPENAI_FUNCTIONS,
verbose=True,
agent_kwargs=agent_kwargs,
)
agent.run("how many different artists are there?")
> 进入新的链条...

调用: `sql_db_query`,参数为 `{'query': 'SELECT COUNT(DISTINCT artist_name) AS num_artists FROM artists'}`

错误: (sqlite3.OperationalError) no such table: artists
[SQL: SELECT COUNT(DISTINCT artist_name) AS num_artists FROM artists]
(Background on this error at: https://sqlalche.me/e/20/e3q8)

调用: `sql_db_list_tables`,参数为 `{}`

MediaType, Track, Playlist, sales_table, Customer, Genre, PlaylistTrack, Artist, Invoice, Album, InvoiceLine, Employee

调用: `sql_db_query`,参数为 `{'query': 'SELECT COUNT(DISTINCT artist_id) AS num_artists FROM Artist'}`

错误: (sqlite3.OperationalError) no such column: artist_id
[SQL: SELECT COUNT(DISTINCT artist_id) AS num_artists FROM Artist]
(Background on this error at: https://sqlalche.me/e/20/e3q8)

调用: `sql_db_query`,参数为 `{'query': 'SELECT COUNT(DISTINCT Name) AS num_artists FROM Artist'}`

[(275,)]数据库中有275位不同的艺术家。

> 链条结束。

'There are 275 different artists in the database.'