Gemini Code Assist Integration Guide
Executive Summary
This document provides guidance on using Gemini Code Assist to accelerate development on TotoAI Hub. Code Assist provides AI-powered code completion, generation, and explanation capabilities integrated directly into your IDE.
Status: 📚 Documentation & Best Practices Priority: Low (Developer Productivity Enhancement) Cost: Free tier available, paid tiers for advanced features Setup Time: 15-30 minutes
What is Gemini Code Assist?
Gemini Code Assist (formerly Duet AI) is Google Cloud's AI-powered coding assistant that provides:
- Code Completion: Context-aware suggestions as you type
- Code Generation: Generate entire functions, classes, or files from natural language
- Code Explanation: Understand complex code with AI-generated explanations
- Code Chat: Ask questions about your codebase
- Test Generation: Automatically generate unit tests
- Documentation: Generate docstrings and comments
- Code Review: Get AI suggestions for code improvements
- Debugging: Get help understanding and fixing errors
Powered by: Gemini 2.0 Pro (optimized for code)
Why Use Code Assist for TotoAI Hub?
Current Development Challenges
- Complex agent architecture with multiple services
- Large prompt system requiring careful maintenance
- TypeScript types across many files
- Firebase Firestore query patterns
- Google Generative AI SDK integration
- RAG and vector search implementations
How Code Assist Helps
| Task | Without Code Assist | With Code Assist | Time Saved |
|---|---|---|---|
| Write new agent method | 15-20 min | 5-8 min | ~60% |
| Generate unit tests | 20-30 min | 5-10 min | ~70% |
| Understand complex code | 10-15 min | 2-3 min | ~80% |
| Write prompt components | 10-15 min | 3-5 min | ~65% |
| Debug TypeScript errors | 5-10 min | 2-3 min | ~60% |
| Write Firestore queries | 8-12 min | 3-5 min | ~65% |
Average Productivity Gain: ~60-70%
Setup Instructions
Option 1: VS Code (Recommended)
-
Install Extension
# Install from VS Code Marketplace
code --install-extension GoogleCloudTools.cloudcode -
Sign in to Google Cloud
- Open VS Code
- Click "Cloud Code" in status bar
- Select "Sign In"
- Choose your Google account with GCP access
-
Configure Project
- Open Command Palette (Cmd/Ctrl + Shift + P)
- Type "Cloud Code: Select Project"
- Choose your TotoAI Hub GCP project
-
Enable Code Assist
- Settings → Extensions → Cloud Code
- Check "Enable Code Suggestions"
- Select "Gemini Code Assist" as provider
Option 2: JetBrains IDEs (WebStorm, IntelliJ)
-
Install Plugin
- Settings → Plugins
- Search "Cloud Code"
- Install and restart
-
Authenticate
- Tools → Cloud Code → Sign In
- Follow OAuth flow
-
Configure
- Settings → Tools → Cloud Code
- Enable "Gemini Code Assist"
Option 3: Cloud Shell Editor
Gemini Code Assist is automatically available in Cloud Shell Editor (no setup required).
Verify Installation
// Type this comment and wait for suggestion:
// Function to analyze a tweet and detect if it's a case update
// Code Assist should suggest a complete function implementation
Usage Guide for TotoAI Hub
1. Generate Agent Methods
Prompt:
// Generate a method for CaseAgent that checks if a case requires urgent attention
// based on medical keywords and funding status
Expected Output:
async checkUrgency(caseId: string): Promise<{
isUrgent: boolean;
reason: string;
recommendedActions: string[];
}> {
const caseData = await this.getCaseData(caseId);
// Check medical urgency keywords
const urgentKeywords = ['emergency', 'critical', 'urgent', 'immediate'];
const hasMedicalUrgency = urgentKeywords.some(keyword =>
caseData.description.toLowerCase().includes(keyword)
);
// Check funding status
const fundingProgress = caseData.fundsRaised / caseData.fundingGoal;
const hasLowFunding = fundingProgress < 0.3;
if (hasMedicalUrgency && hasLowFunding) {
return {
isUrgent: true,
reason: 'Critical medical case with low funding',
recommendedActions: [
'Notify guardians immediately',
'Create urgent donation campaign',
'Contact emergency veterinary services'
]
};
}
return { isUrgent: false, reason: 'Case status normal', recommendedActions: [] };
}
2. Generate Prompt Components
Prompt:
// Create a prompt component for detecting animal species in Instagram posts
Expected Output:
export const speciesDetectionGuidelines = `
🐾 SPECIES DETECTION GUIDELINES:
When analyzing posts about animals, identify:
1. **Primary Species**: Dog, cat, bird, rabbit, etc.
2. **Breed Information**: If mentioned or visually identifiable
3. **Species-Specific Needs**: Consider species-specific medical needs
4. **Multiple Animals**: Note if post involves multiple species
Always prioritize accuracy. If unsure about species, use "Unknown" rather than guessing.
Example:
- "Golden Retriever puppy" → Species: Dog, Breed: Golden Retriever
- "Orange tabby cat" → Species: Cat, Breed: Domestic Shorthair
- "Small animal" → Species: Unknown (insufficient information)
`;
3. Generate Unit Tests
Prompt:
// Generate comprehensive unit tests for SemanticCachingService
Expected Output:
import { SemanticCachingService } from '../SemanticCachingService';
describe('SemanticCachingService', () => {
let service: SemanticCachingService;
beforeEach(() => {
service = new SemanticCachingService();
});
afterEach(() => {
service.clear();
});
describe('get()', () => {
it('should return null for cache miss', async () => {
const result = await service.get('new query');
expect(result).toBeNull();
});
it('should return cached response for exact match', async () => {
await service.set('hello world', 'response 1');
const result = await service.get('hello world');
expect(result).toBe('response 1');
});
it('should return cached response for similar query', async () => {
await service.set('how to help rescue dogs', 'response 1');
const result = await service.get('ways to help rescue dogs');
expect(result).toBe('response 1');
});
it('should not return cached response for dissimilar query', async () => {
await service.set('dog rescue', 'response 1');
const result = await service.get('cat adoption');
expect(result).toBeNull();
});
});
describe('set()', () => {
it('should cache a query-response pair', async () => {
await service.set('test query', 'test response');
const result = await service.get('test query');
expect(result).toBe('test response');
});
it('should evict oldest entry when cache is full', async () => {
// Fill cache to max size
for (let i = 0; i < 1001; i++) {
await service.set(`query ${i}`, `response ${i}`);
}
// First entry should be evicted
const result = await service.get('query 0');
expect(result).toBeNull();
});
});
describe('getStats()', () => {
it('should track cache hits and misses', async () => {
await service.set('query', 'response');
await service.get('query'); // hit
await service.get('unknown'); // miss
const stats = service.getStats();
expect(stats.hits).toBe(1);
expect(stats.misses).toBe(1);
expect(stats.hitRate).toBe(0.5);
});
});
});
4. Explain Complex Code
How to Use:
- Select code block
- Right-click → "Code Assist: Explain This"
- Read AI-generated explanation
Example - Explain VectorDBService's cosineSimilarity:
// Selected code:
private cosineSimilarity(a: number[], b: number[]): number {
const dotProduct = a.reduce((sum, val, i) => sum + val * b[i], 0);
const magnitudeA = Math.sqrt(a.reduce((sum, val) => sum + val * val, 0));
const magnitudeB = Math.sqrt(b.reduce((sum, val) => sum + val * val, 0));
return dotProduct / (magnitudeA * magnitudeB);
}
// AI Explanation:
/**
* This method calculates the cosine similarity between two embedding vectors.
*
* Cosine similarity measures the angle between two vectors in multi-dimensional
* space, producing a value between -1 (opposite) and 1 (identical).
*
* Steps:
* 1. Calculate dot product: sum of element-wise multiplication
* 2. Calculate magnitude of vector A: sqrt of sum of squares
* 3. Calculate magnitude of vector B: sqrt of sum of squares
* 4. Divide dot product by product of magnitudes
*
* In RAG systems, cosine similarity is preferred over Euclidean distance
* because it's invariant to vector magnitude - only direction matters.
*
* Example:
* A = [1, 2, 3], B = [2, 4, 6] // B is 2x A
* Similarity = 1.0 (perfectly similar, same direction)
*/
5. Generate Firestore Queries
Prompt:
// Generate a Firestore query to get all cases with urgency level "critical"
// that were created in the last 7 days, ordered by creation date
Expected Output:
async getCriticalRecentCases(days: number = 7): Promise<CaseData[]> {
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - days);
const casesRef = this.db.collection('cases');
const snapshot = await casesRef
.where('urgencyLevel', '==', 'critical')
.where('createdAt', '>=', cutoffDate)
.orderBy('createdAt', 'desc')
.get();
return snapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
} as CaseData));
}
6. Generate Documentation
Prompt:
// Generate comprehensive JSDoc for StreamingService.streamWithRetry
Expected Output:
/**
* Streams a response from Gemini with automatic retry on interruption.
*
* This method wraps `streamResponse()` with retry logic to handle transient
* failures such as network interruptions, rate limiting, or temporary API issues.
*
* @param prompt - The prompt to send to the AI model
* @param options - Streaming options including callbacks and generation config
* @param maxRetries - Maximum number of retry attempts (default: 2)
*
* @returns {Promise<StreamResult>} Result containing:
* - fullText: Complete generated text
* - chunks: Array of stream chunks received
* - duration: Total time in milliseconds
* - tokenCount: Estimated token count
* - interrupted: Whether stream was interrupted
*
* @throws {Error} If all retry attempts fail
*
* @example
* ```typescript
* const result = await streamingService.streamWithRetry(
* 'Explain quantum computing',
* {
* onChunk: (chunk) => console.log(chunk.text),
* temperature: 0.7
* },
* maxRetries: 3
* );
* console.log(`Generated ${result.tokenCount} tokens in ${result.duration}ms`);
* ```
*
* @remarks
* - Uses exponential backoff between retries (1s, 2s, 4s, ...)
* - Returns partial result if interrupted after max retries
* - Callbacks are invoked for each retry attempt
* - Analytics are updated even on retry
*
* @see streamResponse For single-attempt streaming
* @see streamWithFallback For streaming with non-streaming fallback
*/
async streamWithRetry(
prompt: string,
options: StreamOptions = {},
maxRetries: number = 2
): Promise<StreamResult> {
// Implementation...
}
Best Practices for TotoAI Hub
1. Use Descriptive Comments
❌ Bad:
// Process tweet
✅ Good:
// Analyze tweet content for case relevance, extract key information (animal type,
// medical condition, urgency level), and determine if it should create a new case
// or update an existing one based on duplicate detection
Better prompts → Better AI suggestions.
2. Leverage Context
Code Assist understands your entire file and related files. Reference existing patterns:
// Generate a method similar to TwitterAgent.analyzeTweet but for Instagram Stories
3. Iterate with AI
Workflow:
- Generate initial code with Code Assist
- Review and test
- Add comment: "Improve error handling and add logging"
- Accept enhanced suggestions
- Add comment: "Add TypeScript types and JSDoc"
- Accept final version
4. Use for Repetitive Tasks
Examples:
- Generate interfaces from JSON data
- Create CRUD methods for new Firestore collections
- Generate test fixtures and mock data
- Create similar methods with variations
5. Combine with Existing Code
// Generate a builder pattern similar to PromptBuilder but for constructing
// Firestore queries with method chaining and type safety
Code Assist will study PromptBuilder.ts and create a similar pattern.
Common Use Cases
Use Case 1: Add New Agent
Goal: Create a new FacebookAgent similar to TwitterAgent
Steps:
- Open
src/agents/TwitterAgent.ts - Create new file
src/agents/FacebookAgent.ts - Add comment:
// Create FacebookAgent class similar to TwitterAgent but optimized for
// Facebook posts and groups, using FacebookPost interface instead of Tweet - Code Assist generates entire agent structure
- Review and customize for Facebook-specific features
Time: ~10 minutes (vs ~30 minutes manual)
Use Case 2: Add New RAG Knowledge Category
Goal: Add "Training Resources" knowledge category
Steps:
- Open
src/services/RAGService.ts - Add comment:
// Add methods to manage "training" knowledge category including
// addTrainingResource, getTrainingRecommendations, and searchTraining - Accept generated methods
- Generate tests with:
// Generate unit tests for new training resource methods
Time: ~5 minutes (vs ~20 minutes manual)
Use Case 3: Refactor for Performance
Goal: Optimize VectorDBService.search() for large datasets
Steps:
- Select
search()method - Ask Code Assist: "How can I optimize this method for 1M+ documents?"
- Review suggestions (batch processing, caching, indexing)
- Ask: "Implement these optimizations with backward compatibility"
- Review and test generated code
Time: ~15 minutes (vs ~1 hour manual)
Use Case 4: Add Telemetry
Goal: Add OpenTelemetry tracing to all agents
Steps:
- Add comment at top of
CaseAgent.ts:// Add OpenTelemetry tracing to all public methods with span attributes
// for agent type, operation, and duration - Accept generated imports and tracer setup
- Let Code Assist add tracing to each method
- Repeat for other agents
Time: ~10 minutes per agent (vs ~30 minutes manual)
Limitations & Caveats
What Code Assist Does Well
✅ Boilerplate code generation ✅ TypeScript type definitions ✅ Unit test scaffolding ✅ Documentation and comments ✅ Code patterns and structure ✅ Firestore query syntax ✅ Google SDK usage
What Requires Human Review
⚠️ Business logic and requirements ⚠️ Security and authentication ⚠️ Complex algorithms ⚠️ Performance optimization decisions ⚠️ Prompt engineering specifics ⚠️ Cost/quota management ⚠️ Edge cases and error scenarios
Best Practices
- Always review generated code - Don't blindly accept
- Test thoroughly - AI can introduce subtle bugs
- Verify security - Check for hardcoded credentials, SQL injection, etc.
- Check types - Ensure TypeScript types are correct
- Validate logic - Ensure business rules are correctly implemented
- Review prompts - AI-generated prompts may need fine-tuning
Advanced Features
1. Chat with Your Codebase
How to Use:
- Open Code Assist Chat panel
- Ask questions like:
- "Where is case urgency calculated?"
- "How does duplicate detection work in TwitterAgent?"
- "What's the difference between RAGService and VectorDBService?"
Benefits:
- Faster onboarding for new developers
- Quick architecture understanding
- Find code across large codebase
2. Code Transformations
Examples:
- "Convert this class to use async/await instead of promises"
- "Refactor this code to use TypeScript generics"
- "Split this large method into smaller helper methods"
3. Migration Assistance
Example - ES5 to ES6:
// Select old code:
var self = this;
getData(function(err, data) {
if (err) {
return callback(err);
}
self.processData(data);
});
// Ask: "Convert to async/await"
// Result:
try {
const data = await getData();
await this.processData(data);
} catch (err) {
throw err;
}
4. Security Scanning
Ask Code Assist:
- "Are there any security issues in this code?"
- "Check for SQL injection vulnerabilities"
- "Review authentication logic for issues"
5. Performance Analysis
Ask Code Assist:
- "Is this code optimized for performance?"
- "Where are the performance bottlenecks?"
- "Suggest caching strategies"
Cost & Licensing
Free Tier (Individual)
- ✅ Code completion in IDE
- ✅ Basic code generation
- ✅ Code explanation
- ✅ 500 suggestions/month
- ❌ Chat with codebase
- ❌ Advanced features
Paid Tier (Team)
- ✅ Everything in Free tier
- ✅ Chat with entire codebase
- ✅ Unlimited suggestions
- ✅ Custom model fine-tuning
- ✅ Team collaboration features
- ✅ Priority support
- Cost: $19/user/month
Enterprise Tier
- ✅ Everything in Paid tier
- ✅ SLA and dedicated support
- ✅ Advanced security controls
- ✅ Audit logging
- ✅ Custom integrations
- Cost: Custom pricing
Recommendation for TotoAI Hub: Start with Free tier for individual developers, upgrade to Paid tier if productivity gains justify the cost (typical ROI: 5-10x).
Metrics & ROI
Productivity Metrics (Expected)
| Metric | Without Code Assist | With Code Assist | Improvement |
|---|---|---|---|
| New feature development | 2-3 days | 1-2 days | 40-50% faster |
| Bug fixing | 2-4 hours | 1-2 hours | 50% faster |
| Test writing | 30% of dev time | 15% of dev time | 50% reduction |
| Code review time | 1-2 hours | 30-60 min | 50% faster |
| Onboarding new developers | 2-3 weeks | 1-2 weeks | 40% faster |
ROI Calculation
Investment:
- Setup time: 2 hours (one-time)
- Learning curve: 4 hours (one-time)
- Monthly cost: $0-19/user
Returns (per developer):
- Time saved: ~8-10 hours/week
- Value: 8 hours × $50/hour × 4 weeks = $1,600/month
- Cost: $19/month
- ROI: ~8,300% 🚀
Even with just 2 hours/week savings, ROI is positive
Getting Started Checklist
Week 1: Setup & Familiarization
- Install Code Assist extension
- Authenticate with GCP
- Test with simple code completion
- Try generating a small function
- Use "Explain This" on existing code
- Review generated suggestions critically
Week 2: Productivity Boost
- Use for new agent method development
- Generate unit tests for new code
- Try chat feature to understand codebase
- Use for documentation generation
- Refactor old code with assistance
Week 3: Advanced Usage
- Use for complex features (RAG, Vector Search)
- Try code transformations
- Leverage for debugging
- Use for performance optimization
- Train team on best practices
Week 4: Measure & Optimize
- Track time savings
- Measure code quality (test coverage, bugs)
- Gather team feedback
- Adjust workflows based on learnings
- Document team best practices
Troubleshooting
Issue: No Suggestions Appearing
Causes:
- Code Assist not enabled
- Not authenticated
- File type not supported
- Suggestions disabled for file
Solutions:
- Check Settings → Extensions → Cloud Code
- Re-authenticate (Cloud Code: Sign In)
- Ensure file is
.ts,.js,.tsx - Check
.gitignoreand.cloudcodeignore
Issue: Poor Quality Suggestions
Causes:
- Unclear/vague comments
- Missing context
- Non-standard code patterns
Solutions:
- Write more detailed comments
- Ensure related files are open
- Follow TypeScript best practices
- Provide examples in comments
Issue: Slow Performance
Causes:
- Large project size
- Network latency
- High CPU usage
Solutions:
- Exclude
node_modules/from indexing - Check internet connection
- Close unused files/applications
Resources
Documentation
Videos
Support
Conclusion
Gemini Code Assist is a powerful productivity multiplier for TotoAI Hub development. By automating boilerplate code, generating tests, and explaining complex logic, it can save 8-10 hours per week per developer.
Key Takeaways:
- ✅ Easy setup (15-30 minutes)
- ✅ Significant time savings (40-70% on repetitive tasks)
- ✅ Excellent ROI even with free tier
- ✅ Best for: boilerplate, tests, docs, exploration
- ⚠️ Always review AI-generated code
- ⚠️ Not a replacement for human judgment
Recommendation: Adopt immediately for individual developers, evaluate team license after 30 days based on measured productivity gains.
Document Version: 1.0 Last Updated: 2025-11-06 Next Review: After 30 days of usage