AIでデータソースをクエリする
データベースについて自然言語で質問し、回答、グラフ、およびそれらを生成するために使用されたクエリを取得できます。
Query with AIを使用する理由
ユーザーはデータベースから回答を得たいと思っていますが、SQLを書くことはできません。プロダクトチームはチケットを起票せずに「各地域のアクティブユーザーは何人か」を知りたいと考えています。サポートチームはスキーマを学ばずに「過去24時間で最も多かったエラーメッセージ」を見つけたいと考えています。
データベースへの自然言語インターフェースを構築するには、プロンプトエンジニアリング、スキーマのシリアライズ、クエリの検証、エラー修正、結果のフォーマットを自分で実装する必要があります。Query with AIでは、バックエンドがこれらすべてを処理します。
- TypeScript
- Python
const response = await this.squid.ai().executeAiQuery(
'postgres',
'How many users signed up last week, broken down by country?',
);
console.log(response.answer); // "1,247 users signed up last week..."
console.log(response.executedQueries); // The actual SQL Squid ran
response = await self.squid.execute_ai_query(
'postgres',
'How many users signed up last week, broken down by country?',
)
print(response['answer']) # "1,247 users signed up last week..."
print(response['executedQueries']) # The actual SQL Squid ran
自然言語で質問するだけで、計画、生成、実行、説明が行われます。
概要
Query with AIは、自然言語のプロンプトとデータベースコネクタを受け取り、3段階のパイプラインを実行します。
- コレクションの選択:スキーマから関連するテーブルまたはコレクションを選択します
- クエリの生成:データベース固有の方言でネイティブクエリを生成し、構文エラーが発生した場合は自動的に再試行します
- 結果の分析:生の結果行を自然言語の回答に変換します
回答、使用したクエリ、および必要に応じて生の結果行を返します。
Query with AIを使用する場面
| ユースケース | 推奨事項 |
|---|---|
| ユーザーがデータベースについて自然言語で質問できるようにする | Query with AI |
| データからチャートやグラフを生成する | analyzeResultsOptions.enableCodeInterpreter: trueを指定したQuery with AI |
| 固定された予測可能なクエリを実行する | Database clientを直接使用する |
| AI agentがインテグレーションごとにカスタムロジックでデータを取得できるようにする | インテグレーションタイプに関連付けられたAI functionを使用する |
| アップロードされたドキュメントを検索する | Knowledge Basesを使用する |
仕組み
- クライアントのプロンプトがバックエンドに送信され、バックエンドが
executeAiQuery(integrationId, prompt, options)を呼び出します - Squidがインテグレーションのスキーマを読み込み、プロンプトとともにモデルに送信します
- (オプション)ステージ1:コレクションの選択。 スキーマが大きい場合、Squidはモデルに関連するテーブルまたはコレクションのサブセットを選択するよう求めます。スキーマが小さい場合、このステージはスキップされます。
- ステージ2:クエリの生成。 モデルがデータベース固有の方言(SQL、Mongo aggregation、Elasticsearch DSLなど)でクエリを生成します。Squidがそのクエリを実行します。構文エラーがある場合、Squidはエラーをモデルに返し、設定可能な上限まで再試行します。
- ステージ3:結果の分析。 モデルが生の結果行を読み取り、自然言語の回答を生成します。オプションで、コードインタープリターでPythonを実行して統計を計算したり、チャートを描画したりします。
- 完全なレスポンス(
answer、executedQueriesなど)がコードに返されます。
クイックスタート
前提条件
squid initで初期化されたSquidバックエンドプロジェクト- Squidアプリケーションに追加されたデータベースコネクタ
- コネクタに設定されたスキーマの説明(以下のスキーマを設定するを参照)
ステップ1:スキーマを設定する
Squidはコレクション、フィールド、およびそれらの説明をモデルに送信します。説明が詳しいほど、モデルが生成するクエリの品質が向上します。Squid Consoleで説明を設定します。
- Squid Consoleを開き、Connectorsタブをクリックします
- データベースコネクタを見つけ、ellipsis (…)メニューをクリックしてからSchemaをクリックします
- Rediscover schemaをクリックして、コレクションとフィールドのメタデータをインポートします
- 各コレクションの横にある鉛筆アイコンをクリックして説明を追加します。次に、各フィールドの**ellipsis (…)**をクリックし、Edit fieldを選択してフィールドごとの説明を追加します
- 必要に応じて、Generate Descriptions with AIをクリックすると、Squidが説明を生成します。この操作では、データの少量のサンプルがモデルに送信されます。データをモデルに送信したくない場合は、代わりに説明を手動で記述してください。Query with AI自体はデータ行をモデルに送信せず、スキーマのみを送信します。
- Save schemaをクリックします
ステップ2:セキュリティルールを記述する
Query with AIはコネクタ内のあらゆるデータを読み取れるため、セキュリティルールで保護する必要があります。SquidServiceのメソッドに@secureAiQueryを追加します。
- TypeScript
- Python
import { secureAiQuery, SquidService } from '@squidcloud/backend';
export class SecurityService extends SquidService {
@secureAiQuery('postgres')
allowAiQuery(): boolean {
// Only authenticated users can run AI queries against the postgres connector.
return this.isAuthenticated();
}
}
from squidcloud_backend import SquidService, secure_ai_query
class SecurityService(SquidService):
@secure_ai_query('postgres')
def allow_ai_query(self) -> bool:
# Only authenticated users can run AI queries against the postgres connector.
return self.is_authenticated()
デコレーターに渡すインテグレーションIDは、Squid ConsoleのコネクタIDと一致する必要があります。組み込みデータベースを保護するには、引数を渡さないでください。
ステップ3:呼び出しをexecutableでラップする
- TypeScript
- Python
import { executable, SquidService } from '@squidcloud/backend';
export class DataAiService extends SquidService {
@executable()
async askAboutData(question: string): Promise<string> {
this.assertIsAuthenticated();
const response = await this.squid.ai().executeAiQuery('postgres', question);
if (!response.success) {
throw new Error(response.answer || 'AI query failed');
}
// Log the query for debugging in the Squid Console logs.
for (const executed of response.executedQueries) {
console.log(`Executed: ${executed.query}`);
}
return response.answer;
}
}
from squidcloud_backend import SquidService, executable
class DataAiService(SquidService):
@executable()
async def ask_about_data(self, question: str) -> str:
self.assert_is_authenticated()
response = await self.squid.execute_ai_query('postgres', question)
if not response.get('success'):
raise RuntimeError(response.get('answer') or 'AI query failed')
# Log the query for debugging in the Squid Console logs.
for executed in response.get('executedQueries', []):
print(f"Executed: {executed['query']}")
return response['answer']
TypeScriptでは、メソッドはsquid.ai().executeAiQuery()にあります。Pythonでは、Squidクライアント上のsquid.execute_ai_query()に直接あります。
ステップ4:バックエンドを実行またはデプロイする
squid start
クラウドへのデプロイについては、バックエンドのデプロイを参照してください。
ステップ5:クライアントから呼び出す
const answer = await squid.executeFunction('askAboutData', 'How many orders shipped this week?');
console.log(answer);
認証とセキュリティ
Query with AIは@secureAiQueryデコレーターで保護されています。各呼び出しは、現在のリクエストに対してtrueを返す@secureAiQuery(integrationId)ルールに一致する必要があります。一致しない場合、呼び出しはUNAUTHORIZEDで拒否されます。
デコレーターはインテグレーションIDを引数に取ります。組み込みデータベースを保護するには、引数を省略してください。
- TypeScript
- Python
import { secureAiQuery, SquidService } from '@squidcloud/backend';
import { AiQueryContext } from '@squidcloud/backend';
export class SecurityService extends SquidService {
@secureAiQuery('postgres')
allowProductionQueries(context: AiQueryContext): boolean {
// The context contains the prompt and options the user submitted.
// Inspect them to apply finer-grained checks.
if (!this.isAuthenticated()) return false;
const userAuth = this.getUserAuth();
return userAuth?.attributes?.['role'] === 'analyst';
}
}
from squidcloud_backend import SquidService, secure_ai_query
class SecurityService(SquidService):
@secure_ai_query('postgres')
def allow_production_queries(self) -> bool:
if not self.is_authenticated():
return False
user_auth = self.get_user_auth()
return (user_auth or {}).get('attributes', {}).get('role') == 'analyst'
Squidのセキュリティルールとリクエストコンテキストの詳細については、セキュリティルールを参照してください。
主要な概念
3段階のパイプライン
executeAiQueryの各呼び出しは3つのステージを通過し、それぞれを個別に調整できます。
| ステージ | 目的 | オプションキー |
|---|---|---|
| コレクションの選択 | 関連するテーブルやコレクションのサブセットを選択する | selectCollectionsOptions |
| クエリの生成 | ネイティブクエリを生成し、構文エラー時に再試行する | generateQueryOptions |
| 結果の分析 | 結果行を自然言語の回答に変換する(必要に応じてチャートも生成) | analyzeResultsOptions |
スキーマ全体がモデルのコンテキストに収まるほど小さい場合、Squidはコレクション選択ステージを自動的にスキップします。selectCollectionsOptions.runModeでこの動作を上書きできます。
サポートされるデータベース
Query with AIは、Squidが自然言語によるクエリをサポートするデータベースコネクタで使用できます。
- リレーショナルSQL:MySQL、PostgreSQL、BigQuery、Snowflake、Oracle、SQL Server、SAP HANA、CockroachDB、ClickHouse、Databricks
- MongoDBおよびSquidの組み込みデータベース
- Elasticsearch
Squidが生成するクエリ言語はコネクタの種類によって異なります。リレーショナルデータベースではSQL、MongoDBではaggregation pipeline、Elasticsearchではquery DSLを使用します。
レスポンスオブジェクト
AiQueryResponseには次のフィールドがあります。
| フィールド | 型 | 説明 |
|---|---|---|
answer | string | AIが生成した自然言語の回答 |
explanation | string | undefined | 回答の導出方法に関する説明(オプション) |
executedQueries | ExecutedQueryInfo[] | Squidが実際に実行したネイティブクエリ。各エントリにはquery、purpose、success、rawResultがあります。 |
success | boolean | パイプラインが正常に完了した場合はtrue |
usedCodeInterpreter | boolean | undefined | 分析ステージでコードインタープリターを実行した場合はtrue |
clarificationQuestion | string | undefined | allowClarificationが有効で、モデルが追加情報を必要とする場合に設定される |
queryMarkdownType | string | undefined | クエリの描画に使用するMarkdown言語('sql'、'json'、'pure') |
providedDefinitions | AiQueryProvidedDefinition[] | undefined | モデルに渡されたglossaryの用語。それぞれにtype、id、nameがあります |
ExecutedQueryInfoのフィールド:
| フィールド | 型 | 説明 |
|---|---|---|
query | string | Squidが実行したネイティブクエリの文字列 |
purpose | string | undefined | このクエリで取得しようとした内容 |
success | boolean | この個別のクエリが正常に実行されたかどうか |
rawResult | AiFileUrl | undefined | 生の結果ファイルのURL(enableRawResults: trueの場合のみ設定) |
1回の呼び出しで複数のクエリが実行されることがあります。上限は1回の呼び出しにつき5クエリです。
設定オプション
AiQueryOptionsを使用して、各ステージの動作を調整できます。
トップレベルオプション
| オプション | 型 | 説明 |
|---|---|---|
instructions | string | 各ステージに追加される自由形式の指示 |
enableRawResults | boolean | 各クエリの結果行をファイルストレージにアップロードし、executedQueries[].rawResultにURLを返す |
selectCollectionsOptions | AiQuerySelectCollectionsOptions | 以下を参照 |
generateQueryOptions | AiQueryGenerateQueryOptions | 以下を参照 |
analyzeResultsOptions | AiQueryAnalyzeResultsOptions | 以下を参照 |
memoryOptions | AiAgentMemoryOptions | フォローアップの質問に使用する会話メモリ。agent memoryを参照してください。 |
generateQueriesOnly | boolean | 実行と分析をスキップし、生成されたクエリのみを返す |
validateWithAiOptions | AiQueryValidateWithAiOptions | 実行前に2回目のAI処理を行い、生成されたクエリを検証する |
ontologyIds | string[] | これらのontologyのリレーションシップを使用してテーブルを結合する |
semanticLayer | AiQuerySemanticLayerOptions | { enabled: false }を指定すると、データベースのglossaryの用語をモデルに渡さなくなる |
コレクション選択オプション
パイプラインのステージ1を制御します。
| フィールド | 型 | 説明 |
|---|---|---|
collectionsToUse | string[] | クエリをこのコレクションのサブセットに制限する。省略すると、Squidはスキーマ全体を対象とする |
runMode | 'default' | 'force' | 'disable' | 'default'ではステージを実行するかSquidが判断する。'force'では常に実行する。'disable'ではスキップし、スキーマ全体(またはcollectionsToUse)をステージ2に渡す |
aiOptions | AiChatOptions | このステージで使用するモデルとチャットオプションを上書きする |
クエリ生成オプション
パイプラインのステージ2を制御します。
| フィールド | 型 | 説明 |
|---|---|---|
aiOptions | AiChatOptions | このステージで使用するモデルとチャットオプションを上書きする |
maxErrorCorrections | number | 生成されたクエリに構文エラーがある場合の自動再試行の最大回数。デフォルトは2、最大は10 |
agentId | string | このステージで特定のAI agentを使用する |
allowClarification | boolean | プロンプトが曖昧な場合や回答できない場合に、推測する代わりにclarificationQuestionを返す |
結果分析オプション
パイプラインのステージ3を制御します。
| フィールド | 型 | 説明 |
|---|---|---|
disabled | boolean | 分析ステージを完全にスキップする。レスポンスには生成されたクエリと生の結果のみが含まれる |
enableCodeInterpreter | boolean | Pythonコードインタープリターで分析を実行する。統計の計算やチャートの描画が可能 |
aiOptions | AiChatOptions | このステージで使用するモデルとチャットオプションを上書きする |
agentId | string | このステージで特定のAI agentを使用する |
コード例
Query with AIを特定のテーブルに制限する
データベースの残りの部分を公開せずに、ユーザーが一部について質問できるようにしたい場合に便利です。
- TypeScript
- Python
const response = await this.squid.ai().executeAiQuery('mysql', 'List all people, showing only their ID and height', {
selectCollectionsOptions: {
runMode: 'disable',
collectionsToUse: ['people'],
},
enableRawResults: true,
});
// Download and inspect the raw rows produced by the query.
const url = response.executedQueries[0]?.rawResult?.url;
if (url) {
const fileResponse = await fetch(url);
const rows = await fileResponse.json();
console.log(rows);
}
response = await self.squid.execute_ai_query(
'mysql',
'List all people, showing only their ID and height',
options={
'selectCollectionsOptions': {
'runMode': 'disable',
'collectionsToUse': ['people'],
},
'enableRawResults': True,
},
)
# Download and inspect the raw rows produced by the query.
raw_result = (response.get('executedQueries') or [{}])[0].get('rawResult')
if raw_result:
import httpx
async with httpx.AsyncClient() as http:
file_response = await http.get(raw_result['url'])
rows = file_response.json()
print(rows)
コードインタープリターでチャートを生成する
enableCodeInterpreterがtrueの場合、分析ステージでPythonを実行して集計やチャートの描画ができます。「Xのチャートを表示して」といった要求に対応する方法です。
- TypeScript
- Python
const response = await this.squid.ai().executeAiQuery('postgres', 'Plot a bar chart of order volume per region for last quarter.', {
analyzeResultsOptions: {
enableCodeInterpreter: true,
},
});
console.log(response.answer);
console.log('Used code interpreter:', response.usedCodeInterpreter);
response = await self.squid.execute_ai_query(
'postgres',
'Plot a bar chart of order volume per region for last quarter.',
options={
'analyzeResultsOptions': {
'enableCodeInterpreter': True,
},
},
)
print(response['answer'])
print('Used code interpreter:', response.get('usedCodeInterpreter'))
推測せずに確認を求める
- TypeScript
- Python
const response = await this.squid.ai().executeAiQuery('mysql', 'Show me the top users.', {
generateQueryOptions: { allowClarification: true },
});
if (response.clarificationQuestion) {
// Surface this back to the user, then re-call with the refined prompt.
return { needsClarification: response.clarificationQuestion };
}
return { answer: response.answer };
response = await self.squid.execute_ai_query(
'mysql',
'Show me the top users.',
options={
'generateQueryOptions': {'allowClarification': True},
},
)
if response.get('clarificationQuestion'):
# Surface this back to the user, then re-call with the refined prompt.
return {'needsClarification': response['clarificationQuestion']}
return {'answer': response['answer']}
フォローアップの質問にメモリを使用する
- TypeScript
- Python
// First question
await this.squid.ai().executeAiQuery('mysql', 'How many people taller than 6 feet do we have?', {
memoryOptions: { memoryId: 'session-42', memoryMode: 'read-write' },
});
// Follow-up that depends on the prior context
const followUp = await this.squid.ai().executeAiQuery('mysql', 'What are their average ages?', {
memoryOptions: { memoryId: 'session-42', memoryMode: 'read-write' },
});
# First question
await self.squid.execute_ai_query(
'mysql',
'How many people taller than 6 feet do we have?',
options={
'memoryOptions': {'memoryId': 'session-42', 'memoryMode': 'read-write'},
},
)
# Follow-up that depends on the prior context
follow_up = await self.squid.execute_ai_query(
'mysql',
'What are their average ages?',
options={
'memoryOptions': {'memoryId': 'session-42', 'memoryMode': 'read-write'},
},
)
クエリ生成に特定のモデルを使用する
- TypeScript
- Python
await this.squid.ai().executeAiQuery('mysql', 'How many users signed up yesterday?', {
generateQueryOptions: {
aiOptions: { model: 'claude-sonnet-5-5' },
maxErrorCorrections: 5,
},
validateWithAiOptions: { enabled: true },
});
await self.squid.execute_ai_query(
'mysql',
'How many users signed up yesterday?',
options={
'generateQueryOptions': {
'aiOptions': {'model': 'claude-sonnet-5-5'},
'maxErrorCorrections': 5,
},
'validateWithAiOptions': {'enabled': True},
},
)
Squid Consoleのテスト用UIを使用する
Query with AIを試すためにコードを書く必要はありません。スキーマを設定したら、Squid Consoleのスキーマ画面でQuery with AIをクリックし、平易な英語で質問してください。これはスキーマの説明を繰り返し改善する最も速い方法です。

