from langchain.chat_models import init_chat_model# Follow the steps here to configure your credentials:# https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.htmlmodel = init_chat_model( "anthropic.claude-3-5-sonnet-20240620-v1:0", model_provider="bedrock_converse",)
system_prompt = """You are an agent designed to interact with a SQL database.Given an input question, create a syntactically correct {dialect} query to run,then look at the results of the query and return the answer. Unless the userspecifies a specific number of examples they wish to obtain, always limit yourquery to at most {top_k} results.You can order the results by a relevant column to return the most interestingexamples in the database. Never query for all the columns from a specific table,only ask for the relevant columns given the question.You MUST double check your query before executing it. If you get an error whileexecuting a query, rewrite the query and try again.DO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to thedatabase.To start you should ALWAYS look at the tables in the database to see what youcan query. Do NOT skip this step.Then you should query the schema of the most relevant tables.""".format( dialect=db.dialect, top_k=5,)
现在,使用模型、工具和提示词创建智能体:
from langchain.agents import create_agentagent = create_agent( model, tools, system_prompt=system_prompt,)
question = "Which genre on average has the longest tracks?"for step in agent.stream( {"messages": [{"role": "user", "content": question}]}, stream_mode="values",): step["messages"][-1].pretty_print()
#sql_agent.py for studioimport pathlibfrom langchain.agents import create_agentfrom langchain.chat_models import init_chat_modelfrom langchain_community.agent_toolkits import SQLDatabaseToolkitfrom langchain_community.utilities import SQLDatabaseimport requests# 初始化 LLMmodel = init_chat_model("gpt-5.4")# 获取数据库,存储在本地url = "https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db"local_path = pathlib.Path("Chinook.db")if local_path.exists(): print(f"{local_path} already exists, skipping download.")else: response = requests.get(url) if response.status_code == 200: local_path.write_bytes(response.content) print(f"File downloaded and saved as {local_path}") else: print(f"Failed to download the file. Status code: {response.status_code}")db = SQLDatabase.from_uri("sqlite:///Chinook.db")# 创建工具toolkit = SQLDatabaseToolkit(db=db, llm=model)tools = toolkit.get_tools()for tool in tools: print(f"{tool.name}: {tool.description}\n")# 使用 create_agentsystem_prompt = """You are an agent designed to interact with a SQL database.Given an input question, create a syntactically correct {dialect} query to run,then look at the results of the query and return the answer. Unless the userspecifies a specific number of examples they wish to obtain, always limit yourquery to at most {top_k} results.You can order the results by a relevant column to return the most interestingexamples in the database. Never query for all the columns from a specific table,only ask for the relevant columns given the question.You MUST double check your query before executing it. If you get an error whileexecuting a query, rewrite the query and try again.DO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to thedatabase.To start you should ALWAYS look at the tables in the database to see what youcan query. Do NOT skip this step.Then you should query the schema of the most relevant tables.""".format( dialect=db.dialect, top_k=5,)agent = create_agent( model, tools, system_prompt=system_prompt,)