Skip to main content
Agents can dynamically change their behavior based on the client chain or origin source of the message. This enables different response styles and capabilities depending on where the request comes from:
from timbal import Agent
from timbal.state import get_run_context

def get_origin_specific_prompt():
    """Get system prompt based on detected origin."""
    client_chain = get_run_context().current_span().client_chain
    
    prompts = {
        "whatsapp": """You are a WhatsApp business assistant. Keep responses concise and friendly. 
        Use emojis appropriately. Focus on quick, helpful answers.""",
        
        "slack": """You are a Slack bot for internal team communication. Be professional but approachable. 
        Use Slack formatting (like *bold* and _italics_). Reference team members when relevant.""",
    }
    
    return prompts.get(client_chain, """You are a helpful assistant. Adapt your response style based on the context.""")

def pre_hook():
    span = get_run_context().current_span()
    # Detect client chain from the prompt content
    if "whatsapp" in span.input["prompt"]:
        span.client_chain = "whatsapp"
    elif "slack" in span.input["prompt"]:
        span.client_chain = "slack"

# Create origin-aware agent
agent = Agent(
    name="OriginAwareAgent",
    model="openai/gpt-4o-mini",
    system_prompt="""{__main__::get_origin_specific_prompt}""",
    pre_hook=pre_hook,
)

# Simulate different client chains

# WhatsApp message - system prompt becomes WhatsApp-specific
result1 = await agent(prompt="whatsapp: Hi! I need help with my order").collect()
print(result1.output.content[0].text)
# System prompt used: "You are a WhatsApp business assistant. Keep responses concise and friendly. Use emojis appropriately. Focus on quick, helpful answers."
# Output: "Hello! 😊 I'd be happy to help you with your order. What do you need assistance with? 📦✨"

# Slack message - system prompt becomes Slack-specific  
result2 = await agent(prompt="slack: @bot Can you help me with the project status?").collect()
print(result2.output.content[0].text)
# System prompt used: "You are a Slack bot for internal team communication. Be professional but approachable. Use Slack formatting (like *bold* and _italics_). Reference team members when relevant."
# Output: "Absolutely, @user! 🔍 Can you please specify which project you're referring to? I'd be glad to provide the latest status updates! 📊"

Key Features

  • Dynamic System Prompts: System prompt changes completely based on detected origin
  • Pre-hook Detection: Use pre_hook to detect client chain from message content
  • Platform-Specific Responses: Adapt tone, format, and capabilities per platform
  • Real-time Adaptation: Each message gets the appropriate system prompt automatically