class GeminiAutoGenFramework:
"""
Gemini API allows you to create a full AutoGen Framework using the free API.
Supports multiple-agent conversation, 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-agents :[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, name: str, system_message: str,
use_pro_model: bool = False) -> AssistantAgent:
"""Create a specialized assistant agent"""
config = self.llm_config_pro if use_pro_model else self.llm_config
Agent = AssistantAgent
name=name,
system_message=system_message,
llm_config=config,
human_input_mode="NEVER",
max_consecutive_auto_reply=10,
code_execution_config=False,
)
self.agents[name] = Agent
Return agent
def create_user_proxy(self, name: str = "UserProxy",
enable_code_execution: bool = True) -> UserProxyAgent:
"""Create user proxy agent with optional 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
name=name,
human_input_mode="TERMINATE",
max_consecutive_auto_reply=0,
is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
code_execution_config=code_config,
system_message="""A human admin. Agents will assist you in solving tasks.
When the problem is resolved, reply TERMINATE."""
)
self.agents[name] Agent
Return agent
def create_research_team(self) -> Dict[str, autogen.Agent]:
"""Create a research-focused agent team"""
researcher = self.create_assistant_agent(
name="Researcher",
system_message=""You are a senior research analyst. You will be responsible for:
1. Collect and analyze data on specific topics
2. Find key patterns, trends and insights
3. Provide comprehensive research summaries
4. Cite and remain objective
Structure your research using clear bulleted sections.
Do not be hesitant to provide details, but do so concisely."""
)
analyst = self.create_assistant_agent(
name="DataAnalyst",
system_message=""You are an expert in data analysis. You will be responsible for:
1. Analysis of quantitative data
2. Data visualizations charts and graphs
3. Find patterns and correlates
4. Interpretation and statistical insight
Python is a great tool for visualizing and performing calculations.
Explain your approach to analysis."""
)
writer = self.create_assistant_agent(
name="Writer",
system_message=""You are a technical writer and content strategist. It is your role to:
1. Research and analysis can be transformed into engaging, clear content
2. Write well-structured articles and reports
3. Content should be accessible to target audiences
4. Keep a professional and accurate tone
Content should be structured with bulleted points and clear headings.Return"""
)
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 business analysis team"""
strategist = self.create_assistant_agent(
name="BusinessStrategist",
system_message=""You are an experienced Business Strategist Consultant. You will be responsible for:
1. Analysis of business opportunities and problems
2. Strategic recommendations and Action Plans
3. Market dynamics and the competitive landscape
4. Provide roadmaps for implementation
Take a systematic approach and take into account multiple perspectives.
Offer actionable suggestions.""",
use_pro_model=True
)
financial_analyst = self.create_assistant_agent(
name="FinancialAnalyst",
system_message="""You're a Financial Analysis Expert. It is your role to:
1. Financial modeling and analysis
2. Financial Risks and Opportunities
3. Calculate ROI (return on investment), NPV and other financial metrics
4. Budget and Investment Recommendations
Provide clear and quantitative financial insights using your quantitative analysis."""
)
market_researcher = self.create_assistant_agent(
name="MarketResearcher",
system_message="""You're a Market Research Analyst. You will be responsible for:
1. Market trends and consumer behaviour are analysed
2. Study the competitive landscape to determine your position.
3. Market segments and target customers can be identified.
4. Market size and opportunities assessment
Market insights and actionable recommendations are the focus.Return"""
)
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 development team"""
developer = self.create_assistant_agent(
name="SeniorDeveloper",
system_message="""You're a Senior Developer of Software. It is your role to:
1. Write high-quality, efficient code
2. Design and architecture of software solutions
3. Debugging and optimizing existing code
4. Code standards and best practices
Explain your design and code decisions.
Concentrate on solutions that are clean and maintainable."""
)
devops = self.create_assistant_agent(
name="DevOpsEngineer",
system_message="""You're a DevOps Engineering. You are responsible for:
1. Infrastructure and design solutions
2. Automate the build, test and deployment process
3. Performance and reliability of the system should be monitored
4. Use best practices for security and scaling
Concentrate on automating, scalability, and reliability."""
)
qa_engineer = self.create_assistant_agent(
name="QAEngineer",
system_message="""You're a Quality Assurance Engineering. It is your role to:
1. Test strategies and case studies:
2. Identification of potential bugs as well as edge cases
3. Code quality standards and performance must be met
4. Validate the requirements and acceptability criteria
Consider all possible failures and edge-cases.Return"""
)
return {
"developer": developer,
"devops": devops,
"qa_engineer": qa_engineer,
"executor": self.create_user_proxy("DevExecutor", enable_code_execution=True)
}
def create_group_chat(self, agents: List[autogen.Agent], chat_name: str,
max_round: int = 10) -> GroupChat:
"""Create group chat with specified agents"""
group_chat = GroupChat(
agents=agents,
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, topic: str, max_rounds: int = 8) -> str:
"""Run a comprehensive research project"""
team = self.create_research_team()
agents_list = [team["researcher"]The team["analyst"]The team["writer"]The team["executor"]]
group_chat = self.create_group_chat(agents_list, "research_chat", max_rounds)
Manager = GroupChatManager
groupchat=group_chat,
llm_config=self.llm_config
)
Initial_message is f"""
Research Project: {topic}
Please follow this flowchart to collaborate on a research report that is comprehensive.
1. Researcher: Gather information and key insights about {topic}
2. DataAnalyst : Create visualizations and analyze any quantitative aspect if necessary.
3. Writer: Prepare a final report that is well structured based on your research and analysis
4. CodeExecutor : Run any code required for analysis or visualisation
Final deliverables should include a professionally written research report that:
- Executive Summary
- Highlights and key findings
Analyse data (if applicable).
Conclusions and recommendations
Start your research now.
"""
chat_result = team["executor"].initiate_chat(
manager,
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 business analysis project"""
team = self.create_business_team()
agents_list = [team["strategist"]The team["financial_analyst"],
The team at["market_researcher"]The team["executor"]]
group_chat = self.create_group_chat(agents_list, "business_chat", max_rounds)
Manager = GroupChatManager
groupchat=group_chat,
llm_config=self.llm_config_pro
)
Initial_message is f"""
Business Analysis Project: {business_problem}
You can work together to develop a comprehensive analysis of your business using this method:
1. BusinessStrategists: Develop a strategic framework and analyze the problem.
2. FinancialAnalyst - Assess financial consequences and create financial models
3. MarketResearcher is a tool for researching market context, competitive landscape and other aspects.
4. BusinessExecutor, coordinate and compile recommendations
Deliverables for the final product should include:
Root causes and analysis of problems
- Strategic recommendations
- Economic impact assessment
- Analyse of the market opportunity
- Roadmap for implementation
Start the analysis immediately.
"""
chat_result = Team["executor"].initiate_chat(
manager,
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 development project"""
team = self.create_development_team()
agents_list = [team["developer"]The team["devops"]The team["qa_engineer"]The team["executor"]]
group_chat = self.create_group_chat(agents_list, "dev_chat", max_rounds)
Manager = GroupChatManager
groupchat=group_chat,
llm_config=self.llm_config
)
Initial_message is f"""
Development Project: {project_description}
Please work with us to develop a software solution that is complete.
1. Senior Developer: Write core code and design architecture
2. Plan infrastructure and deployment with DevOps Engineer
3. Quality assurance and design tests: QAEngineer
4. DevExecutor : execute code and coordinate the implementation
Deliverables will include:
- Design and architecture of the system
Implementation of the Working Code
Configuration for deployment
Test cases and Quality Assurance Plan
Documentation
Start development now.
"""
chat_result=team["executor"].initiate_chat(
manager,
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 final result from chat"""
If hasattr() ('chat_result', 'chat_history");
Messages = Chat_result.chat_history
else:
messages = chat_result
final_messages = []
For msg, see messages[-5:]:
If isinstance (msg and dict) are true, then msg contains a 'content.'
final_messages.append(f"{msg.get('name', 'Agent')}: {msg['content']}")
You can return to your original language by clicking here.Return "nn".join(final_messages)
def get_framework_stats(self) -> Dict[str, Any]:
"""Get framework statistics"""
return {
"agents": list(self.agents.keys()),
"group_chats": list(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()
}
Trending
- Collectively AI Discloses Immediate Leak After Coding Agent Uncovered Credential – Unite.AI
- Dragos Finds Immediate Leaks and Stolen Keys in AI Provide Chains
- Lean and Mathlib Communities Certify Claude-Assisted Riemann Proof – Unite.AI
- AWS Routes HyperPod Inference Throughout Areas From One Endpoint – Unite.AI
- DailyAI Briefing: A Lean-checked Riemann proof, plus 4 extra
- Anthropic Shares Drop 8.5% in Second Session Throughout AI Selloff – Unite.AI
- OpenAI Ships GPT-Stay-1.1 for Voice Brokers, Cuts Idle Value to $0.02/Min
- Copywriting: The Full Information | Copyblogger

