> ## 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.

# Erweiterte Funktionen

Dieses Dokument behandelt erweiterte Funktionen und Best Practices für Novita Agent Runtime.

***

## Inhaltsverzeichnis

* [Referenz zur Konfigurationsdatei](#configuration-file-reference)
* [Verwaltung von Umgebungsvariablen](#environment-variables-management)
* [Streaming-Antworten](#streaming-responses)
* [Versionsverwaltung](#version-management)
* [Integritätsprüfungen](#health-checks)
* [Mehrstufige Konversationen](#multi-turn-conversations)
* [Beispielprojekte](#example-projects)

***

## Referenz zur Konfigurationsdatei

### .novita-agent.yaml-Struktur

Die `.novita-agent.yaml` Die Konfigurationsdatei verwendet das YAML-Format im Kubernetes-Stil:

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

### Konfiguration ändern

#### CPU- und Arbeitsspeichereinstellungen ändern

Ändern Sie die Ressourcenkonfiguration unter `spec.runtime` in `.novita-agent.yaml`:

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

#### Ändern von Umgebungsvariablen

Die `spec.envVars` in `.novita-agent.yaml` wird nur für die CLI verwendet `agent invoke` Befehl und wird nicht an die bereitgestellte Sandbox-Vorlage übergeben.

Ändern Sie Umgebungsvariablen unter `spec.envVars` in `.novita-agent.yaml`:

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

**Hinweis**:

* ⚠️ **Speichern Sie keine sensiblen Informationen** (wie API-Schlüssel) in `.novita-agent.yaml`
* Sie können Umgebungsvariablen auch über die `--env` Parameter beim Ausführen des `agent invoke` command

#### Erneut bereitstellen, um Konfigurationsänderungen anzuwenden

Nach dem Ändern der Ressourcenspezifikationen in `.novita-agent.yaml`, erneutes Deployment ist erforderlich:

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

***

## Verwaltung von Umgebungsvariablen

Es gibt mehrere Möglichkeiten, Umgebungsvariablen an Agenten zu übergeben, die in Sandbox-Instanzen ausgeführt werden:

### Methode 1: In der Konfigurationsdatei definieren (nur CLI-Aufruf)

Definieren Sie Umgebungsvariablen unter `spec.envVars` in `.novita-agent.yaml`:

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

### Methode 2: Dynamisch per SDK übergeben

Beim Aufrufen eines Agenten mithilfe des SDKs `invoke_agent_runtime` Methode, übergeben Sie sie dynamisch über die `envVars` parameter:

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

***

## Streaming-Antworten

### Implementierung von Streaming mit synchronen Generatoren

Verwenden Sie Python-Generatoren, um Streaming-Antworten zu implementieren:

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

```

### Streaming mit asynchronen Generatoren implementieren

Verwenden Sie asynchrone Python-Generatoren:

```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 Streaming-Response-Beispiel

Vollständiges Beispiel mit LangChain für Streaming-Antworten:

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

### Aufrufen eines Streaming-Agenten

Rufen Sie einen Streaming-Agenten mit dem SDK auf:

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

***

## Versionsverwaltung

### Bereitstellen einer neuen Agent-Version

Ändern Sie die Versionsnummer und stellen Sie eine neue Version bereit:

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

Nach erfolgreicher Bereitstellung wird ein neuer `agent_id` wird generiert. Jede Bereitstellung generiert eine eindeutige `agent_id` die einer bestimmten Version entspricht.

***

## Integritätsprüfungen

### Standard-Endpunkt für Integritätsprüfungen

AgentRuntimeApp stellt automatisch eine `/ping` Health-Check-Endpunkt:

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

app = AgentRuntimeApp()

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

### Benutzerdefinierte Integritätsprüfungen

Verwenden Sie die `@app.ping` Decorator zur Anpassung der Health-Check-Logik:

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

### Unterstützte Health-Check-Status

Agenten können die folgenden Health-Status zurückgeben:

\| Status | Beschreibung | HTTP-Statuscode |
\|--------|-------------|------------------| `Healthy` | Agent ist vollständig verfügbar | 200 | `HealthyBusy` | Agent ist teilweise verfügbar (z. B. bei hoher Verarbeitungslast) | 200 |
\| `Unhealthy` | Agent ist nicht verfügbar | 503 |

***

## Mehrstufige Unterhaltungen

### Verwenden der Sitzungs-ID für mehrstufige Unterhaltungen

Verwenden Sie die `runtimeSessionId` Parameter, um mehrere Anfragen an dieselbe Sandbox-Instanz weiterzuleiten:

```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"
```

***

## Beispielprojekte

Wir stellen ein vollständiges Beispielprojekt auf Basis von LangGraph bereit, das zeigt, wie man reale KI-Anwendungen mit Novita Agent Runtime erstellt.

### Projekt-Repository

🔗 [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)
