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

加载工具包

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("有多少不同的艺术家?")
> Entering new  chain...

Invoking: `sql_db_query` with `{'query': 'SELECT COUNT(DISTINCT artist_name) AS num_artists FROM artists'}`


Error: (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)
Invoking: `sql_db_list_tables` with `{}`


MediaType, Track, Playlist, sales_table, Customer, Genre, PlaylistTrack, Artist, Invoice, Album, InvoiceLine, Employee
Invoking: `sql_db_query` with `{'query': 'SELECT COUNT(DISTINCT artist_id) AS num_artists FROM Artist'}`


Error: (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)
Invoking: `sql_db_query` with `{'query': 'SELECT COUNT(DISTINCT Name) AS num_artists FROM Artist'}`


[(275,)]There are 275 different artists in the database.

> Finished chain.





'There are 275 different artists in the database.'