Skip to content

Commit 68fb972

Browse files
feat: add input variable value examples
- simple_input.py: Basic user input example - medium_complexity_input.py: Multiple inputs with tools and context - advanced_dynamic_input.py: Class-based system with conditional logic - environment_variable_input.py: Combining env vars with user input - streamlit_ui_input.py: Web-based UI for dynamic input These examples demonstrate various approaches to handling dynamic user input in PraisonAI agents. Closes #66 Co-authored-by: Mervin Praison <[email protected]>
1 parent 0c299ad commit 68fb972

File tree

5 files changed

+485
-0
lines changed

5 files changed

+485
-0
lines changed
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
"""
2+
Advanced Dynamic Input Example for PraisonAI
3+
4+
This example demonstrates an advanced system that dynamically creates agents and tasks
5+
based on user inputs, including conditional logic, custom configurations, and file output.
6+
"""
7+
8+
from praisonaiagents import Agent, Task, PraisonAIAgents
9+
from praisonaiagents.tools import duckduckgo
10+
import os
11+
from typing import Dict, List
12+
13+
class DynamicAgentSystem:
14+
"""Advanced system for handling dynamic user inputs"""
15+
16+
def __init__(self):
17+
self.user_preferences = {}
18+
self.llm_config = {
19+
"model": os.getenv("LLM_MODEL", "gpt-4o-mini"),
20+
"temperature": 0.7
21+
}
22+
23+
def collect_user_inputs(self) -> Dict[str, str]:
24+
"""Collect multiple user inputs"""
25+
inputs = {}
26+
inputs['topic'] = input("What topic would you like to explore? ")
27+
inputs['depth'] = input("Analysis depth (quick/detailed)? ").lower() or "quick"
28+
inputs['output_format'] = input("Output format (summary/report/bullets)? ").lower() or "summary"
29+
inputs['language'] = input("Language preference (en/es/fr)? ").lower() or "en"
30+
return inputs
31+
32+
def create_dynamic_agents(self, inputs: Dict[str, str]) -> List[Agent]:
33+
"""Create agents based on user inputs"""
34+
agents = []
35+
36+
# Research agent with dynamic configuration
37+
research_agent = Agent(
38+
name="ResearchExpert",
39+
role=f"{'Detailed' if inputs['depth'] == 'detailed' else 'Quick'} Research Specialist",
40+
goal=f"Conduct {inputs['depth']} research on {inputs['topic']} in {inputs['language']}",
41+
backstory=f"Multilingual expert specializing in {inputs['depth']} analysis",
42+
tools=[duckduckgo],
43+
self_reflect=inputs['depth'] == 'detailed',
44+
llm=self.llm_config
45+
)
46+
agents.append(research_agent)
47+
48+
# Format agent based on output preference
49+
format_agent = Agent(
50+
name="FormatExpert",
51+
role=f"{inputs['output_format'].title()} Formatter",
52+
goal=f"Format research into {inputs['output_format']} style",
53+
backstory=f"Expert in creating {inputs['output_format']} documents",
54+
llm=self.llm_config
55+
)
56+
agents.append(format_agent)
57+
58+
# Optional quality agent for detailed analysis
59+
if inputs['depth'] == 'detailed':
60+
quality_agent = Agent(
61+
name="QualityChecker",
62+
role="Quality Assurance Specialist",
63+
goal="Verify accuracy and completeness",
64+
backstory="Expert in fact-checking and quality control",
65+
llm=self.llm_config
66+
)
67+
agents.append(quality_agent)
68+
69+
return agents
70+
71+
def create_dynamic_tasks(self, agents: List[Agent], inputs: Dict[str, str]) -> List[Task]:
72+
"""Create tasks based on user inputs and agents"""
73+
tasks = []
74+
75+
# Research task
76+
research_task = Task(
77+
description=f"""
78+
Research '{inputs['topic']}' with the following requirements:
79+
- Depth: {inputs['depth']}
80+
- Language: {inputs['language']}
81+
- Find {'5-10' if inputs['depth'] == 'detailed' else '3-5'} key points
82+
- Include sources and citations
83+
""",
84+
expected_output=f"Research findings about {inputs['topic']} with sources",
85+
agent=agents[0], # Research agent
86+
name="research_phase"
87+
)
88+
tasks.append(research_task)
89+
90+
# Formatting task
91+
format_instructions = {
92+
'summary': "Create a concise paragraph summary",
93+
'report': "Create a structured report with sections",
94+
'bullets': "Create a bullet-point list of key findings"
95+
}
96+
97+
format_task = Task(
98+
description=f"""
99+
Format the research findings as follows:
100+
- Style: {format_instructions[inputs['output_format']]}
101+
- Language: {inputs['language']}
102+
- Maintain all source citations
103+
""",
104+
expected_output=f"{inputs['output_format'].title()} of {inputs['topic']}",
105+
agent=agents[1], # Format agent
106+
context=[research_task],
107+
name="formatting_phase"
108+
)
109+
tasks.append(format_task)
110+
111+
# Quality check task (if detailed)
112+
if inputs['depth'] == 'detailed' and len(agents) > 2:
113+
quality_task = Task(
114+
description="Verify all facts, check sources, and ensure completeness",
115+
expected_output="Quality-assured final output with verification notes",
116+
agent=agents[2], # Quality agent
117+
context=[format_task],
118+
name="quality_phase"
119+
)
120+
tasks.append(quality_task)
121+
122+
return tasks
123+
124+
def run(self):
125+
"""Main execution flow"""
126+
# Collect inputs
127+
print("🎯 PraisonAI Dynamic Input System")
128+
print("-" * 40)
129+
inputs = self.collect_user_inputs()
130+
131+
# Create dynamic agents and tasks
132+
agents = self.create_dynamic_agents(inputs)
133+
tasks = self.create_dynamic_tasks(agents, inputs)
134+
135+
# Configure process based on depth
136+
process = "hierarchical" if inputs['depth'] == 'detailed' else "sequential"
137+
138+
# Run the system
139+
print(f"\n🚀 Starting {process} analysis for '{inputs['topic']}'...")
140+
praison_agents = PraisonAIAgents(
141+
agents=agents,
142+
tasks=tasks,
143+
process=process,
144+
verbose=inputs['depth'] == 'detailed'
145+
)
146+
147+
result = praison_agents.start()
148+
149+
# Save results if detailed
150+
if inputs['depth'] == 'detailed':
151+
filename = f"{inputs['topic'].replace(' ', '_')}_{inputs['output_format']}.txt"
152+
with open(filename, 'w', encoding='utf-8') as f:
153+
f.write(result)
154+
print(f"\n📄 Results saved to: {filename}")
155+
156+
return result
157+
158+
# Usage
159+
if __name__ == "__main__":
160+
system = DynamicAgentSystem()
161+
result = system.run()
162+
print("\n📊 Final Result:")
163+
print(result)
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""
2+
Environment Variable Input Example for PraisonAI
3+
4+
This example demonstrates how to use environment variables combined with user input
5+
to create flexible agent configurations that can be pre-configured via environment.
6+
"""
7+
8+
import os
9+
from praisonaiagents import Agent, Task, PraisonAIAgents
10+
11+
# Set via environment or use default
12+
default_topic = os.getenv("RESEARCH_TOPIC", "AI trends")
13+
user_topic = input(f"Topic to research [{default_topic}]: ") or default_topic
14+
15+
# Get other configuration from environment
16+
llm_model = os.getenv("LLM_MODEL", "gpt-4o-mini")
17+
temperature = float(os.getenv("LLM_TEMPERATURE", "0.7"))
18+
max_retries = int(os.getenv("MAX_RETRIES", "3"))
19+
20+
# Create agent with environment-based configuration
21+
agent = Agent(
22+
name="Researcher",
23+
role="Research Assistant",
24+
goal=f"Research {user_topic}",
25+
backstory="Expert researcher with configurable capabilities",
26+
llm={
27+
"model": llm_model,
28+
"temperature": temperature
29+
},
30+
max_retry_limit=max_retries
31+
)
32+
33+
# Create task
34+
task = Task(
35+
description=f"Research and summarize: {user_topic}",
36+
expected_output="Comprehensive summary with key findings",
37+
agent=agent
38+
)
39+
40+
# Show configuration
41+
print(f"\n🔧 Configuration:")
42+
print(f" - Topic: {user_topic}")
43+
print(f" - Model: {llm_model}")
44+
print(f" - Temperature: {temperature}")
45+
print(f" - Max Retries: {max_retries}")
46+
print("\n" + "="*50 + "\n")
47+
48+
# Run agents
49+
agents = PraisonAIAgents(agents=[agent], tasks=[task])
50+
result = agents.start()
51+
52+
# Save to environment-specified location if provided
53+
output_path = os.getenv("OUTPUT_PATH")
54+
if output_path:
55+
output_file = os.path.join(output_path, f"{user_topic.replace(' ', '_')}_research.txt")
56+
with open(output_file, 'w', encoding='utf-8') as f:
57+
f.write(result)
58+
print(f"\n📁 Results saved to: {output_file}")
59+
60+
print("\n✅ Research completed!")
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
Medium Complexity Input Example for PraisonAI
3+
4+
This example shows how to use multiple user inputs to create a more sophisticated
5+
agent system with tools, multiple agents, and context passing between tasks.
6+
"""
7+
8+
from praisonaiagents import Agent, Task, PraisonAIAgents
9+
from praisonaiagents.tools import duckduckgo
10+
11+
# Get multiple inputs
12+
topic = input("Enter search topic: ")
13+
num_results = input("How many results? (default: 5): ") or "5"
14+
15+
# Create search agent with tools
16+
search_agent = Agent(
17+
name="WebSearcher",
18+
role="Search Specialist",
19+
goal=f"Find {num_results} relevant results about {topic}",
20+
backstory="Expert in internet research and data collection",
21+
tools=[duckduckgo],
22+
self_reflect=False
23+
)
24+
25+
# Create analysis agent
26+
analysis_agent = Agent(
27+
name="Analyzer",
28+
role="Data Analyst",
29+
goal="Analyze and summarize search results",
30+
backstory="Expert in data synthesis and reporting"
31+
)
32+
33+
# Create tasks with context passing
34+
search_task = Task(
35+
description=f"Search for '{topic}' and find top {num_results} results",
36+
expected_output=f"List of {num_results} relevant results with sources",
37+
agent=search_agent,
38+
name="search_task"
39+
)
40+
41+
analyze_task = Task(
42+
description="Analyze the search results and create a summary report",
43+
expected_output="Comprehensive summary with key insights",
44+
agent=analysis_agent,
45+
context=[search_task], # Receives results from search_task
46+
name="analysis_task"
47+
)
48+
49+
# Run sequential process
50+
agents = PraisonAIAgents(
51+
agents=[search_agent, analysis_agent],
52+
tasks=[search_task, analyze_task],
53+
process="sequential"
54+
)
55+
agents.start()
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
Simple Input Example for PraisonAI
3+
4+
This example demonstrates how to use basic user input to create dynamic agents and tasks.
5+
The user is prompted for a search query, and the agent searches for information about it.
6+
"""
7+
8+
from praisonaiagents import Agent, Task, PraisonAIAgents
9+
10+
# Get user input
11+
user_query = input("What would you like to search for? ")
12+
13+
# Create agent
14+
agent = Agent(
15+
name="SearchAgent",
16+
role="Information Finder",
17+
goal="Find information about user's query",
18+
backstory="Expert researcher with web access"
19+
)
20+
21+
# Create task with dynamic input
22+
task = Task(
23+
description=f"Search for information about: {user_query}",
24+
expected_output=f"Summary of findings about {user_query}",
25+
agent=agent
26+
)
27+
28+
# Run
29+
agents = PraisonAIAgents(agents=[agent], tasks=[task])
30+
agents.start()

0 commit comments

Comments
 (0)