javascript-sdk について
inference.sh JavaScript SDKは、JavaScriptまたはTypeScriptでAIアプリを実行するアプリケーションやエージェントを構築するための開発者向けSDKです。タスクのストリーミング、ファイル処理、ステートフルなセッション、ツールビルダー、フロントエンド用サーバープロキシを備えます。
主な機能
- 01AIアプリの実行とタスク取得
- 02実行状況とエージェント更新のストリーミング
- 03ファイルのアップロードとセッション管理
- 04エージェントと設定可能なツールの構築
- 05対応サーバー経由のリクエストプロキシ
- 06TypeScript型定義とエラー処理
活用シーン
- 01JavaScriptアプリにAIアプリ実行を組み込む
- 02ツールを使うマルチターンエージェントを構築する
- 03アプリやエージェント入力用のファイルをアップロードする
- 04ブラウザのフロントエンドでAPIキーを保護する
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ inference-sh/ skills --skill javascript-sdkインストール後、Claude Code で/javascript-sdkを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/agent-patterns.mdfiles.mdreact-integration.mdserver-proxy.mdsessions.mdstreaming.mdtool-builder.mdtypescript.md詳細
belt CLI スキルをインストール:
npx skills add belt-sh/cli
JavaScript SDK
inference.sh JavaScript/TypeScript SDK を使って AI アプリケーションを構築します。

