|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import sqlite3 |
| 16 | +import tempfile |
| 17 | + |
| 18 | +from langchain_community.agent_toolkits.sql.toolkit import SQLDatabaseToolkit |
| 19 | +from langchain_community.utilities.sql_database import SQLDatabase |
| 20 | +from langchain_core.messages import HumanMessage, SystemMessage |
| 21 | +from langchain_core.runnables.config import ( |
| 22 | + RunnableConfig, |
| 23 | +) |
| 24 | +from langgraph.checkpoint.memory import InMemorySaver |
| 25 | +from langgraph.prebuilt import create_react_agent |
| 26 | +from opentelemetry import trace |
| 27 | +from sqlalchemy import create_engine |
| 28 | + |
| 29 | +from patched_vertexai import PatchedChatVertexAI |
| 30 | +from utils import ask_prompt, console, print_markdown, render_messages |
| 31 | + |
| 32 | +SYSTEM_PROMPT = SystemMessage( |
| 33 | + content=f"""\ |
| 34 | +You are a helpful AI assistant with a mastery of database design and querying. You have access |
| 35 | +to an ephemeral sqlite3 database that you can query and modify through some tools. Help answer |
| 36 | +questions and perform actions. Follow these rules: |
| 37 | +
|
| 38 | +- Make sure you always use sql_db_query_checker to validate SQL statements **before** running |
| 39 | + them. In pseudocode: `checked_query = sql_db_query_checker(query); |
| 40 | + sql_db_query(checked_query)`. |
| 41 | +- Be creative and don't ask for permission! The database is ephemeral so it's OK to make some mistakes. |
| 42 | +- The sqlite version is {sqlite3.sqlite_version} which supports multiple row inserts. |
| 43 | +- Always prefer to insert multiple rows in a single call to the sql_db_query tool, if possible. |
| 44 | +- You may request to execute multiple sql_db_query tool calls which will be run in parallel. |
| 45 | +
|
| 46 | +If you make a mistake, try to recover.""" |
| 47 | +) |
| 48 | + |
| 49 | +INTRO_TEXT = """\ |
| 50 | +Starting agent using ephemeral SQLite DB {dbpath}. This demo allows you to chat with an Agent |
| 51 | +that has full access to an ephemeral SQLite database. The database is initially empty. It is |
| 52 | +built with the the LangGraph prebuilt **ReAct Agent** and the **SQLDatabaseToolkit**. Here are some samples you can try: |
| 53 | +
|
| 54 | +**Weather** |
| 55 | +- Create a new table to hold weather data. |
| 56 | +- Populate the weather database with 20 example rows. |
| 57 | +- Add a new column for weather observer notes |
| 58 | +
|
| 59 | +**Pets** |
| 60 | +- Create a database table for pets including an `owner_id` column. |
| 61 | +- Add 20 example rows please. |
| 62 | +- Create an owner table. |
| 63 | +- Link the two tables together, adding new columns, values, and rows as needed. |
| 64 | +- Write a query to join these tables and give the result of owners and their pets. |
| 65 | +- Show me the query, then the output as a table |
| 66 | +
|
| 67 | +--- |
| 68 | +""" |
| 69 | + |
| 70 | +tracer = trace.get_tracer(__name__) |
| 71 | + |
| 72 | + |
| 73 | +def run_agent(*, model_name: str, recursion_limit: int = 50) -> None: |
| 74 | + model = PatchedChatVertexAI(model=model_name) |
| 75 | + checkpointer = InMemorySaver() |
| 76 | + |
| 77 | + # Ephemeral sqlite database per run |
| 78 | + _, dbpath = tempfile.mkstemp(suffix=".db") |
| 79 | + engine = create_engine( |
| 80 | + f"sqlite:///{dbpath}", |
| 81 | + isolation_level="AUTOCOMMIT", |
| 82 | + ) |
| 83 | + |
| 84 | + # The agent has access to the SQL database through these tools |
| 85 | + db = SQLDatabase(engine) |
| 86 | + toolkit = SQLDatabaseToolkit(db=db, llm=model) |
| 87 | + # Filter out sql_db_list_tables since it only lists the initial tables |
| 88 | + tools = [tool for tool in toolkit.get_tools() if tool.name != "sql_db_list_tables"] |
| 89 | + |
| 90 | + # Use the prebuilt ReAct agent graph |
| 91 | + # https://langchain-ai.github.io/langgraph/agents/agents/ |
| 92 | + agent = create_react_agent( |
| 93 | + model, tools, checkpointer=checkpointer, prompt=SYSTEM_PROMPT |
| 94 | + ) |
| 95 | + config: RunnableConfig = { |
| 96 | + "configurable": {"thread_id": "default"}, |
| 97 | + "recursion_limit": recursion_limit, |
| 98 | + } |
| 99 | + |
| 100 | + print_markdown(INTRO_TEXT.format(dbpath=dbpath)) |
| 101 | + |
| 102 | + while True: |
| 103 | + # Accept input from the user |
| 104 | + try: |
| 105 | + prompt_txt = ask_prompt() |
| 106 | + except (EOFError, KeyboardInterrupt): |
| 107 | + print_markdown("Exiting...") |
| 108 | + break |
| 109 | + |
| 110 | + if not prompt_txt: |
| 111 | + continue |
| 112 | + prompt = HumanMessage(prompt_txt) |
| 113 | + |
| 114 | + with console.status("Agent is thinking"): |
| 115 | + # [START opentelemetry_langgraph_agent_span] |
| 116 | + # Invoke the agent within a span |
| 117 | + with tracer.start_as_current_span("invoke agent"): |
| 118 | + result = agent.invoke({"messages": [prompt]}, config=config) |
| 119 | + # [END opentelemetry_langgraph_agent_span] |
| 120 | + |
| 121 | + # Print history |
| 122 | + render_messages(result["messages"]) |
0 commit comments