名称: python-sdk 描述: “inference.sh 的 Python SDK - 运行 AI 应用、构建代理并集成 150 多种模型。包: inferencesh (pip install inferencesh)。支持同步/异步、流式传输、文件上传。使用模板或临时模式构建代理,工具构建器 API、技能和人工批准。用途: Python 集成、AI 应用、代理开发、RAG 管道、自动化。触发词: python sdk, inferencesh, pip install, python api, python client, async inference, python agent, tool builder python, 程序化 ai, python 集成, sdk python” 允许工具: Bash(pip install inferencesh), Bash(python *)
Python SDK
使用 inference.sh Python SDK 构建 AI 应用程序。

快速开始
pip install inferencesh
from inferencesh import inference
client = inference(api_key="inf_your_key")
# 运行一个 AI 应用
result = client.run({
"app": "infsh/flux-schnell",
"input": {"prompt": "夕阳下的山脉"}
})
print(result["output"])
安装
# 标准安装
pip install inferencesh
# 带异步支持
pip install inferencesh[async]
要求: Python 3.8+
认证
import os
from inferencesh import inference
# 直接 API 密钥
client = inference(api_key="inf_your_key")
# 从环境变量(推荐)
client = inference(api_key=os.environ["INFERENCE_API_KEY"])
获取您的 API 密钥: 设置 → API 密钥 → 创建 API 密钥
运行应用
基本执行
result = client.run({
"app": "infsh/flux-schnell",
"input": {"prompt": "一只猫宇航员"}
})
print(result["status"]) # "completed"
print(result["output"]) # 输出数据
异步执行
task = client.run({
"app": "google/veo-3-1-fast",
"input": {"prompt": "无人机飞越山脉"}
}, wait=False)
print(f"任务 ID: {task['id']}")
# 稍后用 client.get_task(task['id']) 检查
流式进度
for update in client.run({
"app": "google/veo-3-1-fast",
"input": {"prompt": "日落时的海浪"}
}, stream=True):
print(f"状态: {update['status']}")
if update.get("logs"):
print(update["logs"][-1])
运行参数
| 参数 | 类型 | 描述 |
|---|---|---|
app |
字符串 | 应用 ID (命名空间/名称@版本) |
input |
字典 | 输入匹配应用模式 |
setup |
字典 | 隐藏设置配置 |
infra |
字符串 | ‘cloud’ 或 ‘private’ |
session |
字符串 | 用于有状态执行的会话 ID |
session_timeout |
整数 | 空闲超时 (1-3600 秒) |
文件处理
自动上传
result = client.run({
"app": "image-processor",
"input": {
"image": "/path/to/image.png" # 自动上传
}
})
手动上传
from inferencesh import UploadFileOptions
# 基本上传
file = client.upload_file("/path/to/image.png")
# 带选项
file = client.upload_file(
"/path/to/image.png",
UploadFileOptions(
filename="custom_name.png",
content_type="image/png",
public=True
)
)
result = client.run({
"app": "image-processor",
"input": {"image": file["uri"]}
})
会话(有状态执行)
在多个调用中保持工作器温暖:
# 开始新会话
result = client.run({
"app": "my-app",
"input": {"action": "init"},
"session": "new",
"session_timeout": 300 # 5 分钟
})
session_id = result["session_id"]
# 在同一会话中继续
result = client.run({
"app": "my-app",
"input": {"action": "process"},
"session": session_id
})
代理 SDK
模板代理
使用工作区中的预构建代理:
agent = client.agent("my-team/support-agent@latest")
# 发送消息
response = agent.send_message("你好!")
print(response.text)
# 多轮对话
response = agent.send_message("告诉我更多")
# 重置对话
agent.reset()
# 获取聊天历史
chat = agent.get_chat()
临时代理
以编程方式创建自定义代理:
from inferencesh import tool, string, number, app_tool
# 定义工具
calculator = (
tool("calculate")
.describe("执行计算")
.param("expression", string("数学表达式"))
.build()
)
image_gen = (
app_tool("generate_image", "infsh/flux-schnell@latest")
.describe("生成图像")
.param("prompt", string("图像描述"))
.build()
)
# 创建代理
agent = client.agent({
"core_app": {"ref": "infsh/claude-sonnet-4@latest"},
"system_prompt": "你是一个有用的助手。",
"tools": [calculator, image_gen],
"temperature": 0.7,
"max_tokens": 4096
})
response = agent.send_message("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
参数类型
from inferencesh import (
string, number, integer, boolean,
enum_of, array, obj, optional
)
name = string("用户姓名")
age = integer("年龄(岁)")
score = number("分数 0-1")
active = boolean("是否激活")
priority = enum_of(["low", "medium", "high"], "优先级")
tags = array(string("标签"), "标签列表")
address = obj({
"street": string("街道"),
"city": string("城市"),
"zip": optional(string("ZIP"))
}, "地址")
客户端工具(在代码中运行)
greet = (
tool("greet")
.display("问候用户")
.describe("按姓名问候用户")
.param("name", string("问候姓名"))
.require_approval()
.build()
)
应用工具(调用 AI 应用)
generate = (
app_tool("generate_image", "infsh/flux-schnell@latest")
.describe("从文本生成图像")
.param("prompt", string("图像描述"))
.setup({"model": "schnell"})
.input({"steps": 20})
.require_approval()
.build()
)
代理工具(委托给子代理)
from inferencesh import agent_tool
researcher = (
agent_tool("research", "my-org/researcher@v1")
.describe("研究一个主题")
.param("topic", string("研究主题"))
.build()
)
Webhook 工具(调用外部 API)
from inferencesh import webhook_tool
notify = (
webhook_tool("slack", "https://hooks.slack.com/...")
.describe("发送 Slack 通知")
.secret("SLACK_SECRET")
.param("channel", string("频道"))
.param("message", string("消息"))
.build()
)
内部工具(内置功能)
from inferencesh import internal_tools
config = (
internal_tools()
.plan()
.memory()
.web_search(True)
.code_execution(True)
.image_generation({
"enabled": True,
"app_ref": "infsh/flux@latest"
})
.build()
)
agent = client.agent({
"core_app": {"ref": "infsh/claude-sonnet-4@latest"},
"internal_tools": config
})
流式代理响应
def handle_message(msg):
if msg.get("content"):
print(msg["content"], end="", flush=True)
def handle_tool(call):
print(f"
[工具: {call.name}]")
result = execute_tool(call.name, call.args)
agent.submit_tool_result(call.id, result)
response = agent.send_message(
"解释量子计算",
on_message=handle_message,
on_tool_call=handle_tool
)
文件附件
# 从文件路径
with open("image.png", "rb") as f:
response = agent.send_message(
"这张图片里有什么?",
files=[f.read()]
)
# 从 base64
response = agent.send_message(
"分析这个",
files=["data:image/png;base64,iVBORw0KGgo..."]
)
技能(可重用上下文)
agent = client.agent({
"core_app": {"ref": "infsh/claude-sonnet-4@latest"},
"skills": [
{
"name": "code-review",
"description": "代码审查指南",
"content": "# 代码审查
1. 检查安全
2. 检查性能..."
},
{
"name": "api-docs",
"description": "API 文档",
"url": "https://example.com/skills/api-docs.md"
}
]
})
异步支持
from inferencesh import async_inference
import asyncio
async def main():
client = async_inference(api_key="inf_...")
# 异步应用执行
result = await client.run({
"app": "infsh/flux-schnell",
"input": {"prompt": "一个星系"}
})
# 异步代理
agent = client.agent("my-org/assistant@latest")
response = await agent.send_message("你好!")
# 异步流式
async for msg in agent.stream_messages():
print(msg)
asyncio.run(main())
错误处理
from inferencesh import RequirementsNotMetException
try:
result = client.run({"app": "my-app", "input": {...}})
except RequirementsNotMetException as e:
print(f"缺少要求:")
for err in e.errors:
print(f" - {err['type']}: {err['key']}")
except RuntimeError as e:
print(f"错误: {e}")
人工批准工作流
def handle_tool(call):
if call.requires_approval:
# 显示给用户,获取确认
approved = prompt_user(f"允许 {call.name}?")
if approved:
result = execute_tool(call.name, call.args)
agent.submit_tool_result(call.id, result)
else:
agent.submit_tool_result(call.id, {"error": "用户拒绝"})
response = agent.send_message(
"删除所有临时文件",
on_tool_call=handle_tool
)
参考文件
- 代理模式 - 多代理、RAG、人工在环模式
- 工具构建器 - 完整的工具构建器 API 参考
- 流式 - 实时进度更新和 SSE 处理
- 文件处理 - 上传、下载和管理文件
- 会话 - 有状态执行与温暖工作器
- 异步模式 - 并行处理和异步/等待
相关技能
# JavaScript SDK
npx skills add inference-sh/skills@javascript-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