クイックスタート
npm install @inferencesh/sdk
import { inference } from '@inferencesh/sdk';
const client = inference({ apiKey: 'inf_your_key' });
// Run an AI app
const result = await client.run({
app: 'infsh/flux-schnell',
input: { prompt: 'A sunset over mountains' }
});
console.log(result.output);
インストール
npm install @inferencesh/sdk
# or
yarn add @inferencesh/sdk
# or
pnpm add @inferencesh/sdk
要件: Node.js 18.0.0+(または fetch を備えた最新のブラウザー)
認証
import { inference } from '@inferencesh/sdk';
// Direct API key
const client = inference({ apiKey: 'inf_your_key' });
// From environment variable (recommended)
const client = inference({ apiKey: process.env.INFERENCE_API_KEY });
// For frontend apps (use proxy)
const client = inference({ proxyUrl: '/api/inference/proxy' });
API キーを取得するには、Settings → API Keys → Create API Key に進みます。
アプリの実行
基本的な実行
const result = await client.run({
app: 'infsh/flux-schnell',
input: { prompt: 'A cat astronaut' }
});
console.log(result.status); // "completed"
console.log(result.output); // Output data
非同期実行
const task = await client.run({
app: 'google/veo-3-1-fast',
input: { prompt: 'Drone flying over mountains' }
}, { wait: false });
console.log(`Task ID: ${task.id}`);
// Check later with client.getTask(task.id)
進行状況のストリーミング
const stream = await client.run({
app: 'google/veo-3-1-fast',
input: { prompt: 'Ocean waves at sunset' }
}, { stream: true });
for await (const update of stream) {
console.log(`Status: ${update.status}`);
if (update.logs?.length) {
console.log(update.logs.at(-1));
}
}
実行パラメーター
| パラメーター | 型 | 説明 |
|---|---|---|
app | string | アプリ ID(namespace/name@version) |
input | object | アプリのスキーマに適合する入力 |
setup | object | 非表示のセットアップ設定 |
infra | string | 'cloud' または 'private' |
session | string | ステートフル実行用のセッション ID |
session_timeout | number | アイドルタイムアウト(1~3600 秒) |
ファイルの処理
自動アップロード
const result = await client.run({
app: 'image-processor',
input: {
image: '/path/to/image.png' // Auto-uploaded
}
});
手動アップロード
// Basic upload
const file = await client.uploadFile('/path/to/image.png');
// With options
const file = await client.uploadFile('/path/to/image.png', {
filename: 'custom_name.png',
contentType: 'image/png',
public: true
});
const result = await client.run({
app: 'image-processor',
input: { image: file.uri }
});
ブラウザーからのファイルアップロード
const input = document.querySelector('input[type="file"]');
const file = await client.uploadFile(input.files[0]);
セッション(ステートフル実行)
複数回の呼び出しにわたってワーカーをウォーム状態に保ちます。
// Start new session
const result = await client.run({
app: 'my-app',
input: { action: 'init' },
session: 'new',
session_timeout: 300 // 5 minutes
});
const sessionId = result.session_id;
// Continue in same session
const result2 = await client.run({
app: 'my-app',
input: { action: 'process' },
session: sessionId
});
エージェント SDK
テンプレートエージェント
ワークスペースの事前構築済みエージェントを使用します。
const agent = client.agent('my-team/support-agent@latest');
// Send message
const response = await agent.sendMessage('Hello!');
console.log(response.text);
// Multi-turn conversation
const response2 = await agent.sendMessage('Tell me more');
// Reset conversation
agent.reset();
// Get chat history
const chat = await agent.getChat();
アドホックエージェント
プログラムでカスタムエージェントを作成します。
import { tool, string, number, appTool } from '@inferencesh/sdk';
// Define tools
const calculator = tool('calculate')
.describe('Perform a calculation')
.param('expression', string('Math expression'))
.build();
const imageGen = appTool('generate_image', 'infsh/flux-schnell@latest')
.describe('Generate an image')
.param('prompt', string('Image description'))
.build();
// Create agent
const agent = client.agent({
core_app: { ref: 'infsh/claude-sonnet-4@latest' },
system_prompt: 'You are a helpful assistant.',
tools: [calculator, imageGen],
temperature: 0.7,
max_tokens: 4096
});
const response = await agent.sendMessage('What is 25 * 4?');
利用可能なコアアプリ
| モデル | アプリ参照 |
|---|---|
| Claude Sonnet 4 | infsh/claude-sonnet-4@latest |
| Claude 3.5 Haiku | infsh/claude-haiku-35@latest |
| GPT-4o | infsh/gpt-4o@latest |
| GPT-4o Mini | infsh/gpt-4o-mini@latest |
ツールビルダー API
パラメーターの型
import {
string, number, integer, boolean,
enumOf, array, obj, optional
} from '@inferencesh/sdk';
const name = string('User\'s name');
const age = integer('Age in years');
const score = number('Score 0-1');
const active = boolean('Is active');
const priority = enumOf(['low', 'medium', 'high'], 'Priority');
const tags = array(string('Tag'), 'List of tags');
const address = obj({
street: string('Street'),
city: string('City'),
zip: optional(string('ZIP'))
}, 'Address');
クライアントツール(コード内で実行)
const greet = tool('greet')
.display('Greet User')
.describe('Greets a user by name')
.param('name', string('Name to greet'))
.requireApproval()
.build();
アプリツール(AI アプリを呼び出す)
const generate = appTool('generate_image', 'infsh/flux-schnell@latest')
.describe('Generate an image from text')
.param('prompt', string('Image description'))
.setup({ model: 'schnell' })
.input({ steps: 20 })
.requireApproval()
.build();
エージェントツール(サブエージェントに委任)
import { agentTool } from '@inferencesh/sdk';
const researcher = agentTool('research', 'my-org/researcher@v1')
.describe('Research a topic')
.param('topic', string('Topic to research'))
.build();
Webhook ツール(外部 API を呼び出す)
import { webhookTool } from '@inferencesh/sdk';
const notify = webhookTool('slack', 'https://hooks.slack.com/...')
.describe('Send Slack notification')
.secret('SLACK_SECRET')
.param('channel', string('Channel'))
.param('message', string('Message'))
.build();
内部ツール(組み込み機能)
import { internalTools } from '@inferencesh/sdk';
const config = internalTools()
.plan()
.memory()
.webSearch(true)
.codeExecution(true)
.imageGeneration({
enabled: true,
appRef: 'infsh/flux@latest'
})
.build();
const agent = client.agent({
core_app: { ref: 'infsh/claude-sonnet-4@latest' },
internal_tools: config
});
エージェント応答のストリーミング
const response = await agent.sendMessage('Explain quantum computing', {
onMessage: (msg) => {
if (msg.content) {
process.stdout.write(msg.content);
}
},
onToolCall: async (call) => {
console.log(`\n[Tool: ${call.name}]`);
const result = await executeTool(call.name, call.args);
agent.submitToolResult(call.id, result);
}
});
ファイル添付
// From file path (Node.js)
import { readFileSync } from 'fs';
const response = await agent.sendMessage('What\'s in this image?', {
files: [readFileSync('image.png')]
});
// From base64
const response = await agent.sendMessage('Analyze this', {
files: ['data:image/png;base64,iVBORw0KGgo...']
});
// From browser File object
const input = document.querySelector('input[type="file"]');
const response = await agent.sendMessage('Describe this', {
files: [input.files[0]]
});
スキル(再利用可能なコンテキスト)
const agent = client.agent({
core_app: { ref: 'infsh/claude-sonnet-4@latest' },
skills: [
{
name: 'code-review',
description: 'Code review guidelines',
content: '# Code Review\n\n1. Check security\n2. Check performance...'
},
{
name: 'api-docs',
description: 'API documentation',
url: 'https://example.com/skills/api-docs.md'
}
]
});
サーバープロキシ(フロントエンドアプリ)
ブラウザーアプリでは、API キーを安全に保つため、バックエンド経由でプロキシします。
クライアントのセットアップ
const client = inference({
proxyUrl: '/api/inference/proxy'
// No apiKey needed on frontend
});
Next.js プロキシ(App Router)
// app/api/inference/proxy/route.ts
import { createRouteHandler } from '@inferencesh/sdk/proxy/nextjs';
const route = createRouteHandler({
apiKey: process.env.INFERENCE_API_KEY
});
export const POST = route.POST;
Express プロキシ
import express from 'express';
import { createProxyMiddleware } from '@inferencesh/sdk/proxy/express';
const app = express();
app.use('/api/inference/proxy', createProxyMiddleware({
apiKey: process.env.INFERENCE_API_KEY
}));
対応フレームワーク
- Next.js(App Router と Pages Router)
- Express
- Hono
- Remix
- SvelteKit
TypeScript サポート
型定義がすべて含まれています。
import type {
TaskDTO,
ChatDTO,
ChatMessageDTO,
AgentTool,
TaskStatusCompleted,
TaskStatusFailed
} from '@inferencesh/sdk';
if (result.status === TaskStatusCompleted) {
console.log('Done!');
} else if (result.status === TaskStatusFailed) {
console.log('Failed:', result.error);
}
エラー処理
import { RequirementsNotMetException, InferenceError } from '@inferencesh/sdk';
try {
const result = await client.run({ app: 'my-app', input: {...} });
} catch (e) {
if (e instanceof RequirementsNotMetException) {
console.log('Missing requirements:');
for (const err of e.errors) {
console.log(` - ${err.type}: ${err.key}`);
}
} else if (e instanceof InferenceError) {
console.log('API error:', e.message);
}
}
人間の承認を伴うワークフロー
const response = await agent.sendMessage('Delete all temp files', {
onToolCall: async (call) => {
if (call.requiresApproval) {
const approved = await promptUser(`Allow ${call.name}?`);
if (approved) {
const result = await executeTool(call.name, call.args);
agent.submitToolResult(call.id, result);
} else {
agent.submitToolResult(call.id, { error: 'Denied by user' });
}
}
}
});
CommonJS サポート
const { inference, tool, string } = require('@inferencesh/sdk');
const client = inference({ apiKey: 'inf_...' });
const result = await client.run({...});
参考ファイル
- エージェントのパターン - マルチエージェント、RAG、バッチ処理のパターン
- ツールビルダー - ツールビルダー API の完全なリファレンス
- サーバープロキシ - Next.js、Express、Hono、Remix、SvelteKit のセットアップ
- ストリーミング - リアルタイムの進行状況更新と SSE の処理
- ファイルの処理 - ファイルのアップロード、ダウンロード、管理
- セッション - ウォーム状態のワーカーを使ったステートフル実行
- TypeScript - 型定義と型安全なパターン
- React 連携 - フック、コンポーネント、パターン
関連スキル
# Python SDK
npx skills add inference-sh/skills@python-sdk
# Full platform skill (all apps via CLI)
npx skills add inference-sh/skills@infsh-cli
# LLM models
npx skills add inference-sh/skills@llm-models
# Image generation
npx skills add inference-sh/skills@ai-image-generation
ドキュメント
- JavaScript SDK リファレンス - API ドキュメントの全文
- Agent SDK の概要 - エージェントの構築
- Tool Builder リファレンス - ツールの作成
- サーバープロキシのセットアップ - フロントエンドとの連携
- 認証 - API キーのセットアップ
- ストリーミング - リアルタイム更新
- ファイルのアップロード - ファイルの処理
コメント
Markdown 対応