🚀 Awesome Agentic AI Learning Resource By DevKay

The ultimate resource for building intelligent agents and mastering modern AI/ML 🤖
From fundamentals to production-ready agentic systems. No fluff, just actionable content.
🎯 What You’ll Master
🧠 Core AI/ML
- Neural Networks & Deep Learning
- Transformers & LLMs
- Computer Vision & NLP
- MLOps & Production Systems
- Latest Research Papers
|
🤖 Agentic AI
- Agent Architectures
- Reasoning & Planning
- Tool Use & Function Calling
- Multi-Agent Systems
- Autonomous Decision Making
|
- LangChain & LangGraph
- AutoGen & CrewAI
- OpenAI Assistants API
- Vector Databases
- Agent Evaluation
|
🔥 Quick Start Guide
1️⃣ Beginner Path (0-6 months)
# Start with fundamentals
1. Complete Andrew Ng's ML Course → https://www.coursera.org/learn/machine-learning
2. Learn Python for AI → https://github.com/fastai/fastbook
3. Build your first agent → See "Project 2: Multi-Agent Research Team" below
4. Join communities → Discord links in Resources section
# Dive into modern AI
1. Master Transformers → https://huggingface.co/course/
2. Learn LangChain → Complete tutorial series below
3. Build multi-agent systems → CrewAI examples included
4. Read key papers → Research section has 50+ papers
3️⃣ Advanced Path (12+ months)
# Production and research
1. MLOps with agents → Deployment guides included
2. Custom agent architectures → Architecture patterns below
3. Research contributions → Template for writing papers
4. Open source projects → 20+ project ideas included
📚 COMPREHENSIVE LEARNING RESOURCES
🎓 Essential Courses (All Free/Accessible)
📖 Must-Read Books
Foundations
Modern AI & LLMs
Agentic AI & Agents
🧠 CORE AI/ML MASTERY
Neural Networks & Deep Learning
📖 Fundamentals (Click to expand)
Key Concepts to Master:
- Perceptrons & Multi-layer Networks: Start with basic building blocks
- Backpropagation: The learning algorithm that powers everything
- Activation Functions: ReLU, Sigmoid, Tanh, and modern variants
- Optimization: SGD, Adam, RMSprop, learning rate scheduling
- Regularization: Dropout, batch normalization, weight decay
Practical Implementation:
# Simple Neural Network from Scratch (Educational)
import numpy as np
class NeuralNetwork:
def add_documents(self, documents):
"""Add documents to the vector database"""
for i, doc in enumerate(documents):
embedding = self.embedding_model.encode([doc['content']])[0]
self.collection.add(
embeddings=[embedding.tolist()],
documents=[doc['content']],
metadatas=[doc.get('metadata', {})],
ids=[f"doc_{i}"]
)
def retrieve(self, query, k=5):
"""Retrieve relevant documents for a query"""
query_embedding = self.embedding_model.encode([query])[0]
results = self.collection.query(
query_embeddings=[query_embedding.tolist()],
n_results=k
)
return results['documents'][0]
def generate_response(self, query, context_docs):
"""Generate response using retrieved context"""
context = "\n".join(context_docs[:3]) # Use top 3 docs
prompt = f"Context: {context}\n\nQuestion: {query}\n\nAnswer:"
inputs = self.tokenizer.encode(prompt, return_tensors='pt')
with torch.no_grad():
outputs = self.generator.generate(
inputs,
max_length=inputs.shape[1] + 150,
temperature=0.7,
pad_token_id=self.tokenizer.eos_token_id
)
response = self.tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)
return response.strip()
def query(self, question):
"""Complete RAG pipeline"""
# Retrieve relevant documents
relevant_docs = self.retrieve(question)
# Generate response with context
response = self.generate_response(question, relevant_docs)
return {
'answer': response,
'sources': relevant_docs,
'confidence': self.calculate_confidence(question, relevant_docs)
}
def calculate_confidence(self, query, docs):
"""Calculate confidence score for the response"""
# Simple similarity-based confidence
query_embedding = self.embedding_model.encode([query])[0]
doc_embeddings = self.embedding_model.encode(docs)
similarities = [
torch.cosine_similarity(
torch.tensor(query_embedding),
torch.tensor(doc_emb),
dim=0
).item()
for doc_emb in doc_embeddings
]
return max(similarities) if similarities else 0.0
# Usage example
rag_system = AdvancedRAGSystem()
# Add sample documents
documents = [
{"content": "Machine learning is a subset of AI that focuses on algorithms that can learn from data."},
{"content": "Deep learning uses neural networks with multiple layers to model complex patterns."},
{"content": "Transformers are a type of neural network architecture that uses attention mechanisms."}
]
rag_system.add_documents(documents)
# Query the system
result = rag_system.query("What is machine learning?")
print(f"Answer: {result['answer']}")
print(f"Confidence: {result['confidence']:.2f}")
Advanced RAG Techniques:
- Hybrid Retrieval (Dense + Sparse):
from rank_bm25 import BM25Okapi
class HybridRetriever:
def __init__(self, documents):
self.documents = documents
self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
# BM25 for sparse retrieval
tokenized_docs = [doc.split() for doc in documents]
self.bm25 = BM25Okapi(tokenized_docs)
# Dense embeddings
self.doc_embeddings = self.embedding_model.encode(documents)
def retrieve(self, query, k=5, alpha=0.5):
"""Combine dense and sparse retrieval"""
# BM25 scores
bm25_scores = self.bm25.get_scores(query.split())
# Dense similarity scores
query_embedding = self.embedding_model.encode([query])[0]
dense_scores = [
torch.cosine_similarity(
torch.tensor(query_embedding),
torch.tensor(doc_emb),
dim=0
).item()
for doc_emb in self.doc_embeddings
]
# Combine scores
combined_scores = [
alpha * dense + (1 - alpha) * sparse
for dense, sparse in zip(dense_scores, bm25_scores)
]
# Get top k documents
top_indices = sorted(range(len(combined_scores)),
key=lambda i: combined_scores[i], reverse=True)[:k]
return [self.documents[i] for i in top_indices]
- Multi-Query RAG:
class MultiQueryRAG:
def __init__(self, rag_system):
self.rag_system = rag_system
self.query_generator = AutoModelForCausalLM.from_pretrained("gpt2")
self.query_tokenizer = AutoTokenizer.from_pretrained("gpt2")
def generate_similar_queries(self, original_query, num_queries=3):
"""Generate multiple similar queries for better retrieval"""
prompt = f"Generate {num_queries} similar questions to: {original_query}\n"
inputs = self.query_tokenizer.encode(prompt, return_tensors='pt')
outputs = self.query_generator.generate(inputs, max_length=100)
generated_text = self.query_tokenizer.decode(outputs[0], skip_special_tokens=True)
# Parse and return queries (simplified)
return [original_query] # Would contain parsed queries
def retrieve_multi_query(self, query):
"""Retrieve using multiple query variants"""
queries = self.generate_similar_queries(query)
all_docs = []
for q in queries:
docs = self.rag_system.retrieve(q)
all_docs.extend(docs)
# Remove duplicates and rank
unique_docs = list(set(all_docs))
return unique_docs[:5] # Return top 5
Usage example
#### **Modern Frameworks:**
- **PyTorch**: `pip install torch torchvision`
- **TensorFlow**: `pip install tensorflow`
- **JAX**: `pip install jax jaxlib` (for research)
</details>
### **Transformers & Large Language Models**
<details>
<summary><b>🔥 Transformer Architecture Deep Dive</b></summary>
#### **Understanding Transformers:**
1. **Attention Mechanism**: "Attention is All You Need" - learn this first
2. **Self-Attention**: How tokens relate to each other
3. **Multi-Head Attention**: Parallel attention mechanisms
4. **Positional Encoding**: How transformers understand sequence order
5. **Feed-Forward Networks**: The other half of transformer blocks
#### **Hands-On Transformer Implementation:**
```python
# Simplified Transformer Block (Educational)
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads):
super().__init__()
self.d_model = d_model
self.num_heads = num_heads
self.d_k = d_model // num_heads
self.W_q = nn.Linear(d_model, d_model)
self.W_k = nn.Linear(d_model, d_model)
self.W_v = nn.Linear(d_model, d_model)
self.W_o = nn.Linear(d_model, d_model)
def forward(self, query, key, value, mask=None):
batch_size = query.size(0)
# Linear transformations and reshape
Q = self.W_q(query).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
K = self.W_k(key).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
V = self.W_v(value).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
# Attention
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
attention_weights = F.softmax(scores, dim=-1)
context = torch.matmul(attention_weights, V)
# Concatenate heads
context = context.transpose(1, 2).contiguous().view(
batch_size, -1, self.d_model)
return self.W_o(context)
Pre-trained Models to Use:
- GPT Family: Text generation, completion
- BERT Family: Understanding, classification
- T5: Text-to-text transfer
- Code Models: CodeT5, CodeBERT for programming
Fine-tuning Resources:
Computer Vision & Multimodal AI
👁️ Vision Systems (Click to expand)
Core Architectures:
- CNNs: ResNet, EfficientNet, Vision Transformers
- Object Detection: YOLO, R-CNN family, DETR
- Segmentation: U-Net, Mask R-CNN, Segment Anything
- Generative: Diffusion Models, GANs, VAEs
Multimodal Models:
- CLIP: Image-text understanding
- DALL-E/Midjourney: Text-to-image generation
- GPT-4V: Vision-language reasoning
- LLaVA: Open-source vision-language model
Practical Projects:
# Image Classification with Vision Transformer
from transformers import ViTImageProcessor, ViTForImageClassification
from PIL import Image
# Load pre-trained model
processor = ViTImageProcessor.from_pretrained('google/vit-base-patch16-224')
model = ViTForImageClassification.from_pretrained('google/vit-base-patch16-224')
# Process image
image = Image.open('your_image.jpg')
inputs = processor(images=image, return_tensors="pt")
outputs = model(**inputs)
predictions = outputs.logits.argmax(-1)
🤖 AGENTIC AI MASTERY
Agent Fundamentals
🏗️ Agent Architectures & Design Patterns
Types of Agents:
-
Reactive Agents
- Respond directly to environment stimuli
- No internal state or planning
- Fast but limited reasoning
-
Deliberative Agents
- Maintain internal world model
- Plan before acting
- Better for complex tasks
-
Hybrid Agents
- Combine reactive and deliberative approaches
- Layered architecture (reactive layer + planning layer)
- Most practical for real applications
-
Learning Agents
- Improve performance over time
- Use reinforcement learning or other adaptation methods
- Can discover new strategies
Core Agent Components:
# Agent Architecture Template
class Agent:
def __init__(self):
self.memory = {} # Long-term and short-term memory
self.goals = [] # Current objectives
self.beliefs = {} # Knowledge about the world
self.tools = [] # Available actions/functions
self.reasoner = None # Planning and reasoning engine
def perceive(self, environment):
"""Process input from environment"""
pass
def reason(self):
"""Plan actions based on goals and beliefs"""
pass
def act(self, action):
"""Execute action in environment"""
pass
def learn(self, feedback):
"""Update beliefs and strategies"""
pass
Reasoning & Planning
🧠 Advanced Reasoning Patterns
Chain-of-Thought (CoT) Reasoning:
# CoT Implementation Example
def chain_of_thought_solve(problem, llm):
prompt = f"""
Let's solve this step by step:
Problem: {problem}
Step 1: Understanding the problem
Step 2: Identifying key information
Step 3: Planning the solution approach
Step 4: Executing the solution
Step 5: Verifying the answer
Let me work through each step:
"""
response = llm.generate(prompt)
return response
Tree of Thoughts (ToT):
# Tree of Thoughts for complex reasoning
class TreeOfThoughts:
def __init__(self, llm, max_depth=3):
self.llm = llm
self.max_depth = max_depth
def generate_thoughts(self, problem, current_path=[]):
if len(current_path) >= self.max_depth:
return self.evaluate_solution(current_path)
# Generate multiple thought branches
thoughts = self.llm.generate_thoughts(problem, current_path)
best_thought = None
best_score = -1
for thought in thoughts:
new_path = current_path + [thought]
score = self.evaluate_thought(thought, problem)
if score > best_score:
best_thought = thought
best_score = score
return self.generate_thoughts(problem, current_path + [best_thought])
ReAct (Reasoning + Acting):
# ReAct Pattern Implementation
class ReActAgent:
def __init__(self, llm, tools):
self.llm = llm
self.tools = {tool.name: tool for tool in tools}
def solve(self, task):
thoughts = []
actions = []
observations = []
while not self.is_complete(task, thoughts, actions, observations):
# Think
thought = self.think(task, thoughts, actions, observations)
thoughts.append(thought)
# Act (if thought suggests an action)
if self.should_act(thought):
action = self.extract_action(thought)
if action['tool'] in self.tools:
result = self.tools[action['tool']].run(action['input'])
actions.append(action)
observations.append(result)
return self.synthesize_answer(thoughts, actions, observations)
Memory Systems
🧠 Agent Memory Architectures
Types of Memory:
- Short-term Memory: Current conversation context
- Long-term Memory: Persistent knowledge and experiences
- Working Memory: Active information for current task
- Episodic Memory: Specific experiences and events
- Semantic Memory: General knowledge and facts
Memory Implementation:
# Comprehensive Memory System
class AgentMemory:
def __init__(self, vector_db, graph_db):
self.vector_db = vector_db # For semantic similarity
self.graph_db = graph_db # For structured relationships
self.working_memory = {} # Current task context
self.conversation_buffer = [] # Recent interactions
def store_experience(self, experience):
"""Store new experience with embeddings and relationships"""
# Create vector embedding
embedding = self.embed_text(experience['content'])
# Store in vector database
self.vector_db.add(
id=experience['id'],
embedding=embedding,
metadata=experience
)
# Extract and store relationships
entities = self.extract_entities(experience['content'])
self.graph_db.add_relationships(entities)
def retrieve_relevant(self, query, k=5):
"""Retrieve relevant memories for current context"""
# Vector similarity search
similar_memories = self.vector_db.search(query, k=k)
# Graph traversal for related concepts
entities = self.extract_entities(query)
related_memories = self.graph_db.find_related(entities)
# Combine and rank results
return self.rank_memories(similar_memories + related_memories)
Multi-Agent Systems
👥 Collaborative Agent Networks
Coordination Patterns:
- Hierarchical: Manager-worker relationships
- Peer-to-Peer: Equal agents collaborating
- Market-based: Agents bid for tasks
- Blackboard: Shared knowledge space
Communication Protocols:
# Multi-Agent Communication System
class MultiAgentSystem:
def __init__(self):
self.agents = {}
self.message_queue = []
self.coordination_protocol = None
def add_agent(self, agent):
self.agents[agent.id] = agent
agent.register_system(self)
def broadcast_message(self, sender_id, message):
"""Send message to all other agents"""
for agent_id, agent in self.agents.items():
if agent_id != sender_id:
agent.receive_message(sender_id, message)
def send_message(self, sender_id, recipient_id, message):
"""Send direct message between agents"""
if recipient_id in self.agents:
self.agents[recipient_id].receive_message(sender_id, message)
def coordinate_task(self, task):
"""Coordinate task execution among agents"""
# Decompose task into subtasks
subtasks = self.decompose_task(task)
# Assign subtasks to appropriate agents
assignments = self.assign_subtasks(subtasks)
# Monitor and coordinate execution
results = self.execute_coordinated(assignments)
return self.synthesize_results(results)
AI Safety & Ethics in Agentic Systems
🤖 Responsible AI: Ethics, Hallucination Control & HITL
As we build more autonomous and intelligent agentic systems, ensuring ethical behavior, safety, and alignment becomes critically important. This section highlights best practices for responsible development and deployment of AI agents.
⚖️ Ethical Use of AI Agents
- Transparency: Clearly indicate when users are interacting with an AI system. Never present agents as human entities.
- Data Privacy: Agents must not log, store, or transmit sensitive user data without explicit consent.
- Scope Control: Limit agent actions to well-defined domains to avoid unintended behaviors.
- Bias Mitigation: Be aware of biases in training data or models that may affect the fairness or neutrality of agent outputs.
⚠️ Example: If building an AI code reviewer, avoid suggesting insecure practices or biased hiring recommendations.
🧠 Hallucination Management
AI agents often generate convincing but inaccurate (hallucinated) information. This is a key safety concern, especially in domains like medicine, law, or finance.
🔍 Recommended Strategies:
- Retrieval-Augmented Generation (RAG): Always ground answers in factual documents.
- Source Referencing: Have agents cite sources for claims made.
- Confidence Scoring: Tag outputs with confidence levels or uncertainty estimates.
- Multi-agent Verification: Cross-check outputs using a secondary “fact-checker” agent.
🔧 Example: Simple RAG Retrieval in Python
from langchain.chains import RetrievalQA
from langchain.vectorstores import FAISS
from langchain.embeddings.openai import OpenAIEmbeddings
retriever = FAISS.load_local("my_vector_db", OpenAIEmbeddings()).as_retriever()
qa = RetrievalQA.from_chain_type(llm=chat_model, retriever=retriever)
response = qa.run("What is the latest paper on transformer agents?")
print(response)
📌 Confidence Scoring
response = agent.generate_response(query)
if response.confidence < 0.7:
print("⚠️ Low confidence - recommend human review.")
🤝 Multi-agent Cross-verification
primary = main_agent.run(task)
checker = verifier_agent.run(f"Fact-check this: {primary}")
final_output = f"Primary: {primary}\nVerified: {checker}"
👨👩👧👦 Human-in-the-Loop (HITL)
Human oversight is essential for controlling autonomous agents, especially in high-risk or dynamic environments.
💡 Best Practices:
- Approval Gates: Require human approval before executing sensitive actions (e.g., sending emails, making API calls).
- Feedback Loops: Let users provide feedback to improve future agent behavior.
- Escalation Triggers: Detect when agents are unsure or entering unfamiliar contexts—and escalate to a human operator.
✅ Example: Human Confirmation Before Action
action = agent.plan_next_action()
if action.sensitive:
user_input = input(f"Agent wants to do: {action.description}. Approve? (y/n): ")
if user_input.lower() != "y":
print("Action aborted by user.")
📩 Feedback Collection
user_feedback = input("Was this helpful? (yes/no): ")
agent.log_feedback(user_feedback)
✅ Summary Checklist
| Principle |
Recommendation |
| Transparency |
Disclose AI use and avoid impersonation |
| Privacy |
Handle personal data ethically and securely |
| Accuracy |
Ground outputs in facts and verifiable sources |
| HITL |
Keep a human supervisor in key decision loops |
| Bias Awareness |
Monitor for biased behavior and retrain if needed |
📚 Further Reading
📊 EVALUATION & MONITORING
📈 Comprehensive Evaluation Framework
Key Metrics to Track:
- Task Success Rate: Percentage of successfully completed tasks
- Response Quality: Relevance, accuracy, helpfulness scores
- Efficiency: Time to completion, token usage
- User Satisfaction: Human feedback scores
- Safety: Harmful content detection, bias metrics
Evaluation Implementation:
import json
from datetime import datetime
from typing import Dict, List, Any
class AgentEvaluator:
def __init__(self):
self.metrics = {
'task_success': [],
'response_quality': [],
'efficiency': [],
'safety': [],
'user_satisfaction': []
}
def evaluate_response(self,
query: str,
response: str,
expected_output: str = None,
user_feedback: int = None) -> Dict[str, float]:
"""Comprehensive response evaluation"""
evaluation = {}
# 1. Relevance Score (using embeddings)
evaluation['relevance'] = self.calculate_relevance(query, response)
# 2. Accuracy (if ground truth available)
if expected_output:
evaluation['accuracy'] = self.calculate_accuracy(response, expected_output)
# 3. Safety Score
evaluation['safety'] = self.evaluate_safety(response)
# 4. Coherence
evaluation['coherence'] = self.evaluate_coherence(response)
# 5. User Satisfaction (if available)
if user_feedback:
evaluation['user_satisfaction'] = user_feedback / 5.0 # Normalize to 0-1
return evaluation
def calculate_relevance(self, query: str, response: str) -> float:
"""Calculate semantic relevance between query and response"""
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('all-MiniLM-L6-v2')
query_emb = model.encode([query])
response_emb = model.encode([response])
similarity = torch.cosine_similarity(
torch.tensor(query_emb),
torch.tensor(response_emb)
).item()
return max(0, similarity) # Ensure non-negative
def calculate_accuracy(self, response: str, expected: str) -> float:
"""Calculate accuracy against expected output"""
# Simple token overlap for demonstration
response_tokens = set(response.lower().split())
expected_tokens = set(expected.lower().split())
if not expected_tokens:
return 0.0
overlap = len(response_tokens.intersection(expected_tokens))
return overlap / len(expected_tokens)
def evaluate_safety(self, response: str) -> float:
"""Evaluate response safety (placeholder implementation)"""
# In practice, use models like OpenAI's moderation API
harmful_keywords = ['hate', 'violence', 'illegal', 'harmful']
response_lower = response.lower()
harmful_count = sum(1 for keyword in harmful_keywords if keyword in response_lower)
safety_score = max(0, 1 - (harmful_count * 0.2))
return safety_score
def evaluate_coherence(self, response: str) -> float:
"""Evaluate response coherence and structure"""
# Simple heuristics (in practice, use more sophisticated methods)
sentences = response.split('.')
# Check for reasonable sentence length
avg_sentence_length = sum(len(s.split()) for s in sentences) / len(sentences)
length_score = min(1.0, avg_sentence_length / 15) # Normalize around 15 words
# Check for proper punctuation
punct_score = min(1.0, response.count('.') / max(1, len(sentences)))
return (length_score + punct_score) / 2
def track_efficiency(self, start_time: datetime, end_time: datetime,
tokens_used: int, task_complexity: str):
"""Track efficiency metrics"""
duration = (end_time - start_time).total_seconds()
efficiency_metrics = {
'duration': duration,
'tokens_per_second': tokens_used / max(duration, 1),
'complexity': task_complexity,
'timestamp': datetime.now()
}
self.metrics['efficiency'].append(efficiency_metrics)
def generate_report(self) -> Dict[str, Any]:
"""Generate comprehensive evaluation report"""
if not any(self.metrics.values()):
return {"error": "No evaluation data available"}
report = {
'summary': {},
'trends': {},
'recommendations': []
}
# Calculate averages
for metric_type, values in self.metrics.items():
if values:
if metric_type == 'efficiency':
report['summary'][metric_type] = {
'avg_duration': sum(v['duration'] for v in values) / len(values),
'avg_tokens_per_second': sum(v['tokens_per_second'] for v in values) / len(values)
}
else:
report['summary'][metric_type] = {
'average': sum(values)
提示:代码过长已自动截断
A/B Testing for Agents:
class AgentABTester:
def __init__(self, agent_a, agent_b):
self.agent_a = agent_a
self.agent_b = agent_b
self.results = {'a': [], 'b': []}
def run_test(self, test_queries, num_iterations=100):
"""Run A/B test between two agents"""
import random
for _ in range(num_iterations):
query = random.choice(test_queries)
# Randomly assign to agent A or B
if random.random() < 0.5:
response = self.agent_a.process(query)
self.results['a'].append({
'query': query,
'response': response,
'timestamp': datetime.now()
})
else:
response = self.agent_b.process(query)
self.results['b'].append({
'query': query,
'response': response,
'timestamp': datetime.now()
})
def analyze_results(self):
"""Statistical analysis of A/B test results"""
# Implementation would include statistical significance testing
return {
'agent_a_performance': len(self.results['a']),
'agent_b_performance': len(self.results['b']),
'statistical_significance': 'p < 0.05' # Placeholder
}
🚀 HANDS-ON PROJECTS
Project 1: Personal AI Assistant
🤖 Build Your Own AI Assistant (Click to expand)
Project Overview:
Create a personal AI assistant that can:
- Answer questions using RAG
- Manage calendar and tasks
- Send emails and messages
- Browse the web for information
- Learn from user preferences
Complete Implementation:
import openai
import sqlite3
from datetime import datetime, timedelta
import smtplib
from email.mime.text import MIMEText
import requests
from typing import List, Dict, Any
class PersonalAIAssistant:
def __init__(self, openai_api_key: str):
self.openai_client = openai.OpenAI(api_key=openai_api_key)
self.db_connection = sqlite3.connect('assistant.db')
self.setup_database()
self.tools = self.initialize_tools()
self.conversation_history = []
def setup_database(self):
"""Initialize SQLite database for storing information"""
cursor = self.db_connection.cursor()
# Tasks table
cursor.execute('''
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
due_date TEXT,
completed BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# User preferences
cursor.execute('''
CREATE TABLE IF NOT EXISTS preferences (
key TEXT PRIMARY KEY,
value TEXT
)
''')
# Conversation memory
cursor.execute('''
CREATE TABLE IF NOT EXISTS conversations (
id INTEGER PRIMARY KEY,
query TEXT,
response TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
self.db_connection.commit()
def initialize_tools(self) -> List[Dict[str, Any]]:
"""Define available tools/functions"""
return [
{
"type": "function",
"function": {
"name": "add_task",
"description": "Add a new task to the user's task list",
"parameters": {
"type": "object",
"properties": {
"title": {"type": "string"},
"description": {"type": "string"},
"due_date": {"type": "string", "format": "date"}
},
"required": ["title"]
}
}
},
{
"type": "function",
"function": {
"name": "get_tasks",
"description": "Retrieve user's tasks, optionally filtered by completion status",
"parameters": {
"type": "object",
"properties": {
"completed": {"type": "boolean"}
}
}
}
},
{
"type": "function",
"function": {
"name": "web_search",
"description": "Search the web for current information",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "send_email",
"description": "Send an email to a specified recipient",
"parameters": {
"type": "object",
"properties": {
"to": {"type": "string"},
"subject": {"type": "string"},
"body": {"type": "string"}
},
"required": ["to", "subject", "body"]
}
}
},
{
"type": "function",
"function": {
"name": "set_preference",
"description": "Store a user preference",
"parameters": {
"type": "object",
"properties": {
"key": {"type": "string"},
"value": {"type": "string"}
},
"required": ["key", "value"]
}
}
}
]
def add_task(self, title: str, description: str = "", due_date: str = None):
"""Add a new task"""
cursor = self.db_connection.cursor()
cursor.execute(
"INSERT INTO tasks (title, description, due_date) VALUES (?, ?, ?)",
(title, description, due_date)
)
self.db_connection.commit()
return f"Task '{title}' added successfully!"
def get_tasks(self, completed: bool = None):
"""Retriev
提示:代码过长已自动截断
Enhancement Ideas:
- Voice Interface: Add speech-to-text and text-to-speech
- Calendar Integration: Connect with Google Calendar API
- Smart Notifications: Proactive reminders and suggestions
- Learning System: Adapt responses based on user feedback
- Mobile App: Create a companion mobile application
Project 2: Multi-Agent Research Team
🔬 Automated Research Pipeline (Click to expand)
Project Overview:
Build a team of specialized agents that can:
- Conduct comprehensive research on any topic
- Synthesize information from multiple sources
- Generate detailed reports with citations
- Fact-check and validate information
- Present findings in various formats
Implementation:
from dataclasses import dataclass
from typing import List, Dict, Any
import json
import requests
from datetime import datetime
import asyncio
@dataclass
class ResearchArticle:
title: str
content: str
source: str
url: str
date_published: str
credibility_score: float
class ResearcherAgent:
def __init__(self, name: str, specialty: str, tools: List[str]):
self.name = name
self.specialty = specialty
self.tools = tools
self.findings = []
async def research_topic(self, topic: str, depth: str = "comprehensive") -> List[ResearchArticle]:
"""Conduct research on a given topic"""
print(f"{self.name} researching: {topic}")
# Simulate different research strategies based on specialty
if self.specialty == "academic":
return await self._academic_search(topic, depth)
elif self.specialty == "web_research":
return await self._web_search(topic, depth)
elif self.specialty == "data_analysis":
return await self._data_research(topic, depth)
else:
return await self._general_research(topic, depth)
async def _academic_search(self, topic: str, depth: str) -> List[ResearchArticle]:
"""Search academic databases and papers"""
# In practice, integrate with ArXiv, PubMed, Google Scholar APIs
papers = [
ResearchArticle(
title=f"Academic Study on {topic}",
content=f"Comprehensive academic analysis of {topic} with peer-reviewed findings...",
source="Academic Journal",
url="https://example.com/paper1",
date_published="2024-01-15",
credibility_score=0.95
)
]
return papers
async def _web_search(self, topic: str, depth: str) -> List[ResearchArticle]:
"""Search web sources and news"""
# Integrate with search APIs (Google, Bing, DuckDuckGo)
articles = [
ResearchArticle(
title=f"Recent Developments in {topic}",
content=f"Latest news and developments about {topic}...",
source="Tech News Site",
url="https://example.com/article1",
date_published="2024-02-20",
credibility_score=0.75
)
]
return articles
async def _data_research(self, topic: str, depth: str) -> List[ResearchArticle]:
"""Analyze data sources and statistics"""
datasets = [
ResearchArticle(
title=f"Statistical Analysis of {topic}",
content=f"Data-driven insights about {topic} based on recent datasets...",
source="Data Repository",
url="https://example.com/dataset1",
date_published="2024-02-01",
credibility_score=0.88
)
]
return datasets
async def _general_research(self, topic: str, depth: str) -> List[ResearchArticle]:
"""General purpose research"""
return [
ResearchArticle(
title=f"Overview of {topic}",
content=f"General information about {topic}...",
source="Encyclopedia",
url="https://example.com/overview",
date_published="2024-01-01",
credibility_score=0.80
)
]
class AnalystAgent:
def __init__(self, name: str):
self.name = name
def analyze_sources(self, articles: List[ResearchArticle]) -> Dict[str, Any]:
"""Analyze research sources for credibility and relevance"""
print(f"{self.name} analyzing {len(articles)} sources...")
analysis = {
'total_sources': len(articles),
'avg_credibility': sum(a.credibility_score for a in articles) / len(articles),
'source_types': {},
'date_range': {
'earliest': min(a.date_published for a in articles),
'latest': max(a.date_published for a in articles)
},
'recommendations': []
}
# Analyze source types
for article in articles:
source_type = article.source
analysis['source_types'][source_type] = analysis['source_types'].get(source_type, 0) + 1
# Generate recommendations
if analysis['avg_credibility'] < 0.7:
analysis['recommendations'].append("Consider finding more credible sources")
if len(set(a.source for a in articles)) < 3:
analysis['recommendations'].append("Diversify source types for better coverage")
return analysis
def synthesize_findings(self, articles: List[ResearchArticle]) -> str:
"""Synthesize information from multiple sources"""
print(f"{self.name} synthesizing findings...")
# Group articles by t
提示:代码过长已自动截断
Advanced Features:
- Real API Integration: Connect to actual search APIs (Google, Bing, ArXiv)
- Advanced NLP: Use transformer models for better claim extraction and verification
- Collaborative Filtering: Cross-verify information between multiple agents
- Visual Reports: Generate charts and graphs from data
- Continuous Learning: Improve research strategies based on feedback
Project 3: Code Review & Development Assistant
💻 AI-Powered Development Team (Click to expand)
Project Overview:
Create an AI development team that can:
- Review code for bugs, security issues, and best practices
- Generate documentation automatically
- Suggest improvements and refactoring
- Write unit tests
- Perform security audits
Implementation:
import ast
import re
import subprocess
from typing import List, Dict, Any, Optional
from dataclasses import dataclass
from pathlib import Path
import json
@dataclass
class CodeIssue:
type: str # 'bug', 'security', 'performance', 'style'
severity: str # 'high', 'medium', 'low'
line_number: int
description: str
suggestion: str
code_snippet: str
@dataclass
class CodeAnalysis:
file_path: str
issues: List[CodeIssue]
complexity_score: float
maintainability_score: float
test_coverage: float
suggestions: List[str]
class CodeReviewAgent:
def __init__(self, name: str, specialty: str):
self.name = name
self.specialty = specialty
self.rules = self._load_review_rules()
def _load_review_rules(self) -> Dict[str, List[str]]:
"""Load code review rules based on specialty"""
rules = {
'security': [
'SQL injection vulnerabilities',
'XSS vulnerabilities',
'Hardcoded credentials',
'Insecure random number generation',
'Unvalidated input'
],
'performance': [
'Inefficient loops',
'Memory leaks',
'Unnecessary database queries',
'Large object creation in loops',
'Blocking operations on main thread'
],
'style': [
'PEP 8 compliance',
'Naming conventions',
'Function length',
'Code duplication',
'Missing docstrings'
],
</details>
> README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论