class GeminiAutoGenFramework:
"""
Full AutoGen framework using free Gemini API
Helps multi-agent conversations, code execution, and retrieval
"""
def __init__(self, gemini_api_key: str):
"""Initialize with Gemini API key"""
self.gemini_api_key = gemini_api_key
self.setup_gemini_config()
self.brokers: Dict[str, autogen.Agent] = {}
self.group_chats: Dict[str, GroupChat] = {}
def setup_gemini_config(self):
"""Configure Gemini for AutoGen"""
os.environ["GOOGLE_API_KEY"] = self.gemini_api_key
self.llm_config = {
"config_list": [
{
"model": "gemini/gemini-1.5-flash",
"api_key": self.gemini_api_key,
"api_type": "google",
"temperature": 0.7,
"max_tokens": 4096,
}
],
"timeout": 120,
"cache_seed": 42,
}
self.llm_config_pro = {
"config_list": [
{
"model": "gemini/gemini-1.5-pro",
"api_key": self.gemini_api_key,
"api_type": "google",
"temperature": 0.5,
"max_tokens": 8192,
}
],
"timeout": 180,
"cache_seed": 42,
}
def create_assistant_agent(self, establish: str, system_message: str,
use_pro_model: bool = False) -> AssistantAgent:
"""Create a specialised assistant agent"""
config = self.llm_config_pro if use_pro_model else self.llm_config
agent = AssistantAgent(
establish=establish,
system_message=system_message,
llm_config=config,
human_input_mode="NEVER",
max_consecutive_auto_reply=10,
code_execution_config=False,
)
self.brokers[name] = agent
return agent
def create_user_proxy(self, establish: str = "UserProxy",
enable_code_execution: bool = True) -> UserProxyAgent:
"""Create individual proxy agent with non-compulsory code execution"""
code_config = {
"work_dir": "autogen_workspace",
"use_docker": False,
"timeout": 60,
"last_n_messages": 3,
} if enable_code_execution else False
agent = UserProxyAgent(
establish=establish,
human_input_mode="TERMINATE",
max_consecutive_auto_reply=0,
is_termination_msg=lambda x: x.get("content material materials", "").rstrip().endswith("TERMINATE"),
code_execution_config=code_config,
system_message="""A human admin. Work along with the brokers to resolve duties.
Reply TERMINATE when the obligation is solved."""
)
self.brokers[name] = agent
return agent
def create_research_team(self) -> Dict[str, autogen.Agent]:
"""Create a research-focused agent group"""
researcher = self.create_assistant_agent(
establish="Researcher",
system_message="""You are a Senior Evaluation Analyst. Your perform is to:
1. Accumulate and analyze information on given issues
2. Decide key tendencies, patterns, and insights
3. Current full evaluation summaries
4. Cite sources and preserve objectivity
On a regular basis building your evaluation with clear sections and bullet elements.
Be thorough nevertheless concise."""
)
analyst = self.create_assistant_agent(
establish="DataAnalyst",
system_message="""You are a Info Analysis Educated. Your perform is to:
1. Analyze quantitative data and statistics
2. Create data visualizations and charts
3. Decide patterns and correlations
4. Current statistical insights and interpretations
Use Python code when needed for calculations and visualizations.
On a regular basis make clear your analytical technique."""
)
writer = self.create_assistant_agent(
establish="Creator",
system_message="""You are a Technical Creator and Content material materials Strategist. Your perform is to:
1. Rework evaluation and analysis into clear, taking part content material materials
2. Create well-structured research and articles
3. Assure content material materials is accessible to the goal market
4. Protect expert tone and accuracy
Building content material materials with clear headings, bullet elements, and conclusions."""
)
executor = self.create_user_proxy("CodeExecutor", enable_code_execution=True)
return {
"researcher": researcher,
"analyst": analyst,
"writer": writer,
"executor": executor
}
def create_business_team(self) -> Dict[str, autogen.Agent]:
"""Create enterprise analysis group"""
strategist = self.create_assistant_agent(
establish="BusinessStrategist",
system_message="""You are a Senior Enterprise Method Advertising and marketing advisor. Your perform is to:
1. Analyze enterprise points and alternate options
2. Develop strategic solutions and movement plans
3. Assess market dynamics and aggressive panorama
4. Current implementation roadmaps
Suppose systematically and take note of various views.
On a regular basis current actionable solutions.""",
use_pro_model=True
)
financial_analyst = self.create_assistant_agent(
establish="FinancialAnalyst",
system_message="""You are a Financial Analysis Educated. Your perform is to:
1. Perform financial modeling and analysis
2. Assess financial risks and alternate options
3. Calculate ROI, NPV, and completely different financial metrics
4. Current value vary and funding solutions
Use quantitative analysis and provide clear financial insights."""
)
market_researcher = self.create_assistant_agent(
establish="MarketResearcher",
system_message="""You are a Market Evaluation Specialist. Your perform is to:
1. Analyze market tendencies and consumer conduct
2. Evaluation aggressive panorama and positioning
3. Decide aim markets and purchaser segments
4. Current market sizing and different analysis
Consider actionable market insights and proposals."""
)
return {
"strategist": strategist,
"financial_analyst": financial_analyst,
"market_researcher": market_researcher,
"executor": self.create_user_proxy("BusinessExecutor")
}
def create_development_team(self) -> Dict[str, autogen.Agent]:
"""Create software program program progress group"""
developer = self.create_assistant_agent(
establish="SeniorDeveloper",
system_message="""You are a Senior Software program program Developer. Your perform is to:
1. Write high-quality, surroundings pleasant code
2. Design software program program construction and choices
3. Debug and optimize current code
4. Observe best practices and coding necessities
On a regular basis make clear your code and design choices.
Consider clear, maintainable choices."""
)
devops = self.create_assistant_agent(
establish="DevOpsEngineer",
system_message="""You are a DevOps Engineer. Your perform is to:
1. Design deployment and infrastructure choices
2. Automate assemble, verify, and deployment processes
3. Monitor system effectivity and reliability
4. Implement security and scalability best practices
Consider automation, reliability, and scalability."""
)
qa_engineer = self.create_assistant_agent(
establish="QAEngineer",
system_message="""You are a Top quality Assurance Engineer. Your perform is to:
1. Design full verify strategies and cases
2. Decide potential bugs and edge cases
3. Assure code top quality and effectivity necessities
4. Validate requirements and individual acceptance requirements
Be thorough and consider edge cases and failure eventualities."""
)
return {
"developer": developer,
"devops": devops,
"qa_engineer": qa_engineer,
"executor": self.create_user_proxy("DevExecutor", enable_code_execution=True)
}
def create_group_chat(self, brokers: Report[autogen.Agent], chat_name: str,
max_round: int = 10) -> GroupChat:
"""Create group chat with specified brokers"""
group_chat = GroupChat(
brokers=brokers,
messages=[],
max_round=max_round,
speaker_selection_method="round_robin",
allow_repeat_speaker=False,
)
self.group_chats[chat_name] = group_chat
return group_chat
def run_research_project(self, matter: str, max_rounds: int = 8) -> str:
"""Run an entire evaluation enterprise"""
group = self.create_research_team()
agents_list = [team["researcher"], group["analyst"], group["writer"], group["executor"]]
group_chat = self.create_group_chat(agents_list, "research_chat", max_rounds)
supervisor = GroupChatManager(
groupchat=group_chat,
llm_config=self.llm_config
)
initial_message = f"""
Evaluation Endeavor: {matter}
Please collaborate to produce an entire evaluation report following this workflow:
1. Researcher: Accumulate information and key insights about {matter}
2. DataAnalyst: Analyze any quantitative options and create visualizations if needed
3. Creator: Create a well-structured remaining report based mostly totally on the evaluation and analysis
4. CodeExecutor: Execute any code needed for analysis or visualization
The final word deliverable must be educated evaluation report with:
- Govt summary
- Key findings and insights
- Info analysis (if related)
- Conclusions and proposals
Begin the evaluation course of now.
"""
chat_result = group["executor"].initiate_chat(
supervisor,
message=initial_message,
max_consecutive_auto_reply=0
)
return self._extract_final_result(chat_result)
def run_business_analysis(self, business_problem: str, max_rounds: int = 8) -> str:
"""Run enterprise analysis enterprise"""
group = self.create_business_team()
agents_list = [team["strategist"], group["financial_analyst"],
group["market_researcher"], group["executor"]]
group_chat = self.create_group_chat(agents_list, "business_chat", max_rounds)
supervisor = GroupChatManager(
groupchat=group_chat,
llm_config=self.llm_config_pro
)
initial_message = f"""
Enterprise Analysis Endeavor: {business_problem}
Please collaborate to produce full enterprise analysis following this technique:
1. BusinessStrategist: Analyze the enterprise disadvantage and develop strategic framework
2. FinancialAnalyst: Assess financial implications and create financial fashions
3. MarketResearcher: Evaluation market context and aggressive panorama
4. BusinessExecutor: Coordinate and compile remaining solutions
Remaining deliverable should embody:
- Draw back analysis and root causes
- Strategic solutions
- Financial have an effect on analysis
- Market different analysis
- Implementation roadmap
Begin the analysis now.
"""
chat_result = group["executor"].initiate_chat(
supervisor,
message=initial_message,
max_consecutive_auto_reply=0
)
return self._extract_final_result(chat_result)
def run_development_project(self, project_description: str, max_rounds: int = 10) -> str:
"""Run software program program progress enterprise"""
group = self.create_development_team()
agents_list = [team["developer"], group["devops"], group["qa_engineer"], group["executor"]]
group_chat = self.create_group_chat(agents_list, "dev_chat", max_rounds)
supervisor = GroupChatManager(
groupchat=group_chat,
llm_config=self.llm_config
)
initial_message = f"""
Development Endeavor: {project_description}
Please collaborate to ship a complete software program program decision:
1. SeniorDeveloper: Design construction and write core code
2. DevOpsEngineer: Plan deployment and infrastructure
3. QAEngineer: Design assessments and top quality assurance technique
4. DevExecutor: Execute code and coordinate implementation
Deliverables should embody:
- System construction and design
- Working code implementation
- Deployment configuration
- Check out cases and QA plan
- Documentation
Start progress now.
"""
chat_result = group["executor"].initiate_chat(
supervisor,
message=initial_message,
max_consecutive_auto_reply=0
)
return self._extract_final_result(chat_result)
def _extract_final_result(self, chat_result) -> str:
"""Extract and format remaining finish consequence from chat"""
if hasattr(chat_result, 'chat_history'):
messages = chat_result.chat_history
else:
messages = chat_result
final_messages = []
for msg in messages[-5:]:
if isinstance(msg, dict) and 'content material materials' in msg:
final_messages.append(f"{msg.get('establish', 'Agent')}: {msg['content']}")
return "nn".be part of(final_messages)
def get_framework_stats(self) -> Dict[str, Any]:
"""Get framework statistics"""
return {
"brokers": guidelines(self.brokers.keys()),
"group_chats": guidelines(self.group_chats.keys()),
"llm_config": {
"model": self.llm_config["config_list"][0]["model"],
"temperature": self.llm_config["config_list"][0]["temperature"]
},
"timestamp": datetime.now().isoformat()
}
Elevate your perspective with NextTech Info, the place innovation meets notion.
Uncover the latest breakthroughs, get distinctive updates, and be part of with a worldwide neighborhood of future-focused thinkers.
Unlock tomorrow’s tendencies instantly: be taught additional, subscribe to our e-newsletter, and alter into part of the NextTech group at NextTech-news.com
Keep forward of the curve with NextBusiness 24. Discover extra tales, subscribe to our e-newsletter, and be part of our rising neighborhood at nextbusiness24.com