mcpField
J
javascript-sdk

javascript-sdk

github.com/qu-skills开发441 次安装12 周前更新
代码仓库

关于 javascript-sdk

这是用于通过 inference.sh 构建应用和 Agent 的 JavaScript/TypeScript SDK。它提供运行应用、处理文件与会话、定义工具、流式响应及连接 Agent 的 API。

主要功能

  1. 01同步或异步运行 AI 应用
  2. 02流式接收任务进度和 Agent 响应
  3. 03上传文件并管理有状态会话
  4. 04构建客户端、应用、Agent 和 Webhook 工具
  5. 05连接 Agent 并附加可复用技能
  6. 06通过支持的 Web 框架代理请求

适用场景

  1. 01在 JavaScript 产品中加入 inference.sh 应用执行
  2. 02使用自定义工具构建多轮 Agent
  3. 03在浏览器或 Node.js 应用中处理上传文件
  4. 04通过后端代理保护 API 密钥

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/qu-skills/superpowers --skill javascript-sdk

安装后在 Claude Code 中输入/javascript-sdk确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
agent-patterns.md
files.md
react-integration.md
server-proxy.md
sessions.md
streaming.md
tool-builder.md
typescript.md

详细介绍

安装 belt CLI 技能: npx skills add belt-sh/cli

JavaScript SDK

使用 inference.sh JavaScript/TypeScript SDK 构建 AI 应用。

JavaScript SDK

快速入门

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));
  }
}
运行参数
参数类型描述
appstringApp ID(namespace/name@version)
inputobject与应用架构匹配的输入
setupobject隐藏的设置配置
infrastring'cloud' 或 'private'
sessionstring有状态执行的会话 ID
session_timeoutnumber空闲超时(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 4infsh/claude-sonnet-4@latest
Claude 3.5 Haikuinfsh/claude-haiku-35@latest
GPT-4oinfsh/gpt-4o@latest
GPT-4o Miniinfsh/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({...});

参考文件

相关技能

# 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

文档

评论

支持 Markdown