> ## Documentation Index
> Fetch the complete documentation index at: https://novita.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 高度な機能

このドキュメントでは、Novita Agent Runtime の高度な機能とベストプラクティスについて説明します。

***

## 目次

* [設定ファイルリファレンス](#configuration-file-reference)
* [環境変数の管理](#environment-variables-management)
* [ストリーミングレスポンス](#streaming-responses)
* [バージョン管理](#version-management)
* [ヘルスチェック](#health-checks)
* [マルチターン会話](#multi-turn-conversations)
* [サンプルプロジェクト](#example-projects)

***

## 設定ファイルリファレンス

### .novita-agent.yaml の構造

`.novita-agent.yaml` 設定ファイルは、Kubernetes スタイルの YAML 形式を使用します。

```yaml theme={"system"}
apiVersion: v1
kind: Agent
metadata:
  name: my-agent              # Agent name (must consist of lowercase letters, numbers, and hyphens only)
  version: 1.0.0              # Agent version (semantic versioning)
  author: dev@example.com     # Author email (required)
  description: My AI Agent    # Agent description (optional)
  created: '2025-10-23T10:30:00Z'  # Creation time (auto-generated)

spec:
  entrypoint: app.py          # Python entry file (must be .py file)
  
  # Environment variables configuration (optional)
  envVars:
    MODEL_NAME: deepseek/deepseek-v3-0324
    TEMPERATURE: '0.7'
  
  # Runtime configuration (optional, applied to the built sandbox template)
  runtime:
    timeout: 300              # Startup timeout in seconds (1-3600, default 300)
    memory_limit: 1Gi         # Memory limit (supports "512Mi", "1Gi", etc.)
    cpu_limit: '1'            # CPU limit (supports "1", "1000m", etc.)

# Status field (maintained by the system, should not be modified manually by users)
status:
  phase: deployed             # Current phase: pending/building/deployed/failed
  agent_id: agent-xxxxx       # Agent ID (auto-generated after deployment)
  last_deployed: '2025-10-23T10:35:00Z'  # Last deployment time
  build_id: build_xyz789      # Build ID (auto-generated after deployment)
```

### 設定の変更

#### CPU とメモリ設定の変更

`.novita-agent.yaml` の `spec.runtime` 配下にあるリソース設定を変更します。

```yaml theme={"system"}
spec:
  runtime:
    # CPU configuration
    cpu_limit: '2'        # 2 CPU cores
    # Memory configuration
    memory_limit: 2Gi     # 2 GB memory
```

#### 環境変数の変更

`.novita-agent.yaml` の `spec.envVars` は、CLI の `agent invoke` コマンドでのみ使用され、デプロイされたサンドボックステンプレートには渡されません。

`.novita-agent.yaml` の `spec.envVars` 配下にある環境変数を変更します。

```yaml theme={"system"}
spec:
  envVars:
    # LLM configuration
    MODEL_NAME: deepseek/deepseek-v3-0324
    TEMPERATURE: '0.7'
```

**注**:

* ⚠️ `.novita-agent.yaml` に API Keys などの**機密情報を保存しないでください**
* `agent invoke` コマンドを実行する際に、`--env` パラメーター経由で環境変数を渡すこともできます

#### 設定変更を適用するための再デプロイ

`.novita-agent.yaml` のリソース仕様を変更した後は、再デプロイが必要です。

```bash theme={"system"}
# Redeploy (creates a new version)
npx novita-sandbox-cli agent launch
```

***

## 環境変数の管理

サンドボックスインスタンスで実行されている Agents に環境変数を渡す方法はいくつかあります。

### 方法 1: 設定ファイルで定義する（CLI 呼び出しのみ）

`.novita-agent.yaml` の `spec.envVars` 配下に環境変数を定義します。

```yaml theme={"system"}
spec:
  envVars:
    MODEL_NAME: deepseek/deepseek-v3-0324
    TEMPERATURE: '0.7'
```

### 方法 2: SDK 経由で動的に渡す

SDK の `invoke_agent_runtime` メソッドを使用して Agent を呼び出す場合、`envVars` パラメーター経由で動的に渡します。

```python theme={"system"}
import os
from novita_sandbox.agent_runtime import AgentRuntimeClient

client = AgentRuntimeClient(api_key=os.getenv("NOVITA_API_KEY"))

response = await client.invoke_agent_runtime(
    agentId="agent-xxxxx",
    payload=payload,
    envVars={
        # Read sensitive information from environment variables
        "NOVITA_API_KEY": os.getenv("NOVITA_API_KEY"),
        "DATABASE_PASSWORD": os.getenv("DATABASE_PASSWORD"),
        
        # Or pass directly
        "MODEL_NAME": "deepseek/deepseek-v3-0324",
        "TEMPERATURE": "0.7"
    }
)
```

***

## ストリーミングレスポンス

### 同期ジェネレーターによるストリーミングの実装

Python ジェネレーターを使用してストリーミングレスポンスを実装します。

```python theme={"system"}
from novita_sandbox.agent_runtime import AgentRuntimeApp

app = AgentRuntimeApp()

@app.entrypoint
def streaming_agent(request: dict):
    """Synchronous streaming response"""
    prompt = request.get("prompt", "")

    # Use generator to return chunks
    for i, chunk in enumerate(generate_response(prompt)):
        yield {
            "chunk": chunk,
            "type": "content",
            "index": i
        }
    # Send end marker
    yield {"chunk": "", "type": "end"}

```

### 非同期ジェネレーターによるストリーミングの実装

Python 非同期ジェネレーターを使用します。

```python theme={"system"}
import asyncio

@app.entrypoint
async def async_streaming_agent(request: dict):
    """Async streaming response"""
    prompt = request.get("prompt", "")

    async for chunk in async_generate_response(prompt):
        yield {
            "chunk": chunk,
            "type": "content"
        }
    yield {"chunk": "", "type": "end"}

```

### LangChain ストリーミングレスポンスの例

LangChain を使用したストリーミングレスポンスの完全な例です。

```python theme={"system"}
import os
from langchain_openai import ChatOpenAI
from langchain.callbacks.base import BaseCallbackHandler
from novita_sandbox.agent_runtime import AgentRuntimeApp

app = AgentRuntimeApp()

class StreamingHandler(BaseCallbackHandler):
    """Streaming callback handler"""
    def __init__(self):
        self.tokens = []
    
    def on_llm_new_token(self, token: str, **kwargs):
        self.tokens.append(token)

@app.entrypoint
def langchain_streaming_agent(request: dict):
    """LangChain streaming response"""
    prompt = request.get("prompt", "")

    # Create streaming-enabled LLM
    llm = ChatOpenAI(
        api_key=os.getenv("NOVITA_API_KEY"),
        streaming=True
    )
    
    # Stream invocation
    for chunk in llm.stream(prompt):
        if chunk.content:
            yield {
                "chunk": chunk.content,
                "type": "content"
            }
    yield {"chunk": "", "type": "end"}
```

### ストリーミング Agent の呼び出し

SDK を使用してストリーミング Agent を呼び出します。

```python theme={"system"}
import asyncio
import json
import os
from novita_sandbox.agent_runtime import AgentRuntimeClient

async def call_streaming_agent():
    client = AgentRuntimeClient(api_key=os.getenv("NOVITA_API_KEY"))
    
    payload = json.dumps({
        "prompt": "Tell me a story"
    }).encode()
    
    response = await client.invoke_agent_runtime(
        agentId="agent-xxxxx",
        payload=payload
    )
    
    # Process streaming response
    print("Streaming response:")
    print(response)
```

***

## バージョン管理

### 新しい Agent バージョンのデプロイ

バージョン番号を変更し、新しいバージョンをデプロイします。

```bash theme={"system"}
# Modify version number
npx novita-sandbox-cli agent configure --agent-version 1.1.0

# Deploy new version
npx novita-sandbox-cli agent launch
```

デプロイが成功すると、新しい `agent_id` が生成されます。各デプロイでは、特定のバージョンに対応する一意の `agent_id` が生成されます。

***

## ヘルスチェック

### デフォルトのヘルスチェックエンドポイント

AgentRuntimeApp は、`/ping` ヘルスチェックエンドポイントを自動的に提供します。

```python theme={"system"}
from novita_sandbox.agent_runtime import AgentRuntimeApp

app = AgentRuntimeApp()

# Default health check automatically responds with {"status": "Healthy"}
```

### カスタムヘルスチェック

`@app.ping` デコレーターを使用して、ヘルスチェックロジックをカスタマイズします。

```python theme={"system"}
@app.ping
def custom_health_check():
    """Custom health check"""
    # Check dependent services
    db_ok = check_database_connection()
    llm_ok = check_llm_service()
    
    if db_ok and llm_ok:
        return {"status": "Healthy"}
    elif db_ok or llm_ok:
        return {"status": "HealthyBusy"}  # Partially available
    else:
        return {"status": "Unhealthy"}  # Unavailable

def check_database_connection():
    """Check database connection"""
    try:
        # Simulate database check
        return True
    except:
        return False

def check_llm_service():
    """Check LLM service"""
    try:
        # Simulate LLM service check
        return True
    except:
        return False
```

### サポートされるヘルスチェックステータス

Agents は次のヘルスステータスを返すことができます。

| ステータス         | 説明                            | HTTP ステータスコード |
| ------------- | ----------------------------- | ------------- |
| `Healthy`     | Agent は完全に利用可能です              | 200           |
| `HealthyBusy` | Agent は部分的に利用可能です（例: 高負荷を処理中） | 200           |
| `Unhealthy`   | Agent は利用できません                | 503           |

***

## マルチターン会話

### マルチターン会話での Session ID の使用

`runtimeSessionId` パラメーターを使用して、複数のリクエストを同じサンドボックスインスタンスにルーティングします。

```python theme={"system"}
import uuid
import json
import os
from novita_sandbox.agent_runtime import AgentRuntimeClient

async def multi_turn_conversation():
    runtime_session_id = str(uuid.uuid4())
    client = AgentRuntimeClient(api_key=os.getenv("NOVITA_API_KEY"))
    agent_id = "agent-xxxxx"
    
    # First turn
    response1 = await client.invoke_agent_runtime(
        agentId=agent_id,
        payload=json.dumps({"prompt": "Hello, my name is John"}).encode(),
        runtimeSessionId=runtime_session_id,
    )
    print(f"AI: {response1}")
    
    # Second turn (sent to the same sandbox instance, Agent remembers the context)
    response2 = await client.invoke_agent_runtime(
        agentId=agent_id,
        payload=json.dumps({"prompt": "What's my name?"}).encode(),
        runtimeSessionId=runtime_session_id,
    )
    print(f"AI: {response2}")  # Should answer "John"
```

***

## サンプルプロジェクト

LangGraph をベースにした完全なサンプルプロジェクトを提供しており、Novita Agent Runtime で実際の AI アプリケーションを構築する方法を示しています。

### プロジェクトリポジトリ

🔗 [https://github.com/novitalabs/Novita-CollabHub/tree/main/examples/agent-runtime/agentic-frameworks/langgraph](https://github.com/novitalabs/Novita-CollabHub/tree/main/examples/agent-runtime/agentic-frameworks/langgraph)
