Files
langchaingo/examples/sql-database-chain-example
Dmitry Ng 1fc129969f feat(llms): add provider-neutral structured output via WithStructuredOutput
Add a single WithStructuredOutput(StructuredOutputConfig) call option
carrying a raw JSON Schema (Draft 2020-12), so one contract yields the
same guarantee — a normal-final response is a single JSON value matching
the schema — on OpenAI, Anthropic, Bedrock (Converse and legacy), Google
AI, Vertex, and Ollama. Each provider maps it to its native mechanism;
the result is validated locally against the original schema in the new
llms/structuredoutput package. Also fixes a latent Converse gap where the
response stop reason was never surfaced on ContentChoice.StopReason.
2026-07-17 04:39:05 +03:00
..
2024-06-20 23:47:52 -04:00

SQL Database Chain Example

This example demonstrates how to use the langchaingo library to interact with a SQLite database using natural language queries. The program showcases the power of combining language models with database operations.

What This Example Does

  1. Database Setup:

    • Creates a SQLite database named foo.db.
    • Initializes two tables: foo and foo1.
    • Populates foo with 100 rows and foo1 with 200 rows of sample data.
  2. Language Model Integration:

    • Utilizes OpenAI's language model to interpret natural language queries.
  3. SQL Database Chain:

    • Creates a SQL Database Chain that combines the language model with database operations.
  4. Query Execution:

    • Demonstrates three different types of queries: a. A direct query to return rows from the foo table. b. A query using specific table names. c. A comparative query to determine which table has more data.

Key Features

  • Natural Language to SQL: Converts human-readable questions into SQL queries.
  • Flexible Querying: Allows querying the database without writing explicit SQL.
  • Multi-Table Analysis: Capable of comparing data across different tables.

How It Works

  1. The program sets up a sample SQLite database with two tables.
  2. It then initializes a language model (OpenAI in this case) and creates a SQL Database Chain.
  3. The chain is used to process natural language queries and execute them against the database.
  4. Results are printed to the console, showing the power of combining AI with database operations.

This example is perfect for developers looking to explore how language models can be used to simplify database interactions and make data querying more accessible to non-technical users.