微算力 · API 导航与自营网关
API 接入 EN
未登录登录
🟨

150+ 模型一键调用,类型安全的 AI 开发套件

Javascript Sdk · v0.1.5
这个包缺安装入口,装上也不会生效 缺 SKILL.md 或 frontmatter 不完整(NO_FRONTMATTER)。我们仍保留下载,方便你自行查看内容。
开发 安全 B 级 作者 okaris 公开目录收录
2.3k 下载 0 安装 7.5k 收藏 18 浏览

简介

inference.sh 官方 JavaScript/TypeScript SDK,支持 150+ AI 模型调用、Agent 构建与工具编排,提供完整类型定义与多框架代理支持。

原始描述

JavaScript/TypeScript SDK for inference.sh - run AI apps, build agents, integrate 150+ models. Package: @inferencesh/sdk (npm install). Full TypeScript suppo...

通过你的 Agent 添加

安装目录:javascript-sdk/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。

点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。

或者手动安装

Claude Code~/.claude/skills/javascript-sdk/
Codex CLI~/.codex/skills/javascript-sdk/
DeepSeek Harness~/.agents/skills/javascript-sdk/

包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可; 目录名不用换,也不要把包直接解压到 skills 根目录。 技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。

中文使用说明 来自收录源

核心用法

inference.sh JavaScript SDK 是官方提供的 TypeScript 优先客户端,通过 npm install @inferencesh/sdk 安装。核心能力包括:

基础推理调用:通过 client.run() 执行任意 AI 应用,支持同步等待、异步任务(fire-and-forget)及流式进度追踪(SSE)。

Agent 开发:提供模板化 Agent(client.agent('ref'))与程序化构建(ad-hoc)两种模式。内置工具编排 API,支持 Client Tools(本地执行)、App Tools(调用 AI 应用)、Agent Tools(子代理委派)、Webhook Tools(外部 API)及 Internal Tools(规划、记忆、搜索、代码执行等内置能力)。

文件与状态管理:自动/手动文件上传、Base64 与浏览器 File 对象支持;Session 机制实现有状态执行与 Worker 保活。

前端集成:通过 Server Proxy 模式(Next.js、Express、Hono、Remix、SvelteKit 等)安全代理请求,避免前端暴露 API Key。

显著优点

  • 类型安全:完整 TypeScript 定义,涵盖 Task、Chat、Tool 等全链路 DTO,开发体验友好。
  • 生态兼容:支持 Node.js 18+ 与现代浏览器,同时提供 CommonJS 与 ESM 双格式。
  • 框架深度集成:官方提供 Next.js App Router/Pages Router、Express 等框架的代理封装,降低接入成本。
  • Agent 能力完备:多工具类型、人审工作流(requireApproval)、Skill 复用上下文、流式响应回调,覆盖复杂交互场景。
  • 多包管理器支持:npm、yarn、pnpm 均可安装。

潜在局限

  • 运行时依赖:要求 Node.js 18+ 或现代浏览器(fetch API),旧环境需 polyfill。
  • 网络模型:纯云端推理,无本地模型支持,离线场景不可用。
  • 计费模式:调用按量计费,高频场景需关注成本;免费额度与定价策略需查阅官方文档。
  • 平台绑定:深度耦合 inference.sh 生态,迁移至其他推理平台需重写工具编排层。

适合人群

  • 前端/全栈开发者:React、Next.js、Node.js 技术栈,需快速集成多模型 AI 能力。
  • AI 应用开发者:构建 Chatbot、自动化 Agent、多步骤工作流,需类型安全与工具链支持。
  • 中小团队:希望避免自建模型服务基建,通过 SDK 直接调用 150+ 托管模型。

常规风险

  • 密钥安全:前端直接使用 API Key 存在泄露风险,必须使用 Server Proxy 模式。
  • 数据隐私:文件上传与推理数据流经 inference.sh 云服务,敏感数据需评估合规性。
  • 流式异常:SSE 连接需处理网络中断与重连,生产环境建议加兜底逻辑。
  • 版本漂移:Agent 与 Tool Builder API 迭代较快,需锁定版本或关注 breaking changes。

技能正文


name: javascript-sdk description: "JavaScript/TypeScript SDK for inference.sh - run AI apps, build agents, integrate with all models. Package: @inferencesh/sdk (npm install). Full TypeScript support, streaming, file uploads. Build agents with template or ad-hoc patterns, tool builder API, skills, human approval. Use for: JavaScript integration, TypeScript, Node.js, React, Next.js, frontend apps. Triggers: 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" allowed-tools: Bash(npm *), Bash(npx *), Bash(node *), Bash(pnpm *), Bash(yarn *)

