Ömer Karışman

Python Sdk

AI 智慧體v0.1.5
作者:Ömer Karışman更新於 2026-05-17共 2 個版本 · 最新版本釋出於 2026-02-18python-sdk@clawhub_okaris/python-sdk
Agent 框架工具呼叫#Sdk#Rag

據 AlphaMoat 統計,截至 2026-09,Python Sdk 累計下載 3,224 次、獲 1 個星標,在全部 5,078 個 AI 技能中排名第 3,530 位,在「AI 智慧體」分類(969 個)中排名第 721 位。

累計安裝
263
累計下載
3224
星標
1
全站排名
#3,530
全站前 70% · 「AI 智慧體」前 75%
平台累計安裝累計下載星標評論
ClawHub ↗762559--
SkillHub ↗26332241—

各平台的計數口徑不同,統計時間不一致。

這個技能是做什麼的

快速開始:pip install inferencesh(非同步支援裝 inferencesh[async]),要求 Python 3.8+;用 inference(api_key=...) 初始化,推薦從環境變數 INFERENCE_API_KEY 讀取。執行應用:client.run 同步執行並返回 status/output;wait=False 即發即棄後用 get_task 查詢;stream=True 流式獲取進度與日誌。Run 引數含 app、input、setup、infra(cloud/private)、session、session_timeout(空閒超時 1-3600 秒)。檔案處理:輸入傳本地路徑自動上傳,或用 upload_file + UploadFileOptions 手動上傳。Sessions 讓 worker 在多次呼叫間保溫(session="new" 開啟,回傳 session_id 續用)。Agent SDK:模板 agent(workspace 預建,支援多輪對話與 reset)與 ad-hoc agent(core_app + system_prompt + tools,核心應用如 infsh/claude-sonnet-4@latest、infsh/gpt-4o@latest)。Tool Builder API 五類工具:client 工具(tool())、app 工具(app_tool())、agent 工具(agent_tool() 委派子 agent)、webhook 工具(webhook_tool() 調外部 API)、internal 工具(plan/memory/web_search/code_execution/image_generation 內建能力),引數型別含 string/number/integer/boolean/enum_of/array/obj/optional,可 require_approval() 人工審批。另支援 Skills 複用上下文、async_inference 非同步、RequirementsNotMetException 錯誤處理與人工審批工作流。

資料釋出於 2026-10-27

可以用來做什麼

  • 在 Python 中同步/非同步/流式執行 inference.sh 上的 AI 應用
  • 用模板或 ad-hoc 模式構建 agent,配自定義工具與人工審批
  • 檔案上傳、有狀態會話、RAG 流水線等整合場景

什麼時候用

  • Python 整合、AI 應用、agent 開發、RAG 流水線、自動化場景使用
  • 觸發詞:python sdk、inferencesh、pip install、python api、async inference、tool builder python 等

示例提示詞

以下是根據技能文件生成的示例,不代表實際執行結果。

用 flux-schnell 生成一張圖並把結果存到本地
幫我寫一個帶人工審批的 agent,工具呼叫前先確認
把這個應用改成非同步流式執行並列印日誌

月度資料趨勢

累計下載3224
1293233033672026-03 · 累計下載 14362026-05 · 累計下載 18832026-06 · 累計下載 20602026-07 · 累計下載 23352026-08 · 累計下載 26102026-09 · 累計下載 322426-0326-09
星標1
0112026-03 · 星標 -2026-05 · 星標 12026-06 · 星標 12026-07 · 星標 12026-08 · 星標 12026-09 · 星標 126-0326-09

2026-09 起統計方法調整:同名技能按作者分別統計,並覆蓋全部技能。圖中虛線為調整前的月份,與之後的資料不直接比較,也不計算跨越調整的增長。

月份累計下載環比星標
2026-093224—1
2026-082610+11.8%1
2026-072335+13.3%1
2026-062060+9.4%1
2026-051883—1
2026-031436—-

SKILL.md 原文

以下是作者釋出的原始檔案,按純文字顯示,本站未做修改或稽核;其中的連結不可點選,命令請核實後再執行。抓取於 2026-10-23。

11 KB · ClawHub v0.1.5
---
name: python-sdk
description: "Python SDK for inference.sh - run AI apps, build agents, and integrate with 150+ models. Package: inferencesh (pip install inferencesh). Supports sync/async, streaming, file uploads. Build agents with template or ad-hoc patterns, tool builder API, skills, and human approval. Use for: Python integration, AI apps, agent development, RAG pipelines, automation. Triggers: python sdk, inferencesh, pip install, python api, python client, async inference, python agent, tool builder python, programmatic ai, python integration, sdk python"
allowed-tools: Bash(pip install inferencesh), Bash(python *)
---

