SQLToolkit 통합

SQLToolkit 통합 (SQLToolkit integration)

LangChain JavaScript로 SQLToolkit 툴과 통합해요.

SqlToolkit 툴킷 시작을 도와드려요. 더 자세한 내용은 Python SQL 툴킷 문서도 참고할 수 있어요.

이 툴킷에는 다음 툴이 포함돼요:

이름 설명
query-sql 이 툴의 입력은 상세하고 올바른 SQL 쿼리이며, 출력은 데이터베이스의 결과예요. 쿼리가 올바르지 않으면 오류 메시지가 반환돼요. 오류가 반환되면 쿼리를 다시 작성하고, 확인한 뒤 다시 시도하세요.
info-sql 이 툴의 입력은 쉼표로 구분된 테이블 목록이며, 출력은 해당 테이블들의 스키마와 샘플 행이에요. list-tables-sql을 먼저 호출해 테이블이 실제로 존재하는지 확인하세요! 예시 입력: "table1, table2, table3".
list-tables-sql 입력은 빈 문자열이며, 출력은 데이터베이스에 있는 테이블의 쉼표로 구분된 목록이에요.
query-checker 이 툴은 쿼리 실행 전에 쿼리가 올바른지 이중으로 확인하는 데 사용해요. query-sql로 쿼리를 실행하기 전에 항상 이 툴을 사용하세요!

이 툴킷은 SQL 데이터베이스에 질문하기, 쿼리 수행하기, 쿼리 검증하기 등에 유용해요.

설정 (Setup)

이 예제는 SQL Server, Oracle, MySQL 등에서 사용할 수 있는 샘플 데이터베이스인 Chinook 데이터베이스를 사용해요. 설정하려면 이 지침을 따라 코드가 있는 디렉터리에 .db 파일을 배치하세요.

개별 툴 실행의 자동 추적을 받으려면 아래 주석을 해제해 LangSmith API 키를 설정할 수도 있어요:

process.env.LANGSMITH_TRACING="true"
process.env.LANGSMITH_API_KEY="your-api-key"

설치 (Installation)

이 툴킷은 langchain 패키지에 있어요. typeorm peer 의존성도 설치해야 해요.

```bash npm npm install langchain @langchain/core typeorm ```
yarn add langchain @langchain/core typeorm
pnpm add langchain @langchain/core typeorm

인스턴스화 (Instantiation)

먼저 툴킷에 사용할 LLM을 정의해야 해요.

// @lc-docs-hide-cell

import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({
  model: "gpt-5.4-mini",
  temperature: 0,
})
import { SqlToolkit } from "@langchain/classic/agents/toolkits/sql"
import { DataSource } from "typeorm";
import { SqlDatabase } from "@langchain/classic/sql_db";

const datasource = new DataSource({
  type: "sqlite",
  database: "../../../../../../Chinook.db", // Replace with the link to your database
});
const db = await SqlDatabase.fromDataSourceParams({
  appDataSource: datasource,
});

const toolkit = new SqlToolkit(db, llm);

툴 (Tools)

사용 가능한 툴 보기:

const tools = toolkit.getTools();

console.log(tools.map((tool) => ({
  name: tool.name,
  description: tool.description,
})))
[
  {
    name: 'query-sql',
    description: 'Input to this tool is a detailed and correct SQL query, output is a result from the database.\n' +
      '  If the query is not correct, an error message will be returned.\n' +
      '  If an error is returned, rewrite the query, check the query, and try again.'
  },
  {
    name: 'info-sql',
    description: 'Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.\n' +
      '    Be sure that the tables actually exist by calling list-tables-sql first!\n' +
      '\n' +
      '    Example Input: "table1, table2, table3.'
  },
  {
    name: 'list-tables-sql',
    description: 'Input is an empty string, output is a comma-separated list of tables in the database.'
  },
  {
    name: 'query-checker',
    description: 'Use this tool to double check if your query is correct before executing it.\n' +
      '    Always use this tool before executing a query with query-sql!'
  }
]

에이전트 내에서 사용 (Use within an agent)

먼저 LangGraph가 설치되어 있는지 확인하세요:

```bash npm npm install @langchain/langgraph ```
yarn add @langchain/langgraph
pnpm add @langchain/langgraph
import { createAgent } from "@langchain/classic"

const agentExecutor = createAgent({ llm, tools });
const exampleQuery = "Can you list 10 artists from my database?"

const stream = await agentExecutor.streamEvents(
  { messages: [["user", exampleQuery]] },
  { version: "v3" },
);

for await (const snapshot of stream.values) {
  const lastMsg = snapshot.messages[snapshot.messages.length - 1];
  if (lastMsg.tool_calls?.length) {
    console.dir(lastMsg.tool_calls, { depth: null });
  } else if (lastMsg.content) {
    console.log(lastMsg.content);
  }
}
[
  {
    name: 'list-tables-sql',
    args: {},
    type: 'tool_call',
    id: 'call_LqsRA86SsKmzhRfSRekIQtff'
  }
]
Album, Artist, Customer, Employee, Genre, Invoice, InvoiceLine, MediaType, Playlist, PlaylistTrack, Track
[
  {
    name: 'query-checker',
    args: { input: 'SELECT * FROM Artist LIMIT 10;' },
    type: 'tool_call',
    id: 'call_MKBCjt4gKhl5UpnjsMHmDrBH'
  }
]
The SQL query you provided is:

```sql
SELECT * FROM Artist LIMIT 10;

This query is straightforward and does not contain any of the common mistakes listed. It simply selects all columns from the Artist table and limits the result to 10 rows.

Therefore, there are no mistakes to correct, and the original query can be reproduced as is:

SELECT * FROM Artist LIMIT 10;

[ { name: 'query-sql', args: { input: 'SELECT * FROM Artist LIMIT 10;' }, type: 'tool_call', id: 'call_a8MPiqXPMaN6yjN9i7rJctJo' } ] [{"ArtistId":1,"Name":"AC/DC"},{"ArtistId":2,"Name":"Accept"},{"ArtistId":3,"Name":"Aerosmith"},{"ArtistId":4,"Name":"Alanis Morissette"},{"ArtistId":5,"Name":"Alice In Chains"},{"ArtistId":6,"Name":"Antônio Carlos Jobim"},{"ArtistId":7,"Name":"Apocalyptica"},{"ArtistId":8,"Name":"Audioslave"},{"ArtistId":9,"Name":"BackBeat"},{"ArtistId":10,"Name":"Billy Cobham"}] Here are 10 artists from your database:

  1. AC/DC
  2. Accept
  3. Aerosmith
  4. Alanis Morissette
  5. Alice In Chains
  6. Antônio Carlos Jobim
  7. Apocalyptica
  8. Audioslave
  9. BackBeat
  10. Billy Cobham

> 출처: [문서](https://docs.langchain.com/oss/javascript/integrations/tools/sql)

## 본문

`SqlToolkit`은 SQL 데이터베이스용 툴킷으로, `query-sql`·`info-sql`·`list-tables-sql`·`query-checker` 툴을 제공해요. `@langchain/classic`의 `SqlToolkit`과 `@langchain/classic/sql_db`의 `SqlDatabase`, `typeorm`의 `DataSource`로 구성하고 `createAgent`에 연결해 에이전트가 데이터베이스에 대한 질문과 쿼리를 수행할 수 있게 해요.

## 더 알아보기 (Learn more)

* [LangChain JavaScript 툴 통합 문서](https://docs.langchain.com/oss/javascript/integrations/tools/sql)