Kontext
Ein gemeinsames Dictionary hält Daten während des gesamten Agenten-Runs für Middleware, Prompts und Tools bereit.
Auf dieser Seite
Was ist Kontext?
Ein gemeinsames, veränderbares Dictionary, das während des gesamten Agenten-Runs verfügbar ist
Der Kontext ist ein Python-Dictionary, das zu Beginn jedes Agenten-Runs erstellt wird. Es enthält bereits System-Metadaten und die Payload der eingehenden Verbindung und kann anschließend von Middleware, Tool Hooks und Tools gelesen und verändert werden. Im Kontext gespeicherte Werte lassen sich außerdem im System-Prompt über die Template-Syntax {var} referenzieren. Der vollständige Kontext wird zusammen mit dem Run gespeichert.
Datenfluss des Kontexts
Das Kontext-Dictionary
# The context dict is shared across the entire run
context = {
# System metadata (pre-populated automatically)
"run_id": "uuid-string",
"agent_name": "assistant",
"connector_id": "uuid-string",
"timestamp": "2025-01-15T10:30:00Z",
# Original connector payload (available in before(), tools, and after())
"payload": {
"user_id": 123,
"user_name": "Peter",
"question": "How do I update my billing details?"
},
# Your custom values (set in middleware or tools)
"user_name": "Peter",
"user_id": 123,
# Added automatically after agent completes (available in after() hook)
"token_usage": {
"input_tokens": 150,
"output_tokens": 200,
"thinking_tokens": 0,
"cached_input_tokens": 0,
"total_tokens": 350
},
"duration_ms": 1234.5
}Systemfelder (run_id, agent_name, connector_id, timestamp) und payload werden automatisch gesetzt. Beliebige eigene Schlüssel-Wert-Paare lassen sich ergänzen.
Kontext in Middleware
Sowohl der Hook before() als auch after() erhalten den Kontext als zweiten Parameter. Verwende context["payload"] in before(), um JSON-Bodys von Webhooks, Formularfelder, GET-Query-Parameter und andere Eingaben der Verbindung zu lesen. Setze Werte mit before(); lies den finalen Zustand mit after(), einschließlich aller Werte, die Tools während des Runs gesetzt haben.
from typing import Any, Dict
async def before(content: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]:
"""Set values on context that are available everywhere."""
# Read request data from the original connector payload.
payload = context.get("payload", {})
# Copy selected values into top-level context so prompts can reference
# them as {user_name}, {user_id}, and {subscription_tier}.
context["user_name"] = payload.get("user_name", "there")
context["user_id"] = payload.get("user_id")
# Store additional request data for prompts/tools.
context["subscription_tier"] = payload.get("subscription_tier", "free")
return content
async def after(response: str, context: Dict[str, Any]) -> str:
"""Read values from context, including those set by tools."""
# Access system metadata
run_id = context.get("run_id")
duration = context.get("duration_ms")
# Access values set by tools during the run
api_calls_made = context.get("api_calls_made", 0)
return responseKontext in Tools
Um in einem Tool auf den Kontext zuzugreifen, füge der Funktionssignatur einen optionalen Parameter context hinzu. Connic stellt den Wert bereit. Der Parameter ist für das LLM verborgen, erscheint also nicht im Tool-Schema und wird nicht vom KI-Modell ausgefüllt.
from typing import Any, Dict
async def lookup_customer(email: str, context: Dict[str, Any]) -> dict:
"""Look up a customer by email in the CRM.
Args:
email: The customer's email address
Returns:
Customer details from the CRM
"""
# Read values set by middleware
user_id = context.get("user_id")
tier = context.get("subscription_tier", "free")
# ... perform the lookup ...
customer = {"email": email, "name": "Jane Doe", "plan": tier}
# Write values back to context for other tools or the after() hook
context["api_calls_made"] = context.get("api_calls_made", 0) + 1
context["last_customer_lookup"] = email
return customerDer Parameter context ist optional. Füge ihn nur hinzu, wenn ein Tool gemeinsame Run-Daten benötigt.
Kontext in Prompts
Jeder Wert im Kontext lässt sich im system_prompt des Agenten über die Syntax {variable_name} referenzieren. Die Variablen werden zur Laufzeit ersetzt, bevor der Prompt an das KI-Modell gesendet wird.
version: "1.0"
name: assistant
model: connic/gpt-5.6-terra
description: "Support assistant with user context"
system_prompt: |
You are a support assistant for {user_name} (ID: {user_id}).
Their subscription tier is {subscription_tier}.
Always address the user by name and tailor your responses
to their subscription level.
tools:
- crm.lookup_customer# System prompt template
system_prompt: |
Hello {user_name}, your account ID is {user_id}.
# If before() set context = {"user_name": "Peter", "user_id": 123}
# The agent sees:
# "Hello Peter, your account ID is 123."
# Unmatched placeholders are left as-is:
# {unknown_var} stays as {unknown_var} in the promptSichere Ersetzung: Wenn ein Platzhalter wie {unknown_var} keinen passenden Kontextwert hat, bleibt er im Prompt unverändert. Es wird kein Fehler ausgelöst.
Vollständiges Beispiel: End-to-End-Ablauf
Ein vollständiges Beispiel dafür, wie der Kontext von Middleware durch Prompts und Tools bis zurück zum After-Hook fließt.
# 1. middleware/assistant.py - Derive context values from the payload
async def before(content, context):
payload = context.get("payload", {})
context["user_name"] = payload.get("user_name", "there")
context["user_id"] = payload.get("user_id")
context["locale"] = payload.get("locale", "en-US")
return content
# 2. agents/assistant.yaml - Reference in prompts
# system_prompt: "Assist {user_name} (locale: {locale})"
# 3. tools/billing.py - Read and write context
async def get_invoice(invoice_id: str, context: dict) -> dict:
user_id = context.get("user_id") # Read from middleware
context["last_invoice"] = invoice_id # Write for after() hook
return {"invoice_id": invoice_id, "user_id": user_id}
# 4. middleware/assistant.py - Access everything in after()
async def after(response, context):
# context contains: run_id, agent_name, user_name, user_id,
# locale, last_invoice, token_usage, duration_ms
return responsePersistenz
Nach Abschluss des Runs wird das vollständige Kontext-Dictionary aus System-Metadaten und eigenen Werten im Run-Protokoll gespeichert. Es ist in den Run-Details im Dashboard und über die API verfügbar.