# Python SDK

Build AI applications with the [inference.sh](https://inference.sh) Python SDK.
展開全部(共 484 行)
![Python SDK](https://cloud.inference.sh/app/files/u/4mg21r6ta37mpaz6ktzwtt8krr/01kgvftjwhby36trvaj66bwzcf.jpeg)

## Quick Start

```bash
pip install inferencesh
```

```python
from inferencesh import inference

client = inference(api_key="inf_your_key")

# Run an AI app
result = client.run({
    "app": "infsh/flux-schnell",
    "input": {"prompt": "A sunset over mountains"}
})
print(result["output"])
```

## Installation

```bash
# Standard installation
pip install inferencesh

# With async support
pip install inferencesh[async]
```

**Requirements:** Python 3.8+

## Authentication

```python
import os
from inferencesh import inference

# Direct API key
client = inference(api_key="inf_your_key")

# From environment variable (recommended)
client = inference(api_key=os.environ["INFERENCE_API_KEY"])
```

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

## Running Apps

### Basic Execution

```python
result = client.run({
    "app": "infsh/flux-schnell",
    "input": {"prompt": "A cat astronaut"}
})

print(result["status"])  # "completed"
print(result["output"])  # Output data
```

### Fire and Forget

```python
task = client.run({
    "app": "google/veo-3-1-fast",
    "input": {"prompt": "Drone flying over mountains"}
}, wait=False)

print(f"Task ID: {task['id']}")
# Check later with client.get_task(task['id'])
```

### Streaming Progress

```python
for update in client.run({
    "app": "google/veo-3-1-fast",
    "input": {"prompt": "Ocean waves at sunset"}
}, stream=True):
    print(f"Status: {update['status']}")
    if update.get("logs"):
        print(update["logs"][-1])
```

### Run Parameters

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

## File Handling

### Automatic Upload

```python
result = client.run({
    "app": "image-processor",
    "input": {
        "image": "/path/to/image.png"  # Auto-uploaded
    }
})
```

### Manual Upload

```python
from inferencesh import UploadFileOptions

# Basic upload
file = client.upload_file("/path/to/image.png")

# With options
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"]}
})
```

## Sessions (Stateful Execution)

Keep workers warm across multiple calls:

```python
# Start new session
result = client.run({
    "app": "my-app",
    "input": {"action": "init"},
    "session": "new",
    "session_timeout": 300  # 5 minutes
})
session_id = result["session_id"]

# Continue in same session
result = client.run({
    "app": "my-app",
    "input": {"action": "process"},
    "session": session_id
})
```

## Agent SDK

### Template Agents

Use pre-built agents from your workspace:

```python
agent = client.agent("my-team/support-agent@latest")

# Send message
response = agent.send_message("Hello!")
print(response.text)

# Multi-turn conversation
response = agent.send_message("Tell me more")

# Reset conversation
agent.reset()

# Get chat history
chat = agent.get_chat()
```

### Ad-hoc Agents

Create custom agents programmatically:

```python
from inferencesh import tool, string, number, app_tool

# Define tools
calculator = (
    tool("calculate")
    .describe("Perform a calculation")
    .param("expression", string("Math expression"))
    .build()
)

image_gen = (
    app_tool("generate_image", "infsh/flux-schnell@latest")
    .describe("Generate an image")
    .param("prompt", string("Image description"))
    .build()
)

# Create agent
agent = client.agent({
    "core_app": {"ref": "infsh/claude-sonnet-4@latest"},
    "system_prompt": "You are a helpful assistant.",
    "tools": [calculator, image_gen],
    "temperature": 0.7,
    "max_tokens": 4096
})

response = agent.send_message("What is 25 * 4?")
```

### Available Core Apps

| Model | App Reference |
|-------|---------------|
| 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` |

## Tool Builder API

### Parameter Types

```python
from inferencesh import (
    string, number, integer, boolean,
    enum_of, array, obj, optional
)

name = string("User's name")
age = integer("Age in years")
score = number("Score 0-1")
active = boolean("Is active")
priority = enum_of(["low", "medium", "high"], "Priority")
tags = array(string("Tag"), "List of tags")
address = obj({
    "street": string("Street"),
    "city": string("City"),
    "zip": optional(string("ZIP"))
}, "Address")
```

### Client Tools (Run in Your Code)

```python
greet = (
    tool("greet")
    .display("Greet User")
    .describe("Greets a user by name")
    .param("name", string("Name to greet"))
    .require_approval()
    .build()
)
```

### App Tools (Call AI Apps)

```python
generate = (
    app_tool("generate_image", "infsh/flux-schnell@latest")
    .describe("Generate an image from text")
    .param("prompt", string("Image description"))
    .setup({"model": "schnell"})
    .input({"steps": 20})
    .require_approval()
    .build()
)
```

### Agent Tools (Delegate to Sub-agents)

```python
from inferencesh import agent_tool

researcher = (
    agent_tool("research", "my-org/researcher@v1")
    .describe("Research a topic")
    .param("topic", string("Topic to research"))
    .build()
)
```

### Webhook Tools (Call External APIs)

```python
from inferencesh import webhook_tool

notify = (
    webhook_tool("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)

```python
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
})
```

## Streaming Agent Responses

```python
def handle_message(msg):
    if msg.get("content"):
        print(msg["content"], end="", flush=True)

def handle_tool(call):
    print(f"\n[Tool: {call.name}]")
    result = execute_tool(call.name, call.args)
    agent.submit_tool_result(call.id, result)

response = agent.send_message(
    "Explain quantum computing",
    on_message=handle_message,
    on_tool_call=handle_tool
)
```

## File Attachments

```python
# From file path
with open("image.png", "rb") as f:
    response = agent.send_message(
        "What's in this image?",
        files=[f.read()]
    )

# From base64
response = agent.send_message(
    "Analyze this",
    files=["data:image/png;base64,iVBORw0KGgo..."]
)
```

## Skills (Reusable Context)

```python
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"
        }
    ]
})
```

## Async Support

```python
from inferencesh import async_inference
import asyncio

async def main():
    client = async_inference(api_key="inf_...")

    # Async app execution
    result = await client.run({
        "app": "infsh/flux-schnell",
        "input": {"prompt": "A galaxy"}
    })

    # Async agent
    agent = client.agent("my-org/assistant@latest")
    response = await agent.send_message("Hello!")

    # Async streaming
    async for msg in agent.stream_messages():
        print(msg)

asyncio.run(main())
```

## Error Handling

```python
from inferencesh import RequirementsNotMetException

try:
    result = client.run({"app": "my-app", "input": {...}})
except RequirementsNotMetException as e:
    print(f"Missing requirements:")
    for err in e.errors:
        print(f"  - {err['type']}: {err['key']}")
except RuntimeError as e:
    print(f"Error: {e}")
```

## Human Approval Workflows

```python
def handle_tool(call):
    if call.requires_approval:
        # Show to user, get confirmation
        approved = prompt_user(f"Allow {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": "Denied by user"})

response = agent.send_message(
    "Delete all temp files",
    on_tool_call=handle_tool
)
```

## Reference Files

- [Agent Patterns](references/agent-patterns.md) - Multi-agent, RAG, human-in-the-loop patterns
- [Tool Builder](references/tool-builder.md) - Complete tool builder API reference
- [Streaming](references/streaming.md) - Real-time progress updates and SSE handling
- [File Handling](references/files.md) - Upload, download, and manage files
- [Sessions](references/sessions.md) - Stateful execution with warm workers
- [Async Patterns](references/async-patterns.md) - Parallel processing and async/await

## Related Skills

```bash
# JavaScript SDK
npx skills add inference-sh/skills@javascript-sdk

# Full platform skill (all 150+ apps via CLI)
npx skills add inference-sh/skills@inference-sh

# LLM models
npx skills add inference-sh/skills@llm-models

# Image generation
npx skills add inference-sh/skills@ai-image-generation
```

## Documentation

- [Python SDK Reference](https://inference.sh/docs/api/sdk-python) - Full API documentation
- [Agent SDK Overview](https://inference.sh/docs/api/agent-sdk) - Building agents
- [Tool Builder Reference](https://inference.sh/docs/api/agent-tools) - Creating tools
- [Authentication](https://inference.sh/docs/api/authentication) - API key setup
- [Streaming](https://inference.sh/docs/api/sdk/streaming) - Real-time updates
- [File Uploads](https://inference.sh/docs/api/sdk/files) - File handling

「AI 智慧體」分類下的熱門技能

Ömer Karışman 的其他技能

資料月份:2026-09 · 下載/星標/安裝數聚合自公開技能註冊庫(ClawHub、SkillHub),按月更新。口徑說明見資料方法。