gemini-agents
v1.0.4
Published
A flexible framework for building, customizing, and chaining AI agents using the Gemini API and other tools.
Readme
Gemini Agents
A powerful and flexible TypeScript library for building, customizing, and chaining AI agents powered by Google's Gemini API. This library allows you to create specialized agents for various tasks and chain them together for complex workflows.
Features
- 🤖 Create custom AI agents with specific instructions and capabilities
- ⛓️ Chain multiple agents together for complex workflows
- 🌐 Built-in web scraping capabilities
- 🔢 Mathematical calculations and analysis
- 🔍 Google search integration
- 🏗️ Extensible architecture for adding new agent types
- 📝 Rich history tracking for agent interactions
Installation
npm install gemini-agentsQuick Start
Basic Usage
Here's a simple example of creating an agent to scrape and summarize an article:
import { AgentBuilder } from 'gemini-agents';
async function summarizeArticle() {
// Initialize the builder with your API key
const builder = new AgentBuilder('YOUR_GEMINI_API_KEY');
// Create a web scraper agent
const scraperAgent = builder.createWebScraperAgent('scraper');
// Create a custom summarizer agent
const summarizerAgent = builder.createBasicAgent(
'summarizer',
'You are an expert at summarizing articles. Create a concise summary highlighting the main points.'
);
// Create and execute the chain
const chain = builder.createChain(['scraper', 'summarizer']);
try {
const results = await chain.execute('https://example.com/article');
console.log('Article Summary:', results[results.length - 1].output);
} catch (error) {
console.error('Error:', error);
}
}Advanced Example: Tax Analysis System
Here's a more complex example that demonstrates how to create a system for analyzing tax information:
import { AgentBuilder } from 'gemini-agents';
async function analyzeTaxInfo() {
// Initialize builder with necessary API keys
const builder = new AgentBuilder(
'YOUR_GEMINI_API_KEY',
'YOUR_GOOGLE_API_KEY',
'YOUR_SEARCH_ENGINE_ID'
);
// Create specialized agents
const webScraper = builder.createWebScraperAgent('scraper');
const taxAnalyzer = builder.createBasicAgent(
'analyzer',
`You are a tax analysis expert. Extract specific information about PAYE (Pay As You Earn)
from the content. Focus on tax brackets, rates, and calculation methods.`
);
const calculator = builder.createCalculatorAgent('calculator');
const supervisor = builder.createBasicAgent(
'supervisor',
`You are a senior tax consultant responsible for verifying tax calculations and explanations.
Verify the information matches the initial query and provide a clear, professional summary.
If any discrepancies are found, highlight them and provide corrections.`
);
// Create the processing chain
const chain = builder.createChain(['scraper', 'analyzer', 'calculator', 'supervisor']);
try {
// Execute the chain with initial input
const results = await chain.execute(
'https://example.com/content'
);
// Calculate PAYE for specific salary
const salary = 1000000; // RWF
const calculationResults = await calculator.processInput(
`Calculate PAYE tax for monthly salary of ${salary} RWF using Rwanda's tax brackets`
);
// Final verification by supervisor
const finalReport = await supervisor.processInput(
`Verify this tax calculation and analysis:\n${calculationResults}`
);
console.log('Final Analysis:', finalReport);
} catch (error) {
console.error('Error in tax analysis:', error);
}
}Custom Agent Example: Content Quality Analyzer
Here's an example of creating a specialized agent for analyzing content quality:
import { AgentBuilder } from 'gemini-agents';
async function analyzeContentQuality() {
const builder = new AgentBuilder('YOUR_GEMINI_API_KEY');
// Create a specialized content quality analyzer
const qualityAnalyzer = builder.createBasicAgent(
'quality-analyzer',
`You are an expert content analyst. Evaluate content based on:
1. Readability (Flesch-Kincaid score)
2. Technical accuracy
3. Structure and organization
4. Engagement potential
5. SEO optimization
Provide specific recommendations for improvement.`
);
const webScraper = builder.createWebScraperAgent('scraper');
// Chain the agents
const chain = builder.createChain(['scraper', 'quality-analyzer']);
try {
const results = await chain.execute('https://example.com/content');
console.log('Content Analysis:', results[results.length - 1].output);
} catch (error) {
console.error('Analysis Error:', error);
}
}API Reference
AgentBuilder
Main class for creating and managing agents.
class AgentBuilder {
constructor(
geminiApiKey: string,
googleApiKey?: string,
searchEngineId?: string
);
// Create various types of agents
createBasicAgent(agentId: string, instructions: string): GeminiAgent;
createSearchAgent(agentId: string): SearchAgent;
createCalculatorAgent(agentId: string): CalculatorAgent;
createWebScraperAgent(agentId: string): WebScraperAgent;
// Chain management
createChain(agentIds: string[]): AgentChain;
getAgent(agentId: string): BaseAgent | undefined;
listAgents(): string[];
}AgentChain
Manages the execution flow between multiple agents.
class AgentChain {
addAgent(agent: BaseAgent): this;
async execute(initialInput: string): Promise<ChainResult[]>;
}Best Practices
Agent Design
- Give each agent clear, specific instructions
- Use the supervisor pattern for complex workflows
- Keep agent chains focused on specific tasks
Error Handling
- Always wrap chain execution in try-catch blocks
- Implement proper error handling for API calls
- Validate inputs before processing
Performance
- Minimize chain length when possible
- Use caching for frequently accessed data
- Implement rate limiting for API calls
Contributing
Contributions are welcome! Please read our contributing guidelines for details on our code of conduct and the process for submitting pull requests.
License
This project is licensed under the MIT License.
Creator
@Robertishimwe ([email protected])