Install the belt CLI skill: npx skills add belt-sh/cli

JavaScript SDK

Build AI applications with the inference.sh JavaScript/TypeScript SDK.

JavaScript SDK

Quick Start

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: 'pruna/p-image',
  input: { prompt: 'A sunset over mountains' }
});
console.log(result.output);

Installation

npm install @inferencesh/sdk
# or
yarn add @inferencesh/sdk
# or
pnpm add @inferencesh/sdk

Requirements: Node.js 18.0.0+ (or modern browser with fetch)

Authentication

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' });

Get your API key: Settings → API Keys → Create API Key

Running Apps

Basic Execution

const result = await client.run({
  app: 'pruna/p-image',
  input: { prompt: 'A cat astronaut' }
});

console.log(result.status);  // "completed"
console.log(result.output);  // Output data

Fire and Forget

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)

Streaming Progress

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));
  }
}

Run Parameters

Parameter Type Description
app string App ID (namespace/name@version)
input object Input matching app schema
setup object Hidden setup configuration
infra string 'cloud' or 'private'
session string Session ID for stateful execution
session_timeout number Idle timeout (1-3600 seconds)

File Handling

Automatic Upload

const result = await client.run({
  app: 'image-processor',
  input: {
    image: '/path/to/image.png'  // Auto-uploaded
  }
});

Manual Upload

// 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 }
});

Browser File Upload

const input = document.querySelector('input[type="file"]');
const file = await client.uploadFile(input.files[0]);

Sessions (Stateful Execution)

Keep workers warm across multiple calls:

// 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

Template Agents

Use pre-built agents from your workspace:

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();

Ad-hoc Agents

Create custom agents programmatically:

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', 'pruna/p-image@latest')
  .describe('Generate an image')
  .param('prompt', string('Image description'))
  .build();

// Create agent
const agent = client.agent({
  core_app: { ref: 'anthropic/claude-sonnet-5-5@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?');

Available Core Apps

Model App Reference
Claude Sonnet 5.5 anthropic/claude-sonnet-5-5@latest
Claude Haiku 5.5 anthropic/claude-haiku-5-5@latest
GPT-6.1 Sol openai/gpt-6-1-sol@latest
GPT-6 Luna openai/gpt-6-luna@latest

Tool Builder API

Parameter Types

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');

Client Tools (Run in Your Code)

const greet = tool('greet')
  .display('Greet User')
  .describe('Greets a user by name')
  .param('name', string('Name to greet'))
  .requireApproval()
  .build();

App Tools (Call AI Apps)

const generate = appTool('generate_image', 'pruna/flux-dev@latest')
  .describe('Generate an image from text')
  .param('prompt', string('Image description'))
  .input({ num_inference_steps: 20 })
  .requireApproval()
  .build();

Agent Tools (Delegate to Sub-agents)

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 Tools (Call External APIs)

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();

Internal Tools (Built-in Capabilities)

import { internalTools } from '@inferencesh/sdk';

const config = internalTools()
  .plan()
  .memory()
  .webSearch(true)
  .codeExecution(true)
  .imageGeneration({
    enabled: true,
    appRef: 'pruna/flux-dev@latest'
  })
  .build();

const agent = client.agent({
  core_app: { ref: 'anthropic/claude-sonnet-5-5@latest' },
  internal_tools: config
});

Streaming Agent Responses

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);
  }
});

File Attachments

// 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]]
});

Skills (Reusable Context)

const agent = client.agent({
  core_app: { ref: 'anthropic/claude-sonnet-5-5@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'
    }
  ]
});

Server Proxy (Frontend Apps)

For browser apps, proxy through your backend to keep API keys secure:

Client Setup

const client = inference({
  proxyUrl: '/api/inference/proxy'
  // No apiKey needed on frontend
});

Next.js Proxy (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 Proxy

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
}));

Supported Frameworks

  • Next.js (App Router & Pages Router)
  • Express
  • Hono
  • Remix
  • SvelteKit

TypeScript Support

Full type definitions included:

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);
}

Error Handling

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);
  }
}

Human Approval Workflows

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 Support

const { inference, tool, string } = require('@inferencesh/sdk');

const client = inference({ apiKey: 'inf_...' });
const result = await client.run({...});

Reference Files

Related Skills

# 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

Documentation

正文来自原始仓库, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。

原始仓库

作者的项目地址:https://github.com/101-skills/skills

标签

javascripttypescriptsdkai-inferenceagent-frameworknpmnextjsreactnodejsstreaming-apitool-buildermodel-integration

同类 Skill