class ColabGeminiAgentSystem:
def __init__(self, api_key):
"""Initialize the Colab-optimized Gemini agent system"""
self.api_key = api_key
self.setup_gemini()
self.setup_tools()
self.setup_agents()
self.results_history = []
Def setup_gemini (self)
"""Configure Gemini API for Colab"""
try:
genai.configure(api_key=self.api_key)
model = genai.GenerativeModel('gemini-1.5-flash')
response = model.generate_content("Hello, this is a test.")
print("✅ Gemini API connection successful!")
self.llm = ChatGoogleGenerativeAI(
model="gemini-1.5-flash",
google_api_key=self.api_key,
temperature=0.7,
convert_system_message_to_human=True
)
Although Exception is e:
print(f"❌ Gemini API setup failed: {str(e)}")
raise
Def Setup_tools (self).
"""Initialize available tools"""
Self.file_tool = FILEREADTOOL()
print("🛠️ Tools initialized successfully!")
Def setup_agents (self)
"""Create specialized agents optimized for Colab"""
self.researcher = Agent(
role="Senior Research Analyst",
goal="Conduct comprehensive research and provide detailed insights",
backstory=""You are a highly experienced research analyst.
You are excellent at collecting, analysing, and synthesizing the information. You are good at identifying.
Three key patterns and trends are identified, as well as actionable insight.""",
llm=self.llm,
tools=[self.file_tool],
verbose=True,
allow_delegation=False,
max_iter=2,
memory=True
)
self.data_analyst = Agent(
role="Data Analysis Expert",
goal="Analyze information and provide statistical insights",
backstory="""You're a highly skilled data analyst, who is excellent at interpreting
Finding patterns in complex data and creating actionable information
Recommendations based upon data-driven insights.""",
llm=self.llm,
tools=[self.file_tool],
verbose=True,
allow_delegation=False,
max_iter=2,
memory=True
)
self.content_creator = Agent(
role="Content Strategy Expert",
goal="Transform research into engaging, accessible content",
backstory="""You're a content strategist with a flair for creativity.
Transforming research and analysis from complex to clear and engaging
Content that is relevant to target audiences.""",
llm=self.llm,
tools=[self.file_tool],
verbose=True,
allow_delegation=False,
max_iter=2,
memory=True
)
self.qa_agent = Agent(
role="Quality Assurance Specialist",
goal="Ensure high-quality, accurate, and coherent deliverables",
backstory=""You are an expert in quality control who is meticulous.
Deliverables are subject to high standards in terms of clarity, accuracy and coherence.""",
llm=self.llm,
tools=[self.file_tool],
verbose=True,
allow_delegation=False,
max_iter=1,
memory=True
)
print("🤖 All agents initialized successfully!")
def create_colab_tasks(self, topic, task_type="comprehensive"):
"""Create optimized tasks for Colab environment"""
if task_type== "comprehensive":
return self._create_comprehensive_tasks(topic)
If task_type is equal to "" then the following will be displayed: "quick":
return self._create_quick_tasks(topic)
If task_type is equal to "" then the following will be displayed: "analysis":
return self._create_analysis_tasks(topic)
else:
return self._create_comprehensive_tasks(topic)
def _create_comprehensive_tasks(self, topic):
"""Create comprehensive research tasks"""
research_task = Task(
description=f"""
Research the topic: {topic}
Include in your analysis:
1. Definitions and key concepts
2. The latest trends and development
3. The main challenges and opportunities
4. Perspectives and implications for the future
Then, format your answer in clear bulleted sections.
""",
agent=self.researcher,
expected_output="Structured research report with clear sections and key insights"
)
analysis_task = Task(
description=f"""
Analyze the research findings for: {topic}
Provide:
1. The key insights and patterns
2. Statistic observations
3. Comparison of two analyses
4. Recommendations for Action
5. Risk assessment
Analyze your results and communicate them in an easy-to-understand format.
""",
agent=self.data_analyst,
expected_output="Analytical report with insights and recommendations",
context=[research_task]
)
content_task = Task(
description=f"""
Create engaging content about: {topic}
Based on your research and analysis create:
1. Summary (1-2 paragraphs).
2. The key takeaways (5 to 7 bullet points).
3. Recommendations for Action
4. Future Implications
It should be accessible to a wide audience.
""",
agent=self.content_creator,
expected_output="Engaging, well-structured content for general audience",
context=[research_task, analysis_task]
)
qa_task = Task(
description=f"""
Review and improve all content for: {topic}
Ensure:
1. Precision and consistency
2. Structure and flow should be clear.
3. The completeness of the information
4. The ability to read and engage.
Please provide the polished final version.
""",
agent=self.qa_agent,
expected_output="Final polished content with quality improvements",
context=[research_task, analysis_task, content_task]
)
Return to the Homepage [research_task, analysis_task, content_task, qa_task]
def _create_quick_tasks(self, topic):
"""Create quick analysis tasks for faster execution"""
quick_research = Task(
description=f"""
Provide a quick but thorough analysis of: {topic}
Include:
1. Summary and main points
2. The benefits of the program and its challenges
3. Status and Trends
4. Quick Tips
Be concise, but informative.
""",
agent=self.researcher,
expected_output="Concise analysis with key insights"
)
quick_content = Task(
description=f"""
Create a summary report for: {topic}
Format:
1. The Executive Summary
2. Findings (3-5 Points)
3. Recommendations (5 to 7 points).
4. The next steps
Take action and make it clear.
""",
agent=self.content_creator,
expected_output="Clear summary report with actionable insights",
context=[quick_research]
)
Return to the Homepage [quick_research, quick_content]
def _create_analysis_tasks(self, topic):
"""Create analysis-focused tasks"""
deep_analysis = Task(
description=f"""
Perform deep analysis of: {topic}
Concentrate on:
1. Examining key components in detail
2. Analysis of pros and cons
3. Comparative evaluation
4. Strategic implications
5. Data-driven Conclusions
Give thorough insights into the analysis.
""",
agent=self.data_analyst,
expected_output="Deep analytical report with detailed insights"
)
Return to the Homepage [deep_analysis]
def execute_colab_project(self, topic, task_type="comprehensive", save_results=True):
"""Execute project optimized for Colab"""
print(f"n🚀 Starting Colab AI Agent Project")
print(f"📋 Topic: {topic}")
print(f"🔧 Task Type: {task_type}")
print("=" * 60)
start_time = time.time()
try:
tasks = self.create_colab_tasks(topic, task_type)
If task_type is equal to "quick":
Agents = [self.researcher, self.content_creator]
Task_type == "analysis":
Agents = [self.data_analyst]
else:
Agents = [self.researcher, self.data_analyst, self.content_creator, self.qa_agent]
"Crew" = crew (
agents=agents,
tasks=tasks,
process=Process.sequential,
verbose=1,
memory=True,
max_rpm=20
)
result = crew.kickoff()
execution_time = time.time() - start_time
print(f"n✅ Project completed in {execution_time:.2f} seconds!")
print("=" * 60)
If you want to save results, then:
self._save_results(topic, task_type, result, execution_time)
Return to result
Except Exception As e.
print(f"n❌ Project execution failed: {str(e)}")
print("💡 Try using 'quick' task type for faster execution")
Return None
def _save_results(self, topic, task_type, result, execution_time):
"""Save results to history"""
result_entry = {
'timestamp': datetime.now().isoformat(),
'topic': topic,
'task_type': task_type,
'execution_time': execution_time,
'result': str(result)
}
self.results_history.append(result_entry)
try:
with open('colab_agent_results.json', 'w') as f:
json.dump(self.results_history, f, indent=2)
print("💾 Results saved to colab_agent_results.json")
Except Exception As e.
print(f"⚠️ Could not save results: {e}")
def show_results_history(self):
"""Display results history"""
if not self.results_history:
print("📭 No results history available")
Return to the Homepage
print("n📊 Results History:")
print("=" * 50)
for i, entry in enumerate(self.results_history, 1):
print(f"n{i}. Topic: {entry['topic']}")
print(f" Task Type: {entry['task_type']}")
print(f" Execution Time: {entry['execution_time']:.2f}s")
print(f" Timestamp: {entry['timestamp']}")
print("-" * 30)
def create_custom_agent(self, role, goal, backstory, max_iter=2):
"""Create a custom agent"""
Return Agent
role=role,
goal=goal,
backstory=backstory,
llm=self.llm,
tools=[self.file_tool],
verbose=True,
allow_delegation=False,
max_iter=max_iter,
memory=True
)
We architect the heart of the workflow: a ColabGeminiAgentSystem class that wires Gemini into LangChain, defines a file-reading tool, and spawns four specialized agents, research, data, content, and QA, each ready to collaborate on tasks.
print("🔧 Initializing Colab AI Agent System...")
try:
agent_system = ColabGeminiAgentSystem(GEMINI_API_KEY)
print("✅ System ready for use!")
The e-word is used to indicate that the exception does not apply.
print(f"❌ System initialization failed: {e}")
print("Please check your API key and try again.")
Our framework has officially been activated. We initialize the agent with the API key and watch for the success message.
def run_quick_examples():
"""Run quick examples to demonstrate the system"""
print("n🎯 Quick Start Examples")
print("=" * 40)
print("n1. Quick Analysis Example:")
topic1 = "Machine Learning in Business"
result1 = agent_system.execute_colab_project(topic1, task_type="quick")
If result1:
print(f"n📋 Quick Analysis Result:")
print(result1)
print("n2. Deep Analysis Example:")
topic2 = "Sustainable Energy Solutions"
result2 = agent_system.execute_colab_project(topic2, task_type="analysis")
If you want to know more about the result2, click here.
print(f"n📋 Deep Analysis Result:")
print(result2)
Trending
- xAI Releases Standalone Grok Speech to text and Text to speech APIs, Aimed at Enterprise Voice Developers
- Anthropic releases Claude Opus 4.7, a major upgrade for agentic coding, high-resolution vision, and long-horizon autonomous tasks
- The Coding Guide to Property Based Testing with Hypothesis and Stateful, Differential and Metamorphic Test Designs
- Schematik Is ‘Cursor for Hardware.’ The Anthropics Want In
- Hacking the EU’s new age-verification app takes only 2 minutes
- Google AI Releases Google Auto-Diagnosis: A Large Language Model LLM Based System to Diagnose Integrity Test Failures At Scale
- This is a complete guide to running OpenAI’s GPT-OSS open-weight models using advanced inference workflows.
- The Huey Code Guide: Build a High-Performance Background Task Processor Using Scheduling with Retries and Pipelines.

