用于 inference.sh 的 JavaScript/TypeScript SDK,可运行 AI 应用、构建代理、集成 150+ 模型。包名:@inferencesh/sdk(npm install),完整 TypeScript 支持。
JavaScript SDK. 构建AI应用程序, 并使用推论.sh JavaScript/ TypeScript SDK.是一项面向实际任务的技能,主要用于QQ 快速启动. 要求: 节点.js 18.0.0+( 或带有获取的现代浏览器). 6: 认证;获取您的 API 密钥: 设置。
实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;
涉及批量任务时,还应保存进度,避免中断后重复操作。该技能适合用于一次性任务,也可以接入自动化工作流,与其他技能或上层代理配合完成更完整的业务链路;在组合使用时,应明确每一步的输入输出关系,并避免不同步骤之间出现参数冲突。
使用 inference.sh 的 JavaScript/TypeScript SDK 构建 AI 应用程序。

npm install @inferencesh/sdk
import { inference } from '@inferencesh/sdk';
const client = inference({ apiKey: 'inf_your_key' });
// 运行一个 AI 应用
const result = await client.run({
app: 'infsh/flux-schnell',
input: { prompt: 'A sunset over mountains' }
});
console.log(result.output);
npm install @inferencesh/sdk
# 或
yarn add @inferencesh/sdk
# 或
pnpm add @inferencesh/sdk
要求: Node.js 18.0.0+(或支持 fetch 的现代浏览器)
import { inference } from '@inferencesh/sdk';
// 直接传入 API 密钥
const client = inference({ apiKey: 'inf_your_key' });
// 从环境变量读取(推荐)
const client = inference({ apiKey: process.env.INFERENCE_API_KEY });
// 前端应用(需通过代理)
const client = inference({ proxyUrl: '/api/inference/proxy' });
获取您的 API 密钥:设置 → API 密钥 → 创建 API 密钥
const result = await client.run({
app: 'infsh/flux-schnell',
input: { prompt: 'A cat astronaut' }
});
console.log(result.status); // "completed"
console.log(result.output); // 输出数据
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}`);
// 后续可通过 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(命名空间/名称@版本) |
input |
object | 符合应用 Schema 的输入对象 |
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' // 自动上传
}
});
// 基础上传
const file = await client.uploadFile('/path/to/image.png');
// 指定选项上传
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]);
在多次调用间保持 Worker 热启动:
// 启动新会话
const result = await client.run({
app: 'my-app',
input: { action: 'init' },
session: 'new',
session_timeout: 300 // 5 分钟
});
const sessionId = result.session_id;
// 在同一会话中继续执行
const result2 = await client.run({
app: 'my-app',
input: { action: 'process' },
session: sessionId
});
复用您工作区中预构建的 Agent:
const agent = client.agent('my-team/support-agent@latest');
// 发送消息
const response = await agent.sendMessage('Hello!');
console.log(response.text);
// 多轮对话
const response2 = await agent.sendMessage('Tell me more');
// 重置对话
agent.reset();
// 获取聊天历史
const chat = await agent.getChat();
以编程方式创建自定义 Agent:
import { tool, string, number, appTool } from '@inferencesh/sdk';
// 定义工具
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();
// 创建 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 |
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();
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();
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);
}
});
// 从文件路径读取(Node.js)
import { readFileSync } from 'fs';
const response = await agent.sendMessage("What's in this image?", {
files: [readFileSync('image.png')]
});
// 从 Base64 字符串读取
const response = await agent.sendMessage('Analyze this', {
files: ['data:image/png;base64,iVBORw0KGgo...']
});
// 从浏览器 File 对象读取
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...\n'
},
{
name: 'api-docs',
description: 'API documentation',
url: 'https://example.com/skills/api-docs.md'
}
]
});
对于浏览器端应用,请通过后端代理请求,以保障 API 密钥安全:
const client = inference({
proxyUrl: '/api/inference/proxy'
// 前端无需提供 apiKey
});
// 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;
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
}));
包含完整的类型定义:
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' });
}
}
}
});
const { inference, tool, string } = require('@inferencesh/sdk');
const client = inference({ apiKey: 'inf_...' });
const result = await client.run({...});
# Python SDK
npx skills add inference-sh/skills@python-sdk
# 全平台技能(通过 CLI 访问全部 150+ 个应用)
npx skills add inference-sh/skills@inference-sh
# LLM 模型
npx skills add inference-sh/skills@llm-models
# 图像生成
npx skills add inference-sh/skills@ai-image-generation