AI 関数
AI エージェントを、会話中に呼び出せるカスタムバックエンドロジックで拡張します。
AI 関数を使用する理由
AI エージェントには、質問に答えるだけでなく、注文状況の確認、データベースの更新、特定の分野に固有の計算、外部 API の呼び出しなども求められます。モデルは、それらの操作方法を単独では知りません。
AI 関数がなければ、エージェントはモデルがすでに知っていることしか扱えません。AI 関数を使えば、会話の必要に応じてバックエンドコードを呼び出せます。
- TypeScript
- Python
// Backend: define the function
@aiFunction<{ shipName: string }>(
'Returns the list of pirates on a given ship. Call when the user asks about a ship crew.',
[{ name: 'shipName', description: 'The name of the ship', type: 'string', required: true }],
)
async listPiratesOnShip(params: { shipName: string }): Promise<string> {
// Your custom logic: query a database, call an API, run a calculation, etc.
const { shipName } = params;
const crew = await this.lookupCrew(shipName);
return crew.join(', ');
}
# Backend: define the function
@ai_function(
'Returns the list of pirates on a given ship. Call when the user asks about a ship crew.',
[{'name': 'shipName', 'description': 'The name of the ship', 'type': 'string', 'required': True}],
)
async def list_pirates_on_ship(self, params: dict) -> str:
# Your custom logic: query a database, call an API, run a calculation, etc.
ship_name = params['shipName']
crew = await self.lookup_crew(ship_name)
return ', '.join(crew)
// Frontend: pass the function to the agent and ask a question
const response = await squid
.ai()
.agent('pirate-agent')
.ask('Who is on the Black Pearl?', {
functions: ['listPiratesOnShip'],
});
リクエストごとに関数を渡す代わりに、Agent Studio または setAgentOptionInPath を使用して、関数をエージェントに永続的に追加することもできます。公開エージェントでは、リクエストごとの functions オプションが適用されるのは、アプリの API キーを使用する呼び出し元からの場合のみです。それ以外の呼び出し元には、エージェントに保存された関数が適用されます。公開エージェントのオプションを参照してください。
エージェントは関数の説明を読み、いつ呼び出すかを判断して、その結果を応答に組み込みます。
概要
AI 関数は、@aiFunction でデコレートされた Squid Service のメソッドです。AI エージェントにアタッチすると、エージェントは関数の説明とユーザーのプロンプトに基づいて、会話中にその関数を呼び出せます。
AI 関数を使用する場面
| ユースケース | 推奨事項 |
|---|---|
| エージェントがカスタムのサーバー側ロジックを呼び出す必要がある | AI 関数 |
| エージェントが接続されたデータベースのクエリまたは書き込みを行う必要がある | データベースコネクタを使用するか、カスタムクエリロジックには AI 関数を使用 |
| エージェントが接続されたサービス(CRM、カレンダー、API など)にアクセスする必要がある | 接続された integration を使用 |
| エージェントが MCP 経由で外部ツールに接続する必要がある | MCP を使用 |
| エージェントがアップロードされたドキュメントを検索する必要がある | Knowledge Bases を使用 |
仕組み
SquidServiceを継承するクラスで、メソッドを@aiFunctionでデコレートします- 関数を名前でエージェントにアタッチします(SDK またはコンソールの Agent Studio を使用)
- ユーザーがメッセージを送信すると、エージェントは関数の説明をプロンプトと照らし合わせて評価します
- エージェントが関数を関連すると判断した場合、AI が生成したパラメータ値を使って関数を呼び出します
- 関数はバックエンドで実行され、文字列の結果を返します
- エージェントは結果を応答に組み込みます
クイックスタート
前提条件
- TypeScript
- Python
ステップ 1: AI 関数を作成する
Squid Service に @aiFunction デコレータを付けたメソッドを追加します。
- TypeScript
- Python
import { SquidService, aiFunction } from '@squidcloud/backend';
export class AiService extends SquidService {
@aiFunction<{ city: string }>('Returns the current weather for a given city. Call when the user asks about weather.', [{ name: 'city', description: 'The city name', type: 'string', required: true }])
async getWeather(params: { city: string }): Promise<string> {
const { city } = params;
// Replace with your actual weather API call
return `The weather in ${city} is 72°F and sunny.`;
}
}
from squidcloud_backend import SquidService, ai_function
class AiService(SquidService):
@ai_function(
'Returns the current weather for a given city. Call when the user asks about weather.',
[{'name': 'city', 'description': 'The city name', 'type': 'string', 'required': True}],
)
async def get_weather(self, params: dict) -> str:
city = params['city']
# Replace with your actual weather API call
return f'The weather in {city} is 72°F and sunny.'
ステップ 2: バックエンドをデプロイする
ローカル開発では、次を実行します。
squid start
クラウドへのデプロイについては、バックエンドのデプロイを参照してください。
デプロイ後、関数はコンソールの Agent Studio の Abilities に表示されます。
ステップ 3: 関数を指定してエージェントを呼び出す
const response = await squid
.ai()
.agent('my-agent')
.ask("What's the weather in Tokyo?", {
functions: ['getWeather'],
});
console.log(response);
エージェントはユーザーが天気について尋ねたことを認識し、{ city: "Tokyo" } を指定して getWeather を呼び出し、結果を応答に含めます。
setAgentOptionInPath を使用して関数をエージェントに永続的に追加することもできます。これにより、リクエストごとに関数を渡す必要がなくなります。
await squid.ai().agent('my-agent').setAgentOptionInPath('functions', ['getWeather']);
// Now the agent always has access to getWeather
const response = await squid.ai().agent('my-agent').ask("What's the weather in Tokyo?");
基本概念
@aiFunction デコレータ
このデコレータは、必須の引数を 2 つ受け取ります。
description(文字列): この関数をいつ呼び出すかをエージェントに伝えます。曖昧なラベルではなく、明確な指示として記述してください。params(配列): 関数の呼び出し時にエージェントが指定するパラメータを定義します。
- TypeScript
- Python
@aiFunction<{ productId: string; quantity: number }>(
'Updates the stock quantity for a product. Call when the user wants to adjust inventory.',
[
{ name: 'productId', description: 'The product ID', type: 'string', required: true },
{ name: 'quantity', description: 'Amount to add (negative to subtract)', type: 'number', required: true },
],
)
async updateStock(params: { productId: string; quantity: number }): Promise<string> {
// ...
}
@ai_function(
'Updates the stock quantity for a product. Call when the user wants to adjust inventory.',
[
{'name': 'productId', 'description': 'The product ID', 'type': 'string', 'required': True},
{'name': 'quantity', 'description': 'Amount to add (negative to subtract)', 'type': 'number', 'required': True},
],
)
async def update_stock(self, params: dict) -> str:
...
または、単一のオプションオブジェクトをデコレータに渡すこともできます。
- TypeScript
- Python
@aiFunction({
description: 'Updates the stock quantity for a product.',
params: [
{ name: 'productId', description: 'The product ID', type: 'string', required: true },
{ name: 'quantity', description: 'Amount to add (negative to subtract)', type: 'number', required: true },
],
})
async updateStock(params: { productId: string; quantity: number }): Promise<string> {
// ...
}
@ai_function({
'description': 'Updates the stock quantity for a product.',
'params': [
{'name': 'productId', 'description': 'The product ID', 'type': 'string', 'required': True},
{'name': 'quantity', 'description': 'Amount to add (negative to subtract)', 'type': 'number', 'required': True},
],
})
async def update_stock(self, params: dict) -> str:
...
パラメータの定義
params 配列内の各パラメータは、次のフィールドをサポートします。
| フィールド | 型 | 必須 | 説明 |
|---|---|---|---|
name | string | はい | 関数の params オブジェクト内のキーに対応するパラメータ名 |
description | string | はい | エージェントに指定すべき値を伝える説明 |
type | string | はい | データ型: 'string'、'number'、'boolean'、'object'、'files' など |
required | boolean | はい | エージェントがこの値を指定する必要があるかどうか |
enum | any[] | いいえ | 値を許可された選択肢の集合に制限 |
schema | object | いいえ | type: 'object' パラメータの JSON Schema。オブジェクトパラメータを参照 |
affinity | string | いいえ | 'pod' または 'worker'。このパラメータを関数の affinity キーとして指定し、ルーティングの固定先を定めます。このパラメータの値が一致する呼び出しは、同じ pod または同じ worker に送られます。affinity による固定ルーティングを参照 |
特定の選択肢のみが有効な場合は、enum を使用して値を制限します。
- TypeScript
- Python
@aiFunction('Saves a section in a document', [
{
name: 'sectionId',
type: 'string',
description: 'Which section to update in the document',
required: true,
enum: ['introduction', 'background', 'methodology', 'results', 'conclusion'],
},
{
name: 'content',
type: 'string',
description: 'The content of the section',
required: true,
},
])
async saveSection(params: { sectionId: string; content: string }): Promise<string> {
const { sectionId, content } = params;
// Persist the section using your own data layer.
await this.writeSection('my-doc', sectionId, content);
return 'Section saved: ' + sectionId;
}
@ai_function('Saves a section in a document', [
{
'name': 'sectionId',
'type': 'string',
'description': 'Which section to update in the document',
'required': True,
'enum': ['introduction', 'background', 'methodology', 'results', 'conclusion'],
},
{
'name': 'content',
'type': 'string',
'description': 'The content of the section',
'required': True,
},
])
async def save_section(self, params: dict) -> str:
section_id = params['sectionId']
content = params['content']
# Persist the section using your own data layer.
await self.write_section('my-doc', section_id, content)
return f'Section saved: {section_id}'
オブジェクトパラメータ
type: 'object' のパラメータは、schema に指定された JSON Schema(draft 2020-12)で記述される構造化された値を受け取ります。スキーマのルートは { "type": "object" } でなければならず、additionalProperties はデフォルトで閉じられます。モデルが行うすべての呼び出しは、関数の実行前にこのスキーマに照らして検証されます。スキーマは object パラメータには必須で、それ以外の型では受け付けられません。また、無効なスキーマはバックエンドのビルドを失敗させます。
@aiFunction('Creates a calendar event. Call it when the user schedules something.', [
{
name: 'event',
description: 'The event to create',
type: 'object',
required: true,
schema: {
type: 'object',
properties: {
title: { type: 'string' },
startsAt: { type: 'string', description: 'ISO 8601 start time' },
attendees: { type: 'array', items: { type: 'string' } },
},
required: ['title', 'startsAt'],
},
},
])
async createEvent(params: { event: { title: string; startsAt: string; attendees?: string[] } }): Promise<string> {
return `Created: ${params.event.title}`;
}
Python では、'schema' は dict または Pydantic モデルクラスを受け取ります。
ファイルパラメータとファイルの結果
type: 'files' のパラメータは、会話に添付されたファイルを AiFileUrl オブジェクトの配列として受け取ります。各オブジェクトにはダウンロード URL が含まれます。ファイルを返すには、AiFunctionResponseWithFiles で関数を resolve します。これは、AiFileUrl エントリを含む files 配列がテキスト応答とともにエージェントに返されるオブジェクトです。
affinity による固定ルーティング
ほとんどの AI 関数はステートレスなので、どの worker でも任意の呼び出しを処理できます。関数がウォームキャッシュ、ライブセッション、自身が起動した子プロセスなど、リクエストの外部に状態を保持する場合は、その状態を識別するパラメータに affinity を指定します。すると、同じ値を持つすべての呼び出しは、対象が存続している間、同じ場所にルーティングされます。
'pod': 同じ pod の任意の worker が、ディスク上のファイルや子プロセスなどの状態にアクセスできます。'worker': 状態が 1 つの worker のメモリ内に存在するため、その worker 自体が再利用されます。
affinity と以下のライブ状態フックは TypeScript バックエンド SDK 向けに文書化されているため、このセクションの例には Python タブがありません。
import { SquidService, aiFunction } from '@squidcloud/backend';
/** A long-lived interpreter, for example a child process running Python. */
interface Interpreter {
run(code: string): Promise<string>;
dispose(): Promise<void>;
}
export class InterpreterService extends SquidService {
private readonly sessions = new Map<string, Interpreter>();
@aiFunction<{ sessionName: string; code: string }>('Runs a Python snippet in a named, reusable interpreter session', [
{
name: 'sessionName',
type: 'string',
description: 'The interpreter session to run in. Reuse a name to keep variables between calls.',
required: true,
affinity: 'worker',
},
{
name: 'code',
type: 'string',
description: 'The Python code to execute',
required: true,
},
])
async runInSession(params: { sessionName: string; code: string }): Promise<string> {
const { sessionName, code } = params;
// affinity routes every call with this sessionName back to this worker, so the
// interpreter held in `sessions` is the same one each time.
let interpreter = this.sessions.get(sessionName);
if (!interpreter) {
// The worker may have been replaced since the last call, so rebuild rather than assume.
interpreter = await this.startInterpreter();
this.sessions.set(sessionName, interpreter);
}
return await interpreter.run(code);
}
// Replace with your actual interpreter setup.
private async startInterpreter(): Promise<Interpreter> {
throw new Error('Not implemented');
}
// Keeps the worker alive while a session is open. Called often by the runtime,
// so keep it cheap and synchronous. See "Keeping a worker alive" below.
override hasLiveState(): boolean {
return this.sessions.size > 0;
}
// Called when the worker is being terminated. Child processes outlive the thread that spawned them.
override async releaseLiveState(): Promise<void> {
await Promise.all([...this.sessions.values()].map((session) => session.dispose()));
this.sessions.clear();
}
}
affinity を宣言できるのは、関数の string パラメータのうち 1 つだけです。それ以外の型のパラメータに宣言すると、バンドルのビルドが失敗します。値が undefined、null、または '' の場合は affinity が適用されず、呼び出しは通常どおりにルーティングされます。空の値は意図的にキーとして扱われないため、パラメータを空にした呼び出し元は、同じく空にしたすべての呼び出し元とインスタンスを共有するのではなく、独自のインスタンスを取得します。
この値の名前空間は、アプリケーション、関数のサービス、呼び出し元のジョブの範囲に限定されます。ジョブがない呼び出し元では、代わりに会話が使用されます。同じ値を選択した 2 つのエージェントリクエストも個別にルーティングされるため、値は 1 つのリクエスト内の呼び出しにおいてのみ一意であれば十分です。2 つの呼び出し元が値を合わせても、意図的に 1 つのインスタンスを共有することはできません。真に共有される状態が必要な関数には、代わりに共有ストレージが必要です。名前空間は個々の関数ではなくサービス単位なので、同じサービスの関連関数は互いの状態にアクセスできます。
affinity が保証するのはルーティングであり、永続性ではありません。pod または worker がなくなると、その保持していたものもなくなり、次の呼び出しは新しいものに送られます。状態が存続すると想定せず、関数内でこれを検出して再構築してください。
worker を存続させる
アイドル状態の worker は通常、数分後に破棄されます。ステートレスなサービスでは影響が見えませんが、ライブセッションや子プロセスを保持するサービスでは、それらが失われます。サービスで hasLiveState() をオーバーライドしてそのような状態が存在する間は報告し、releaseLiveState() をオーバーライドしてランタイムが worker を終了する際に状態を解放します。これにより、上記の InterpreterService のセッションが存続します。hasLiveState() はマップがインタープリタを保持している間その状態を報告し、releaseLiveState() は worker が最終的に再生成されるときにインタープリタを破棄します。
true を無期限に返すと、pod が存続する間ずっと worker が固定されるため、代わりに状態自体の存続期間を追跡してください。
戻り値
AI 関数は Promise<string>(TypeScript)または str(Python)を返す必要があります。エージェントはこの文字列を受け取り、応答の作成に使用します。明確で簡潔な結果を返してください。
- TypeScript
- Python
// Good: returns useful information the agent can relay
return 'Order #1234 shipped on March 5. Tracking number: ABC123';
// Bad: returns raw JSON the agent has to interpret
return JSON.stringify(orderObject);
# Good: returns useful information the agent can relay
return 'Order #1234 shipped on March 5. Tracking number: ABC123'
# Bad: returns raw JSON the agent has to interpret
return json.dumps(order_object)
属性
属性を使用すると、AI 関数を特定のコネクタタイプに関連付け、そのコネクタの組み込み機能を独自のカスタムロジックで拡張できます。そのタイプのコネクタをエージェントに追加すると、関数がコネクタのデフォルトの動作とともに自動的に含まれます。
例えば、データベースコネクタでは、エージェントが AI を使ってデータをクエリできます。ただし、エージェントに特定の方法で一貫してクエリさせたい場合は、そのコネクタタイプに関連付けられた AI 関数を作成できます。
- TypeScript
- Python
@aiFunction({
description: 'Retrieves recent orders for a customer from the PostgreSQL database',
params: [
{
name: 'customerEmail',
description: 'The email address of the customer',
type: 'string',
required: true,
},
],
attributes: {
integrationType: ['postgres'],
},
})
async getCustomerOrders(
{ customerEmail }: { customerEmail: string },
{ integrationId }: AiFunctionCallContextWithIntegration,
): Promise<string> {
// Custom query logic.
//
// Squid provides "Query with AI" where the agent can write the query and execute it to
// accomplish a task, but if you want it to consistently query in a certain way, you can write
// an AI Function that you can instruct it to call instead.
}
@ai_function({
'description': 'Retrieves recent orders for a customer from the PostgreSQL database',
'params': [
{
'name': 'customerEmail',
'description': 'The email address of the customer',
'type': 'string',
'required': True,
},
],
'attributes': {
'integrationType': ['postgres'],
},
})
async def get_customer_orders(self, params: dict, ctx: dict) -> str:
customer_email = params['customerEmail']
integration_id = ctx['integrationId']
# Custom query logic.
#
# Squid provides "Query with AI" where the agent can write the query and execute it
# to accomplish a task, but if you want it to consistently query in a certain way,
# write an AI function that you can instruct it to call instead.
...
PostgreSQL コネクタをエージェントに追加すると、この関数が自動的に含まれます。
コネクタタイプに関連付けられた関数は、Agent Studio の AI Functions リストには表示されません。エージェントへの追加はコネクタによって処理されます。
カテゴリ
カテゴリを使用すると、Agent Studio で AI 関数をグループ化し、整理しやすくできます。
- TypeScript
- Python
@aiFunction({
description: 'Get all new user reviews from the product listing on Amazon.',
params: [
{
name: 'productId',
description: 'The ID of the listing on Amazon, e.g. "B094D3JGLT" for the URL "https://www.amazon.com/dp/B094D3JGLT"',
type: 'string',
required: true,
},
{
name: 'cutoffDate',
description: 'The cutoff date. Only reviews newer than this date should be returned. Use ISO8601 format. Defaults to returning all reviews.',
type: 'string',
required: false,
},
],
categories: ['Data Gathering'],
})
async getProductReviews(
{ productId, cutoffDate }: { productId: string; cutoffDate?: string },
{ integrationId }: AiFunctionCallContextWithIntegration,
): Promise<string> {
// Your logic to gather the user reviews.
}
@ai_function({
'description': 'Get all new user reviews from the product listing on Amazon.',
'params': [
{
'name': 'productId',
'description': 'The ID of the listing on Amazon, e.g. "B094D3JGLT" for the URL "https://www.amazon.com/dp/B094D3JGLT"',
'type': 'string',
'required': True,
},
{
'name': 'cutoffDate',
'description': 'The cutoff date. Only reviews newer than this date should be returned. Use ISO8601 format. Defaults to returning all reviews.',
'type': 'string',
'required': False,
},
],
'categories': ['Data Gathering'],
})
async def get_product_reviews(self, params: dict, ctx: dict) -> str:
product_id = params['productId']
cutoff_date = params.get('cutoffDate')
integration_id = ctx['integrationId']
# Your logic to gather the user reviews.
...
これにより、getProductReviews は AI Functions リストの「Data Gathering」カテゴリに表示されます。複数のカテゴリを指定でき、その場合は各カテゴリに関数が表示されます。
パラメータ値のオーバーライド
エージェントによっては、AI に判断させるのではなく、特定のパラメータ値を固定したい場合があります。predefinedParameters を使用してパラメータをオーバーライドできます。AI はオーバーライドされたパラメータの存在を認識せず、その値を設定することもできません。
例えば、先ほどの saveSection 関数を使用して、introduction セクションのみを更新するエージェントを作成できます。
チャットウィジェットを使用する場合:
<squid-chat-widget
...
squid-ai-agent-chat-options={{
functions: [{
name: 'saveSection',
predefinedParameters: { sectionId: 'introduction' }
}]
}}
...
>
</squid-chat-widget>
SDK を使用する場合:
const result = await squid
.ai()
.agent('my-agent')
.ask('Save that content.', {
functions: [
{
name: 'saveSection',
predefinedParameters: { sectionId: 'introduction' },
},
],
});
エージェントが指定できるのは content パラメータのみです。sectionId は常に 'introduction' です。
AI 関数へのコンテキストの受け渡し
AI が生成する params に加えて、コンテキストオブジェクトを使用して独自の値を AI 関数に渡すことができます。これは、ドキュメント ID、ユーザー設定、セキュリティ関連の値など、AI に制御させるべきでないデータに役立ちます。
コンテキストには 2 つのスコープがあります。
agentContext: エージェントが行うすべての AI 関数呼び出しに渡されます。ctx.agentContextからアクセスします。functionContext: 特定の関数にのみ渡されます。ctx.functionContextからアクセスします。
リクエストの agentContext は、エージェントの接続されたエージェントの AI 関数にも渡されます。各接続エージェントに保存された agentContext とマージされ、キーが重複する場合はリクエストの値が優先されます。リクエストに対して実行されるのはルートエージェントの @secureAiAgent ルールのみなので、そこで agentContext のキーを検証してください。接続エージェント自身のルールはこれらのキーを確認しません。公開エージェントでは、agentContext を設定できるのはアプリの API キーを使用したリクエストのみです。
例
saveSection 関数を基に、ドキュメント ID をエージェントレベルで設定し、保存前にコンテンツから内部コードネームを伏せる場合を考えます。
- TypeScript
- Python
import { SquidService, aiFunction, AiFunctionCallContext } from '@squidcloud/backend';
const SECTION_IDS = ['introduction', 'background', 'methodology', 'results', 'conclusion'] as const;
type SectionId = (typeof SECTION_IDS)[number];
interface DocumentIdAgentContext {
documentId: string;
}
interface RedactionFunctionContext {
codenameList: string[];
}
class DocumentService extends SquidService {
@aiFunction('Saves a section in a document', [
{
name: 'sectionId',
type: 'string',
description: 'Which section to update in the document',
required: true,
enum: [...SECTION_IDS],
},
{
name: 'content',
type: 'string',
description: 'The content of the section',
required: true,
},
])
async saveSection({ sectionId, content }: { sectionId: SectionId; content: string }, ctx: AiFunctionCallContext<RedactionFunctionContext, DocumentIdAgentContext>): Promise<string> {
let censoredContent = content;
for (const censorWord of ctx.functionContext.codenameList) {
censoredContent = censoredContent.replaceAll(censorWord, 'REDACTED');
}
// Persist the censored section using your own data layer.
await this.writeSection(ctx.agentContext.documentId, sectionId, censoredContent);
return 'Section saved: ' + sectionId;
}
}
from squidcloud_backend import SquidService, ai_function
SECTION_IDS = ['introduction', 'background', 'methodology', 'results', 'conclusion']
class DocumentService(SquidService):
@ai_function('Saves a section in a document', [
{
'name': 'sectionId',
'type': 'string',
'description': 'Which section to update in the document',
'required': True,
'enum': SECTION_IDS,
},
{
'name': 'content',
'type': 'string',
'description': 'The content of the section',
'required': True,
},
])
async def save_section(self, params: dict, ctx: dict) -> str:
section_id = params['sectionId']
content = params['content']
document_id = ctx['agentContext']['documentId']
codename_list = ctx['functionContext']['codenameList']
censored_content = content
for censor_word in codename_list:
censored_content = censored_content.replace(censor_word, 'REDACTED')
# Persist the censored section using your own data layer.
await self.write_section(document_id, section_id, censored_content)
return f'Section saved: {section_id}'
チャットウィジェットを使用して、クライアントからこれらのコンテキスト値を渡します。
<squid-chat-widget
...
squid-ai-agent-chat-options={{
agentContext: { documentId: "document_controlled_by_this_agent" },
functions: [{
name: 'saveSection',
context: { codenameList: ['LITANIA', 'LEOPARD'] }
}]
}}
...
>
</squid-chat-widget>
または SDK を使用します。
const result = await squid
.ai()
.agent('my-agent')
.ask('I want the "results" section to be "LITANIA has determined the answer to be 42".', {
agentContext: { documentId: 'document_controlled_by_this_agent' },
functions: [
{
name: 'saveSection',
context: { codenameList: ['LITANIA', 'LEOPARD'] },
},
],
});
この場合、「LITANIA」はコードネームリストに含まれているため、保存されるコンテンツは「REDACTED has determined the answer to be 42」になります。
エラー処理
AI 関数がエラーをスローすると、エージェントはエラーメッセージを受け取り、それをユーザーに伝えるか、続行方法を判断できます。明確でわかりやすいエラーをスローしてください。
- TypeScript
- Python
@aiFunction<{ orderId: string }>(
'Looks up the status of an order.',
[{ name: 'orderId', description: 'The order ID', type: 'string', required: true }],
)
async getOrderStatus(params: { orderId: string }): Promise<string> {
const { orderId } = params;
const order = await this.squid.collection('orders').doc(orderId).snapshot();
if (!order) {
throw new Error(`Order ${orderId} not found`);
}
return `Order ${orderId}: ${order.status}, shipped ${order.shippedDate}`;
}
@ai_function(
'Looks up the status of an order.',
[{'name': 'orderId', 'description': 'The order ID', 'type': 'string', 'required': True}],
)
async def get_order_status(self, params: dict) -> str:
order_id = params['orderId']
order = await self.lookup_order(order_id)
if order is None:
raise RuntimeError(f'Order {order_id} not found')
return f"Order {order_id}: {order['status']}, shipped {order['shippedDate']}"
よくある問題
| 問題 | 原因 | 解決策 |
|---|---|---|
| 関数が呼び出されない | 説明がユーザーのプロンプトと一致しない | 関数をいつ呼び出すかを明確に示すよう説明を書き直す |
| パラメータ値が正しくない | パラメータの説明が曖昧 | 具体的な説明を追加し、enum で値を制限する |
| エージェントが関数を見つけられない | 関数名が functions オプションに渡されていない | ask の呼び出しで関数名を渡すか、Agent Studio で追加する |
| 関数が Agent Studio に表示されない | 関数がクラウドにデプロイされていない | squid deploy でバックエンドをデプロイする |
ベストプラクティス
明確な説明を書く
description は、エージェントが関数を正しく呼び出すかどうかを左右する最も重要な要素です。いつ使用するかをエージェントに正確に伝える指示として記述してください。
Good: 'Returns the shipping status and tracking number for an order. Call when the user asks about order status, delivery, or tracking.'
Bad: 'Gets order info'
パラメータを慎重に設計する
required: trueは、関数の動作に不可欠な値にのみ使用する- 有効な値の集合がわかっている場合は
enumを設定する - 使用する形式をエージェントに伝えるパラメータの説明を書く(例: 「ISO8601 date」、「email address」)
情報量のある戻り値にする
エージェントは戻り値の文字列を使用して応答を作成します。生のデータ構造ではなく、人間が読める情報を返してください。
入力を検証する
パラメータ値は AI が生成しますが、関数内で検証してください。AI は予期しない値を生成することがあります。
- TypeScript
- Python
async updateQuantity(params: { quantity: number }): Promise<string> {
const { quantity } = params;
if (!Number.isFinite(quantity) || quantity < 0) {
throw new Error('Quantity must be a non-negative number');
}
// ...
return 'Quantity updated';
}
async def update_quantity(self, params: dict) -> str:
quantity = params['quantity']
if not isinstance(quantity, (int, float)) or quantity < 0:
raise ValueError('Quantity must be a non-negative number')
# ...
return 'Quantity updated'
次のステップ
- エージェントの設定と関数のアタッチについては、AI エージェントのドキュメントを参照
- エージェントを外部ツールサーバーに接続するには、MCP を参照
- AI 関数を使用した完全な例については、AI 住宅メンテナンスチュートリアルを参照