Loading...
Loading...
用于inference.sh的JavaScript/TypeScript SDK - 运行AI应用、构建Agent、集成150+模型。包名:@inferencesh/sdk(可通过npm install安装)。完整TypeScript支持、流式处理、文件上传功能。可通过模板或自定义模式构建Agent,具备工具构建器API、Skills、人工审批功能。适用场景:JavaScript集成、TypeScript、Node.js、React、Next.js、前端应用。相关关键词:javascript sdk、typescript sdk、npm install、node.js api、js client、react ai、next.js ai、frontend sdk、@inferencesh/sdk、typescript agent、browser sdk、js integration
npx skill4agent add inf-sh/skills javascript-sdk
npm install @inferencesh/sdkimport { 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/sdkimport { 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' });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(`任务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(`状态: ${update.status}`);
if (update.logs?.length) {
console.log(update.logs.at(-1));
}
}| 参数 | 类型 | 描述 |
|---|---|---|
| string | 应用ID(命名空间/名称@版本) |
| object | 匹配应用 schema 的输入数据 |
| object | 隐藏的配置参数 |
| string | 'cloud'(云端)或 'private'(私有部署) |
| string | 用于有状态执行的会话ID |
| 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]);// 启动新会话
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
});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();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 | |
| Claude 3.5 Haiku | |
| GPT-4o | |
| GPT-4o Mini | |
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[工具: ${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...'
},
{
name: 'api-docs',
description: 'API documentation',
url: 'https://example.com/skills/api-docs.md'
}
]
});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('完成!');
} else if (result.status === TaskStatusFailed) {
console.log('失败:', 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('缺少必要条件:');
for (const err of e.errors) {
console.log(` - ${err.type}: ${err.key}`);
}
} else if (e instanceof InferenceError) {
console.log('API错误:', e.message);
}
}const response = await agent.sendMessage('Delete all temp files', {
onToolCall: async (call) => {
if (call.requiresApproval) {
const approved = await promptUser(`是否允许执行${call.name}?`);
if (approved) {
const result = await executeTool(call.name, call.args);
agent.submitToolResult(call.id, result);
} else {
agent.submitToolResult(call.id, { error: '用户已拒绝' });
}
}
}
});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
# 全平台Skill(通过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