エラー処理
よくあるエラー
| エラー | 原因 | 解決策 |
|---|---|---|
UNAUTHORIZED | trueを返す@secureAiQuery(integrationId)ルールがない | インテグレーションに一致し、呼び出し元のユーザーに対してtrueを返すセキュリティルールを追加する |
This integration cannot be used yet | コネクタにスキーマが設定されていない | Squid Consoleでスキーマの説明を設定する |
Integration not found | integrationIdがどのコネクタとも一致しない | Squid ConsoleでコネクタIDを確認する |
| クエリの構文エラー | 生成されたクエリがデータベースの方言では無効 | SquidはmaxErrorCorrections回まで自動的に再試行する。必要に応じて上限を引き上げる |
| 書き込みの拒否 | 生成されたクエリが書き込み(INSERT、UPDATE、DELETE、$out、$merge)を試みた | Query with AIは設計上、読み取り専用。プロンプトを組み直すか、書き込みにはexecutablesを使用する |
| パイプラインは成功したが回答が間違っている | スキーマの説明がない、または誤解を招く | Squid Consoleでコレクションとフィールドの説明を改善する |
実行されたクエリを確認する
回答が間違っているように見える場合は、まずSquidが実際に実行したクエリを確認してください。response.executedQueriesをログに出力し、データベースに対してクエリを直接再実行して、返された結果を確認します。
- TypeScript
- Python
const response = await this.squid.ai().executeAiQuery('postgres', question);
for (const executed of response.executedQueries) {
console.log(`Purpose: ${executed.purpose}`);
console.log(`Query: ${executed.query}`);
console.log(`Success: ${executed.success}`);
}
response = await self.squid.execute_ai_query('postgres', question)
for executed in response.get('executedQueries', []):
print(f"Purpose: {executed.get('purpose')}")
print(f"Query: {executed['query']}")
print(f"Success: {executed.get('success')}")
ベストプラクティス
- スキーマの説明を充実させる。 Query with AIの精度は、ほぼ全面的にコレクションとフィールドの説明の品質に依存します。曖昧な説明からは曖昧なクエリが生成されます。
- 必ず
@secureAiQueryルールを追加する。 ルールがなければ、そのインテグレーションに対するexecuteAiQueryの呼び出しはブロックされます。許可範囲が広すぎるルールを設定すると、誰でもコネクタ内のあらゆるデータを読み取れます。他のアクセス制御と同様に扱ってください。 collectionsToUseでクエリの範囲を限定する。 ユーザーがデータベースの一部についてのみ質問する必要がある場合、使用可能なコレクションを制限すると、クエリが高速化され、実在しない結合が生成される可能性が低くなります。- AIクエリのexecutablesに**レート制限を適用する。** 各呼び出しでモデルのトークンとデータベースのCPUを消費します。
- 読み取りが多いユースケースではプロンプトごとにキャッシュする。 同じプロンプトからは同じクエリが生成されることがよくあります。クライアント側のキャッシュを使用して再実行を回避してください。
- 生成されたクエリが本番データに到達する前に追加のチェックが必要な場合は、
validateWithAiOptionsを有効にする。 - データを自分で描画または出力する必要がある場合(チャート、テーブル、エクスポート)は、
enableRawResultsを有効にする。 結果ファイルのURLはexecutedQueries[].rawResultに含まれます。
関連項目
- データベースコネクタ - Query with AIのデータソースを設定する
- Executables - クライアントから呼び出せるように
executeAiQueryをラップする - セキュリティルール -
@secureAiQueryでAIクエリを保護する - AI agent - Query with AIをツールとして使用する本格的なagentを構築する
- AI functions -
executeAiQuery以上の機能が必要なユースケース向けのカスタムAIツール