Complete Flow Examples

Explore end-to-end examples showing multi-agent scientific collaboration. Each example demonstrates the full workflow from agent creation to automated discussions.

Scientific Discovery Lab
Create a multi-agent scientific research environment where Einstein, Darwin, and a Scientific Researcher collaborate on theories.
multi-agent
bulk-creation
knowledge
collaboration
1from dialetica import Dialetica, AgentRequest, ContextRequest, KnowledgeRequest, MessageRequest
2
3client = Dialetica(api_key="dai_your_api_key")
4
5# Step 1: Create three scientific agents using bulk creation
6agents = client.agents.bulk_create([
7    AgentRequest(
8        name="Scientific Researcher",
9        description="Analyzes data and formulates hypotheses",
10        instructions=["You are a scientific researcher", "Analyze objectively and propose testable hypotheses"],
11        model="auto/auto",
12        temperature=0.7,
13        max_tokens=1200
14    ),
15    AgentRequest(
16        name="Einstein",
17        description="Theoretical physicist exploring spacetime and relativity",
18        instructions=["You are Einstein", "Discuss relativity, quantum mechanics, and unified theories"],
19        model="anthropic/claude-3-5-sonnet-20241022",
20        temperature=0.7,
21        max_tokens=1500
22    ),
23    AgentRequest(
24        name="Darwin",
25        description="Biologist studying evolution and natural selection",
26        instructions=["You are Darwin", "Explain evolution, adaptation, and the origin of species"],
27        model="google/gemini-2.0-flash-exp:free",
28        temperature=0.6,
29        max_tokens=1400
30    )
31])
32
33researcher_id = agents[0].id
34einstein_id = agents[1].id
35darwin_id = agents[2].id
36
37print(f"βœ… Created {len(agents)} scientific agents")
38
39# Step 2: Create Scientific Discovery Lab context
40context = client.contexts.create(ContextRequest(
41    name="Scientific Discovery Lab",
42    description="Multi-agent scientific research collaboration",
43    instructions=[
44        "Agents collaborate on scientific hypotheses",
45        "Share insights and build upon each other's theories",
46        "Work together to advance understanding"
47    ],
48    agents=[researcher_id, einstein_id, darwin_id],
49    context_window_size=16000,
50    is_public=True
51))
52
53print(f"βœ… Created context: {context.id}")
54
55# Step 3: Start multi-agent scientific collaboration
56# ONE API CALL triggers entire multi-turn discussion!
57messages = [MessageRequest(
58    role="user",
59    sender_name="Student",
60    content="How might quantum mechanics and evolution inform our understanding of consciousness?"
61)]
62
63responses = client.contexts.run(context.id, messages)
64
65print(f"\nπŸ”¬ Scientific collaboration complete! {len(responses)} responses:")
66for response in responses:
67    print(f"\n{response.sender_name}: {response.content[:200]}...")
68
69# Step 4: Store new insights discovered during the discussion
70# Save novel hypotheses that agents generated for future reference
71for response in responses:
72    if "hypothesis" in response.content.lower() or "theory" in response.content.lower():
73        client.knowledge.create(KnowledgeRequest(
74            knowledge=f"[{response.sender_name}] New insight: {response.content}",
75            context_id=context.id,
76            agent_id=None,  # Available to all agents for future discussions
77            metadata={
78                "type": "generated_insight",
79                "agent": response.sender_name,
80                "timestamp": "2024-01-15"
81            }
82        ))
83
84print("\nβœ… Novel insights stored in knowledge base for future research")
Physics Research Session with Streaming
Stream real-time responses from Einstein and Scientific Researcher discussing theoretical physics. Includes session management and updated event structure.
streaming
multi-agent
async
physics
session-management
1from dialetica import Dialetica, ContextRequest, AgentRequest, MessageRequest
2import asyncio
3
4client = Dialetica(api_key="dai_your_api_key")
5
6# Create Einstein and Researcher
7agents = client.agents.bulk_create([
8    AgentRequest(
9        name="Einstein",
10        description="Theoretical physicist",
11        instructions=["You are Einstein", "Explain relativity and quantum mechanics"],
12        model="anthropic/claude-3-5-sonnet-20241022",
13        temperature=0.7,
14        max_tokens=1500
15    ),
16    AgentRequest(
17        name="Scientific Researcher",
18        description="Analyzes physics theories",
19        instructions=["You are a researcher", "Ask probing questions and analyze theories"],
20        model="auto/auto",
21        temperature=0.7,
22        max_tokens=1000
23    )
24])
25
26# Create Physics Research context
27context = client.contexts.create(ContextRequest(
28    name="Physics Research",
29    description="Einstein explores theoretical physics with Researcher",
30    instructions=["Focus on relativity and quantum mechanics"],
31    agents=[agents[0].id, agents[1].id],
32    context_window_size=8000,
33    is_public=True
34))
35
36# Stream the multi-agent discussion in real-time with new event structure
37async def stream_physics_discussion():
38    messages = [MessageRequest(
39        role="user",
40        sender_name="Professor",
41        content="Einstein, explain how spacetime curvature relates to quantum entanglement"
42    )]
43    
44    print("πŸ”¬ Starting physics discussion...\n")
45    session_id = None
46    
47    async for event in client.contexts.run_streamed(context.id, messages):
48        event_type = event.get('type')
49        payload = event.get('payload', {})
50        
51        # Session lifecycle events
52        if event_type == 'session_started':
53            session_id = payload.get('session_id')
54            print(f"🎬 Session started: {session_id}\n")
55        
56        # Turn events (context or agent starting/completing)
57        elif event_type == 'turn_started':
58            kind = payload.get('kind')
59            name = payload.get('runnable_name')
60            if kind == 'agent':
61                print(f"\nπŸ’­ {name} is thinking...\n")
62            elif kind == 'context':
63                print(f"\n🎯 Context orchestrating...\n")
64        
65        # Token-by-token streaming (new structure)
66        elif event_type == 'token_delta' and payload.get('kind') == 'agent':
67            print(payload.get('delta', ''), end='', flush=True)
68        
69        # Turn completion
70        elif event_type == 'turn_completed':
71            kind = payload.get('kind')
72            name = payload.get('runnable_name')
73            if kind == 'agent':
74                print(f"\nβœ… {name} completed\n")
75        
76        # Session completion
77        elif event_type == 'session_completed':
78            print(f"\nπŸŽ‰ Session completed successfully!")
79        elif event_type == 'session_failed':
80            print(f"\n❌ Session failed: {payload.get('reason')}")
81    
82    return session_id
83
84session_id = asyncio.run(stream_physics_discussion())
85
86# Example: Cancel session if needed
87# client.contexts.cancel_session(context.id, session_id)
Model Discovery and Selection
Discover available AI models and select the best one for your use case based on tier (free/pro) and capabilities.
models
discovery
model-selection
1from dialetica import Dialetica, AgentRequest
2
3client = Dialetica(api_key="dai_your_api_key")
4
5# Get all available models
6models = client.models.list()
7
8print("Available AI Models:")
9print("=" * 70)
10for model in models:
11    tier_badge = "πŸ†“ FREE" if model['tier'] == 'free' else "πŸ’Ž PRO"
12    print(f"{tier_badge:10} {model['label']:30} {model['model']}")
13
14# Filter models by tier
15free_models = [m for m in models if m['tier'] == 'free']
16pro_models = [m for m in models if m['tier'] == 'pro']
17
18print(f"\nπŸ“Š Summary:")
19print(f"   Free models: {len(free_models)}")
20print(f"   Pro models: {len(pro_models)}")
21print(f"   Total: {len(models)}")
22
23# Create agents using different models based on tier
24free_agent = client.agents.create(AgentRequest(
25    name="Free Tier Assistant",
26    description="Uses a free tier model",
27    instructions=["You are a helpful assistant"],
28    model=free_models[0]['model']  # Use first free model
29))
30
31pro_agent = client.agents.create(AgentRequest(
32    name="Pro Tier Assistant",
33    description="Uses a pro tier model",
34    instructions=["You are a helpful assistant"],
35    model=pro_models[0]['model']  # Use first pro model
36))
37
38print(f"\nβœ… Created agents:")
39print(f"   Free: {free_agent.id} ({free_agent.model})")
40print(f"   Pro: {pro_agent.id} ({pro_agent.model})")
Session Management and Cancellation
Monitor and control active sessions. Cancel long-running operations, list active sessions, and handle user-initiated stops.
session-management
cancellation
monitoring
control
1from dialetica import Dialetica, ContextRequest, AgentRequest, MessageRequest
2import asyncio
3import signal
4
5client = Dialetica(api_key="dai_your_api_key")
6
7# Create a context for long-running research
8agents = client.agents.bulk_create([
9    AgentRequest(
10        name="Deep Researcher",
11        description="Conducts thorough research",
12        instructions=["You conduct deep, detailed research"],
13        model="anthropic/claude-3-5-sonnet-20241022",
14        max_tokens=4000  # Long responses
15    )
16])
17
18context = client.contexts.create(ContextRequest(
19    name="Research Session",
20    description="Long-running research context",
21    agents=[agents[0].id],
22    context_window_size=16000
23))
24
25# Example 1: Monitor and cancel a session
26async def monitored_research():
27    messages = [MessageRequest(
28        role="user",
29        sender_name="Researcher",
30        content="Write a comprehensive analysis of quantum computing"
31    )]
32    
33    session_id = None
34    token_count = 0
35    
36    async for event in client.contexts.run_streamed(context.id, messages):
37        event_type = event.get('type')
38        payload = event.get('payload', {})
39        
40        if event_type == 'session_started':
41            session_id = payload.get('session_id')
42            print(f"πŸ“Š Session {session_id} started")
43        
44        elif event_type == 'token_delta' and payload.get('kind') == 'agent':
45            token_count += len(payload.get('delta', ''))
46            print(payload.get('delta', ''), end='', flush=True)
47            
48            # Example: Cancel if response gets too long
49            if token_count > 1000:
50                print(f"\n\n⚠️ Response getting long, cancelling session...")
51                client.contexts.cancel_session(context.id, session_id)
52                break
53        
54        elif event_type == 'session_failed':
55            if payload.get('reason') == 'cancelled':
56                print(f"\nβœ… Session cancelled successfully")
57    
58    return session_id
59
60# Example 2: List all active sessions
61def list_active_sessions():
62    sessions = client.contexts.list_sessions(context.id)
63    
64    if not sessions:
65        print("No active sessions")
66        return
67    
68    print(f"\nπŸ“‹ Active Sessions ({len(sessions)}):")
69    for session in sessions:
70        print(f"   - {session['session_id']}")
71        print(f"     Depth: {session['depth']}/{session['max_depth']}")
72        print(f"     User: {session['user_id']}")
73
74# Example 3: Cancel all active sessions
75def cancel_all_sessions():
76    sessions = client.contexts.list_sessions(context.id)
77    
78    for session in sessions:
79        success = client.contexts.cancel_session(context.id, session['session_id'])
80        if success:
81            print(f"βœ… Cancelled session {session['session_id']}")
82        else:
83            print(f"❌ Failed to cancel session {session['session_id']}")
84
85# Run the monitored research
86session_id = asyncio.run(monitored_research())
87
88# List sessions after
89list_active_sessions()
Research Lab with Private Data
Scientists collaborate using a private knowledge base of experimental results and proprietary research data.
knowledge
semantic-search
multi-agent
private-data
1from dialetica import Dialetica, AgentRequest, ContextRequest, KnowledgeRequest, MessageRequest
2
3client = Dialetica(api_key="dai_your_api_key")
4
5# Create all three scientists
6agents = client.agents.bulk_create([
7    AgentRequest(
8        name="Einstein",
9        description="Theoretical physicist",
10        instructions=["You are Einstein", "Analyze experimental data and propose theories"],
11        model="anthropic/claude-3-5-sonnet-20241022",
12        temperature=0.7
13    ),
14    AgentRequest(
15        name="Darwin",
16        description="Evolutionary biologist",
17        instructions=["You are Darwin", "Interpret biological observations"],
18        model="google/gemini-2.0-flash-exp:free",
19        temperature=0.6
20    ),
21    AgentRequest(
22        name="Scientific Researcher",
23        description="Lab researcher",
24        instructions=["You collect and analyze experimental data"],
25        model="auto/auto",
26        temperature=0.7
27    )
28])
29
30# Create research lab context
31context = client.contexts.create(ContextRequest(
32    name="Private Research Lab",
33    description="Proprietary research with private experimental data",
34    instructions=["Analyze private lab results", "Reference specific experiments by ID"],
35    agents=[agent.id for agent in agents],
36    context_window_size=20000,
37    is_public=False  # Private research context
38))
39
40# Add PRIVATE experimental data that LLMs wouldn't know
41# This is proprietary lab data, patient records, company secrets, etc.
42private_experiments = [
43    "Experiment #2847 (Jan 2024): Novel gene sequence AGTC-9923 shows 340% increased longevity in test subjects. Proprietary to LabCorp.",
44    "Experiment #2891 (Feb 2024): Quantum coherence maintained for 47 seconds at room temperature using compound X-772. Patent pending.",
45    "Patient Study #445: Patient cohort of 1,200 individuals shows genetic marker YZ-443 correlates with 89% resistance to disease Alpha-7.",
46    "Internal Memo: Our new protein folding algorithm reduces computational time by 95% compared to AlphaFold. Confidential.",
47    "Field Observation Log #89: New species discovered in Amazon Basin - exhibits bioluminescence pattern unique to genus. Coordinates: 3.4532Β°S, 62.2163Β°W"
48]
49
50# Store private data in knowledge base
51for experiment in private_experiments:
52    client.knowledge.create(KnowledgeRequest(
53        knowledge=experiment,
54        context_id=context.id,
55        agent_id=None,  # Available to all agents in this private context
56        metadata={"type": "proprietary_data", "confidential": True}
57    ))
58
59print("βœ… Private experimental data loaded into knowledge base")
60
61# Ask agents to analyze the private data
62messages = [MessageRequest(
63    role="user",
64    sender_name="Lab Director",
65    content="Review our recent experiments #2847 and #2891. What connections do you see? Can we combine these findings?"
66)]
67
68# Agents will use semantic search to retrieve relevant private experiments
69# They can ONLY access this data because it's in the knowledge base
70responses = client.contexts.run(context.id, messages)
71
72print(f"\nπŸ”¬ {len(responses)} scientific analyses of private data:")
73for response in responses:
74    print(f"\n{'='*60}")
75    print(f"{response.sender_name}:")
76    print(response.content)
Automated Daily Research Sessions
Schedule automated scientific discussions using cron jobs for continuous exploration.
cron
automation
scheduled-tasks
multi-agent
1from dialetica import Dialetica, AgentRequest, ContextRequest, CronRequest
2
3client = Dialetica(api_key="dai_your_api_key")
4
5# Create scientific agents
6agents = client.agents.bulk_create([
7    AgentRequest(
8        name="Einstein",
9        description="Theoretical physicist",
10        instructions=["You are Einstein", "Explore theoretical physics"],
11        model="anthropic/claude-3-5-sonnet-20241022"
12    ),
13    AgentRequest(
14        name="Darwin",
15        description="Evolutionary biologist",
16        instructions=["You are Darwin", "Investigate evolution and life"],
17        model="google/gemini-2.0-flash-exp:free"
18    ),
19    AgentRequest(
20        name="Scientific Researcher",
21        description="General researcher",
22        instructions=["You synthesize scientific insights"],
23        model="auto/auto"
24    )
25])
26
27# Create research contexts
28physics_context = client.contexts.create(ContextRequest(
29    name="Daily Physics Research",
30    description="Einstein and Researcher explore physics",
31    agents=[agents[0].id, agents[2].id],
32    context_window_size=8000,
33    is_public=True
34))
35
36biology_context = client.contexts.create(ContextRequest(
37    name="Weekly Evolution Study",
38    description="Darwin and Researcher study evolution",
39    agents=[agents[1].id, agents[2].id],
40    context_window_size=8000,
41    is_public=True
42))
43
44# Schedule automated research sessions
45crons = client.crons.bulk_create([
46    CronRequest(
47        name="Morning Physics Discussion",
48        prompt="Einstein, share your latest insights on quantum mechanics and relativity",
49        context_id=physics_context.id,
50        cron_expression="0 9 * * *"  # Every day at 9 AM
51    ),
52    CronRequest(
53        name="Weekly Evolution Research",
54        prompt="Darwin, discuss recent thoughts on natural selection and speciation",
55        context_id=biology_context.id,
56        cron_expression="0 10 * * 1"  # Every Monday at 10 AM
57    ),
58    CronRequest(
59        name="Friday Interdisciplinary Synthesis",
60        prompt="How can physics and biology inform each other? Find connections.",
61        context_id=physics_context.id,
62        cron_expression="0 15 * * 5"  # Every Friday at 3 PM
63    )
64])
65
66print(f"βœ… Scheduled {len(crons)} automated research sessions:")
67for cron in crons:
68    print(f"   - {cron.name}: {cron.cron_expression}")
69
70# List all scheduled crons
71all_crons = client.crons.list()
72print(f"\nπŸ“… Total active research sessions: {len(all_crons)}")
Ready to Get Started?
Start building your own multi-agent applications with Dialetica AI.