关于 javascript-sdk
inference.sh JavaScript SDK 供开发者用 JavaScript 或 TypeScript 构建可运行 AI 应用和创建 Agent 的程序。它提供任务流式更新、文件处理、有状态会话、工具构建器,以及供前端应用使用的服务端代理。
主要功能
- 01运行 AI 应用并查询任务
- 02流式接收执行和 Agent 更新
- 03上传文件并管理会话
- 04构建 Agent 和可配置工具
- 05通过支持的服务端代理请求
- 06TypeScript 类型与错误处理
适用场景
- 01在 JavaScript 应用中接入 AI 应用执行
- 02构建带工具的多轮 Agent
- 03上传文件作为应用或 Agent 输入
- 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 | App 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
});
Agent SDK
模板 Agent
使用工作区中的预构建 Agent:
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();
临时 Agent
以编程方式创建自定义 Agent:
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();
Agent 工具(委派给子 Agent)
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
});
流式传输 Agent 响应
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({...});
参考文件
- Agent 模式 - 多 Agent、RAG、批处理模式
- 工具构建器 - 完整的工具构建器 API 参考
- 服务代理 - Next.js、Express、Hono、Remix、SvelteKit 设置
- 流式传输 - 实时进度更新和 SSE 处理
- 文件处理 - 上传、下载和管理文件
- 会话 - 使用预热工作进程进行有状态执行
- TypeScript - 类型定义和类型安全模式
- React 集成 - Hook、组件和模式
相关技能
# 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 概览 - 构建 Agent
- 工具构建器参考 - 创建工具
- 服务代理设置 - 前端集成
- 身份验证 - API 密钥设置
- 流式传输 - 实时更新
- 文件上传 - 文件处理
评论
支持 Markdown