mcpField
P
python-sdk

python-sdk

github.com/inference-sh開発7891.1k 回インストール2 週間前に更新
リポジトリ

python-sdk について

inference.sh アプリの実行や、ツール・セッション・ストリーミングを使ったエージェント構築に対応する Python SDK です。アプリ実行やエージェントのワークフローを Python に組み込む開発者向けです。

主な機能

  1. 01アプリの同期・非同期実行
  2. 02タスク追跡と進捗ストリーミング
  3. 03ファイルのアップロードとセッション管理
  4. 04エージェントとツール定義の構築
  5. 05承認ワークフローへの対応

活用シーン

  1. 01Python サービスへの AI アプリ実行の組み込み
  2. 02アプリ呼び出しやタスク委任を行うエージェントの作成
  3. 03アプリ入力によるファイル処理
  4. 04長時間タスクの進捗表示

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/inference-sh/skills --skill python-sdk

インストール後、Claude Code で/python-sdkを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
agent-patterns.md
async-patterns.md
files.md
sessions.md
streaming.md
tool-builder.md

詳細

belt CLI スキルをインストールする: npx skills add belt-sh/cli

Python SDK

inference.sh Python SDK を使って AI アプリケーションを構築します。

Python SDK

クイックスタート

pip install inferencesh
from inferencesh import inference

client = inference(api_key="inf_your_key")

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

インストール

# Standard installation
pip install inferencesh

# With async support
pip install inferencesh[async]

要件: Python 3.8 以降

認証

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"])

API キーを取得するには、「Settings」→「API Keys」→「Create API Key」の順に進みます。

アプリの実行

基本的な実行
result = client.run({
    "app": "infsh/flux-1-dev",
    "input": {"prompt": "A cat astronaut"}
})

print(result["status"])  # "completed"
print(result["output"])  # Output data
実行して結果を待たない
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'])
進行状況のストリーミング
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])
実行パラメーター
パラメーター型説明
appstringアプリ ID(namespace/name@version)
inputdictアプリのスキーマに一致する入力
setupdict非表示のセットアップ設定
infrastring'cloud' または 'private'
sessionstringステートフル実行用のセッション ID
session_timeoutintアイドルタイムアウト(1~3600 秒)

ファイルの処理

自動アップロード
result = client.run({
    "app": "image-processor",
    "input": {
        "image": "/path/to/image.png"  # Auto-uploaded
    }
})
手動アップロード
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"]}
})

セッション(ステートフル実行)

複数回の呼び出しにわたってワーカーをウォーム状態に保ちます:

# 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

テンプレートエージェント

ワークスペースの事前構築済みエージェントを使用します:

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()
アドホックエージェント

プログラムからカスタムエージェントを作成します:

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-1-dev@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?")
利用可能なコアアプリ
モデルアプリ参照
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

Tool Builder API

パラメーターの型
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")
クライアントツール(コード内で実行)
greet = (
    tool("greet")
    .display("Greet User")
    .describe("Greets a user by name")
    .param("name", string("Name to greet"))
    .require_approval()
    .build()
)
アプリツール(AI アプリを呼び出す)
generate = (
    app_tool("generate_image", "infsh/flux-1-dev@latest")
    .describe("Generate an image from text")
    .param("prompt", string("Image description"))
    .setup({"model": "schnell"})
    .input({"steps": 20})
    .require_approval()
    .build()
)
エージェントツール(サブエージェントに委任)
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 ツール(外部 API を呼び出す)
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()
)
内部ツール(組み込み機能)
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"\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
)

ファイル添付

# 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..."]
)

スキル(再利用可能なコンテキスト)

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

非同期サポート

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-1-dev",
        "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())

エラー処理

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

人間による承認ワークフロー

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
)

リファレンスファイル

関連スキル

# JavaScript SDK
npx skills add inference-sh/skills@javascript-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

ドキュメント

コメント