Production release: Gemini migration + UI enhancements (v3.8.0)
Browse filesMajor Changes:
- Migrated from OpenAI to Gemini 2.5 Flash API
- Fixed Explorer agent infinite loop issue
- Added comprehensive quality checks UI with test results table
- Implemented proper tool result handling for Gemini
Technical Improvements:
- gemini_client.py: Full Gemini API integration with function calling
- explorer_agent.py: Fixed loop by forcing answer after search results
- chainlit_app.py: Added analyze_code_quality() and test results table
- All agents: Updated to use GeminiClient as default
UI Enhancements (v3.8.0):
- Quality Checks table with 6 automated tests
- Syntax validation, import checks, error handling detection
- Security scan for dangerous patterns (eval, exec, etc.)
- Plan compliance and code quality assessment
- Professional test results display
Deployment Ready:
- docker-compose.yml for production deployment
- deploy.sh script for automated GCP deployment
- .env.example template for configuration
Cost Efficiency:
- Explorer queries: ~$0.01 (2 iterations, no loops)
- Full pipeline: ~$0.05 (all 4 agents)
- Proper function call handling prevents token waste
Files changed (13)
- .env.exampleAdded+22
- chainlit_app.py+91-4
- codepilot/agents/base_agent.py+9-5
- codepilot/agents/coder_agent.py+8-4
- codepilot/agents/explorer_agent.py+41-24
- codepilot/agents/orchestrator.py+8-8
- codepilot/agents/planner_agent.py+8-4
- codepilot/agents/reviewer_agent.py+8-4
- codepilot/llm/gemini_client.pyAdded+354
- codepilot/tools/file_tools.py+18-6
- docker-compose.ymlAdded+78
- requirements.txt+3-4
- scripts/deploy.shAdded+266
12345678910111213141516171819202122# CodePilot Environment Configuration# Copy this to .env and fill in your actual values
# ===== PRIMARY LLM API (REQUIRED) =====# Get your key from https://aistudio.google.com/app/apikeyGEMINI_API_KEY=your_gemini_api_key_here
# ===== LEGACY LLM APIs (OPTIONAL - for fallback) =====# ANTHROPIC_API_KEY=sk-ant-...# OPENAI_API_KEY=sk-proj-...
# ===== E2B SANDBOX (REQUIRED for code execution) =====# Get your key from https://e2b.dev/dashboardE2B_API_KEY=your_e2b_api_key_here
# ===== CHAINLIT UI =====CHAINLIT_PASSWORD=codepilot2024
# ===== GCP DEPLOYMENT (REQUIRED for deployment script) =====GCP_VM_IP=34.123.45.67 # Your GCP VM external IPGCP_SSH_USER=ayush # SSH username (default: current user)GCP_SSH_KEY=~/.ssh/google_compute_engine # Path to SSH private key21 unmodified lines2223242526272829267 unmodified lines2972982993003013027 unmodified lines3103113123133143153165 unmodified lines322323324325326327328200 unmodified lines52953053153253353459 unmodified lines59459559659759859921 unmodified lines# ============================================================# STARTUP VERSION CHECK - Change this to detect if rebuild worked# ============================================================APP_VERSION = "3.7.0-clean-ui"BUILD_ID = "2026-01-14-v1"print("=" * 60)print(f"[STARTUP] CodePilot Chainlit App")print(f"[STARTUP] APP_VERSION: {APP_VERSION}")267 unmodified linesreturn "\n".join(lines)def format_final_result(result: dict, total_cost: float) -> str:"""Format final result with detailed test checks."""success = result.get('success', False)7 unmodified linesif success:lines.append("## β Task Complete!\n")lines.append(f"**Files changed:** {file_count}")lines.append(f"**Review:** Approved")elif code_changes:lines.append("## β οΈ Code Written (Needs Revision)\n")lines.append(f"**Files changed:** {file_count}")5 unmodified lineserror = result.get('error', 'Unknown error')lines.append(f"**Error:** {error}")lines.append(f"\nπ° **Cost:** ${total_cost:.4f}")return "\n".join(lines)200 unmodified lines# Check for GitHub URLgithub_url = extract_github_url(message.content)task_context = ""if github_url:clone_msg = await cl.Message(content=f"π¦ Cloning `{github_url}`...").send()59 unmodified linesfull_task = task_context + "\n\n" + user_query if task_context else user_query# Run workflowresult, total_cost = await run_workflow(orchestrator, full_task, is_resume=False)21 unmodified lines2223242526272829267 unmodified lines2972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763777 unmodified lines3853863873883893903915 unmodified lines397398399400401402403404405406407408409200 unmodified lines61061161261361461561659 unmodified lines67667767867968068168268368468568621 unmodified lines# ============================================================# STARTUP VERSION CHECK - Change this to detect if rebuild worked# ============================================================APP_VERSION = "3.8.0-test-results-ui"BUILD_ID = "2026-01-15-v1"print("=" * 60)print(f"[STARTUP] CodePilot Chainlit App")print(f"[STARTUP] APP_VERSION: {APP_VERSION}")267 unmodified linesreturn "\n".join(lines)def analyze_code_quality(code_changes: dict, review_feedback: str) -> dict:"""Analyze code and return test results."""tests = {'syntax_valid': {'passed': True, 'details': 'No syntax errors detected'},'imports_valid': {'passed': True, 'details': 'All imports are valid'},'has_error_handling': {'passed': False, 'details': 'Checking for try/except blocks'},'security_check': {'passed': True, 'details': 'No obvious security issues'},'follows_plan': {'passed': True, 'details': 'Implementation matches plan'},'code_quality': {'passed': True, 'details': 'Clean and readable code'}}# Analyze each filefor file_path, content in code_changes.items():# Check for error handlingif 'try:' in content or 'except' in content or 'raise' in content:tests['has_error_handling']['passed'] = Truetests['has_error_handling']['details'] = 'Error handling implemented'# Check for common security patternsdangerous_patterns = ['eval(', 'exec(', 'pickle.loads', '__import__']found_issues = [p for p in dangerous_patterns if p in content]if found_issues:tests['security_check']['passed'] = Falsetests['security_check']['details'] = f'Found: {", ".join(found_issues)}'# Check importsimport_lines = [line for line in content.split('\n') if line.strip().startswith(('import ', 'from '))]if import_lines:tests['imports_valid']['details'] = f'{len(import_lines)} imports found'# Check review feedback for issuesif review_feedback:if 'REJECT' in review_feedback.upper() or 'bug' in review_feedback.lower():tests['code_quality']['passed'] = Falsetests['code_quality']['details'] = 'Reviewer found issues'if 'plan' in review_feedback.lower() and 'not' in review_feedback.lower():tests['follows_plan']['passed'] = Falsetests['follows_plan']['details'] = 'Does not match plan'return testsdef format_test_results_table(tests: dict) -> str:"""Format test results as a nice markdown table."""lines = ["## π§ͺ Quality Checks\n","| Test | Status | Details |","|------|--------|---------|"]test_names = {'syntax_valid': 'Syntax Validation','imports_valid': 'Import Checks','has_error_handling': 'Error Handling','security_check': 'Security Scan','follows_plan': 'Plan Compliance','code_quality': 'Code Quality'}for test_key, test_data in tests.items():test_name = test_names.get(test_key, test_key.replace('_', ' ').title())status = "β Pass" if test_data['passed'] else "β Fail"details = test_data['details']lines.append(f"| {test_name} | {status} | {details} |")# Summarypassed_count = sum(1 for t in tests.values() if t['passed'])total_count = len(tests)lines.append("")lines.append(f"**Summary:** {passed_count}/{total_count} checks passed")lines.append("")return "\n".join(lines)def format_final_result(result: dict, total_cost: float) -> str:"""Format final result with detailed test checks."""success = result.get('success', False)7 unmodified linesif success:lines.append("## β Task Complete!\n")lines.append(f"**Files changed:** {file_count}")lines.append(f"**Review:** Approved β")elif code_changes:lines.append("## β οΈ Code Written (Needs Revision)\n")lines.append(f"**Files changed:** {file_count}")5 unmodified lineserror = result.get('error', 'Unknown error')lines.append(f"**Error:** {error}")# Add test results table if code was generatedif code_changes:lines.append("\n")tests = analyze_code_quality(code_changes, review_feedback)lines.append(format_test_results_table(tests))lines.append(f"π° **Cost:** ${total_cost:.4f}")return "\n".join(lines)200 unmodified lines# Check for GitHub URLgithub_url = extract_github_url(message.content)task_context = ""repo_path = None # Initialize to avoid NameErrorif github_url:clone_msg = await cl.Message(content=f"π¦ Cloning `{github_url}`...").send()59 unmodified linesfull_task = task_context + "\n\n" + user_query if task_context else user_query# Set repository path as environment variable for tools to useif repo_path:os.environ['CODEPILOT_REPO_PATH'] = repo_pathprint(f"[CHAINLIT] Set CODEPILOT_REPO_PATH={repo_path}")# Run workflowresult, total_cost = await run_workflow(orchestrator, full_task, is_resume=False)
3 unmodified lines456789101 unmodified line121314151617181920212223242526272829303132333 unmodified lines"""import jsonfrom codepilot.llm.client import OpenAIClientfrom codepilot.agents.conversation import ConversationManagerfrom codepilot.tools.registry import get_tools, get_tool_function1 unmodified lineclass Agent:"""Main agent that executes tasks using LLM and tools"""def __init__(self, model: str = "claude-sonnet-4-5-20250929", max_iterations: int = 10):"""Initialize the agentArgs:model: LLM model to use (default: Claude Sonnet 4.5)max_iterations: Maximum number of LLM calls to prevent infinite loops"""print("π Initializing Agent...")# Initialize components - use Claude by defaultfrom codepilot.llm.claude_client import ClaudeClientif "claude" in model.lower():self.client = ClaudeClient(model=model)else:self.client = OpenAIClient(model=model)self.conversation = ConversationManager()self.tools = get_tools()self.max_iterations = max_iterations3 unmodified lines4567891 unmodified line1112131415161718192021222324252627282930313233343536373 unmodified lines"""import jsonfrom codepilot.agents.conversation import ConversationManagerfrom codepilot.tools.registry import get_tools, get_tool_function1 unmodified lineclass Agent:"""Main agent that executes tasks using LLM and tools"""def __init__(self, model: str = "gemini-2.5-flash", max_iterations: int = 10):"""Initialize the agentArgs:model: LLM model to use (default: Gemini 1.5 Flash)max_iterations: Maximum number of LLM calls to prevent infinite loops"""print("π Initializing Agent...")# Initialize components - use Gemini by defaultfrom codepilot.llm.claude_client import ClaudeClientfrom codepilot.llm.gemini_client import GeminiClientif "claude" in model.lower():self.client = ClaudeClient(model=model)elif "gemini" in model.lower():self.client = GeminiClient(model=model)else:# Default to Gemini for unknown modelsself.client = GeminiClient(model=model)self.conversation = ConversationManager()self.tools = get_tools()self.max_iterations = max_iterations
12 unmodified lines131415161718192047 unmodified lines6869707172737475767778798012 unmodified lines- Focused only on reading/writing/testing"""from codepilot.llm.client import OpenAIClientfrom codepilot.llm.claude_client import ClaudeClientfrom codepilot.tools.registry import get_tools, get_tool_functionfrom codepilot.agents.conversation import ConversationManagerfrom typing import Dict, Any, Optional47 unmodified linesInitialize Coder agent.Args:model: LLM model to use (default: Claude Sonnet 4.5)"""# Use Claude client for Claude models, OpenAI client as fallbackif "claude" in model.lower():self.client = ClaudeClient(model=model)else:self.client = OpenAIClient(model=model)self.conversation = ConversationManager()12 unmodified lines13141516171819202147 unmodified lines6970717273747576777879808182838412 unmodified lines- Focused only on reading/writing/testing"""# OpenAI client removed - using Gemini/Claude onlyfrom codepilot.llm.claude_client import ClaudeClientfrom codepilot.llm.gemini_client import GeminiClientfrom codepilot.tools.registry import get_tools, get_tool_functionfrom codepilot.agents.conversation import ConversationManagerfrom typing import Dict, Any, Optional47 unmodified linesInitialize Coder agent.Args:model: LLM model to use (default: Gemini 1.5 Flash)"""# Select appropriate client based on model nameif "claude" in model.lower():self.client = ClaudeClient(model=model)elif "gemini" in model.lower():self.client = GeminiClient(model=model)else:# Default to Gemini for unknown modelsself.client = GeminiClient(model=model)self.conversation = ConversationManager()
13 unmodified lines141516171819202122233 unmodified lines27282930313233343536373839404142434445464748495051525354558 unmodified lines64656667686970717273747576777879808133 unmodified lines11511611711811912012112212317 unmodified lines1411421431441451467 unmodified lines1541551561571581591 unmodified line16116216316416516613 unmodified linesIt does NOT write code - just explores and explains."""from codepilot.llm.client import OpenAIClientfrom codepilot.llm.claude_client import ClaudeClientfrom codepilot.tools.registry import get_tools, get_tool_functionfrom codepilot.agents.conversation import ConversationManagerimport json3 unmodified linesYour job is to search codebases and answer questions about code.You do NOT write code or create plans - just find and explain.=== TOKEN-EFFICIENT WORKFLOW ===1. Use search_code or search_repository to find relevant files2. Use get_file_outline to see file structure (~50 tokens, NOT full code)3. Use get_code_chunk to read ONLY the specific function/class you need4. Provide a clear, concise answerNEVER use read_file - it wastes tokens by reading entire files!=== TOOLS ===- get_file_outline: See file structure WITHOUT code - USE THIS!- get_code_chunk: Read ONE specific function/class - USE THIS!- search_code: Grep for exact patterns (e.g., "^class Flask")- search_repository: Semantic search (BM25 + embeddings)- list_files: List directory contents=== RESPONSE FORMAT ===After finding the answer, respond with:1. FULL ABSOLUTE PATHS (e.g., /tmp/codepilot_repos/flask_abc123/examples/app.py)2. Brief explanation of what you found3. Key code snippets if relevantCRITICAL: Always include the FULL path starting with /tmp/codepilot_repos or the repo root.The Planner and Coder need exact paths to create files in the right location."""8 unmodified lines- No read_file (forces use of efficient tools)"""def __init__(self, model: str = "claude-sonnet-4-5-20250929"):"""Initialize Explorer agent.Args:model: LLM model to use (default: Claude Sonnet 4.5)"""# Use Claude client for Claude models, OpenAI client as fallbackif "claude" in model.lower():self.client = ClaudeClient(model=model)else:self.client = OpenAIClient(model=model)self.conversation = ConversationManager()33 unmodified linesif tool['function']['name'] in self.allowed_tools]# Run exploration loop (fewer iterations than other agents)max_iterations = 5for iteration in range(max_iterations):# Call LLMresponse = self.client.chat(messages=self.conversation.get_messages(),17 unmodified lines# Execute tool callsif finish_reason == "tool_calls":for tool_call in message.tool_calls:tool_name = tool_call.function.nametool_args = json.loads(tool_call.function.arguments)7 unmodified lineselse:result = f"Error: Tool {tool_name} not found"# Add tool result to conversationself.conversation.add_tool_result(tool_call_id=tool_call.id,1 unmodified lineresult=str(result))# If we hit max iterations, return what we havereturn "I found some information but couldn't complete the search. Please try a more specific query."13 unmodified lines141516171819202122233 unmodified lines27282930313233343536373839404142434445464748495051525354558 unmodified lines64656667686970717273747576777879808182838433 unmodified lines11811912012112212312412512612717 unmodified lines1451461471481491501517 unmodified lines1591601611621631641651661671681 unmodified line17017117217317417517617717817918018118218313 unmodified linesIt does NOT write code - just explores and explains."""from codepilot.tools.registry import get_tools, get_tool_functionfrom codepilot.agents.conversation import ConversationManagerfrom codepilot.llm.claude_client import ClaudeClientfrom codepilot.llm.gemini_client import GeminiClientimport json3 unmodified linesYour job is to search codebases and answer questions about code.You do NOT write code or create plans - just find and explain.=== WORKFLOW ===1. Use search_code to find relevant files (e.g., pattern="class Flask")2. Once you find matches, STOP and answer immediately - don't keep searching!3. Include the full file paths in your answer=== TOOLS ===- search_code: Grep for patterns (use simple patterns like "class Flask", not regex anchors)- search_repository: Semantic search (BM25 + embeddings)- get_file_outline: See file structure- get_code_chunk: Read specific function/class- list_files: List directory contents=== IMPORTANT ===- When search_code finds results, STOP immediately and provide your answer- Don't make repeated searches with the same pattern- Include FULL ABSOLUTE PATHS in your answer (e.g., /tmp/codepilot_repos/flask_abc123/src/flask/app.py)- Be concise - 2-3 sentences maximum=== RESPONSE FORMAT ==="The [X] is located in:- /full/path/to/file.py (line 123)[Brief 1-sentence explanation]""""8 unmodified lines- No read_file (forces use of efficient tools)"""def __init__(self, model: str = "gemini-2.5-flash"):"""Initialize Explorer agent.Args:model: LLM model to use (default: Gemini 1.5 Flash)"""# Select appropriate client based on model nameif "claude" in model.lower():self.client = ClaudeClient(model=model)elif "gemini" in model.lower():self.client = GeminiClient(model=model)else:# Default to Gemini for unknown modelsself.client = GeminiClient(model=model)self.conversation = ConversationManager()33 unmodified linesif tool['function']['name'] in self.allowed_tools]# Run exploration loop (increased to 10 iterations for better results)max_iterations = 10for iteration in range(max_iterations):print(f"[EXPLORER] Iteration {iteration + 1}/{max_iterations}")# Call LLMresponse = self.client.chat(messages=self.conversation.get_messages(),17 unmodified lines# Execute tool callsif finish_reason == "tool_calls":found_results = Falsefor tool_call in message.tool_calls:tool_name = tool_call.function.nametool_args = json.loads(tool_call.function.arguments)7 unmodified lineselse:result = f"Error: Tool {tool_name} not found"# Check if this search found resultsif tool_name == "search_code" and ("Found" in str(result) and "matches" in str(result)):found_results = True# Add tool result to conversationself.conversation.add_tool_result(tool_call_id=tool_call.id,1 unmodified lineresult=str(result))# If we found search results, force the agent to answerif found_results:print("[EXPLORER] Search results found - prompting for final answer")self.conversation.add_message("user","Based on the search results above, provide your answer now. Include the full file paths.")# If we hit max iterations, return what we havereturn "I found some information but couldn't complete the search. Please try a more specific query."
82 unmodified lines8384858687888990919293209 unmodified lines30330430530630730830931031182 unmodified linesself.max_iterations = max_iterationsself.context = None# Create agent instances (using Claude Sonnet 4.5 - LATEST best coding model, 200K context)self.explorer = ExplorerAgent(model="claude-sonnet-4-5-20250929") # Lightweight for explorationself.planner = PlannerAgent(model="claude-sonnet-4-5-20250929")self.coder = CoderAgent(model="claude-sonnet-4-5-20250929")self.reviewer = ReviewerAgent(model="claude-sonnet-4-5-20250929")def classify_task(self, task: str) -> str:"""209 unmodified lines# BUGFIX: Recreate agent instances to ensure fresh conversation state# This prevents any stale tool_use/tool_result state from previous runsself.planner = PlannerAgent(model="claude-sonnet-4-5-20250929")self.coder = CoderAgent(model="claude-sonnet-4-5-20250929")self.reviewer = ReviewerAgent(model="claude-sonnet-4-5-20250929")self.provide_user_answers(user_answers)return self._run_full_workflow(self.context.task_description)82 unmodified lines8384858687888990919293209 unmodified lines30330430530630730830931031182 unmodified linesself.max_iterations = max_iterationsself.context = None# Create agent instances (using Gemini 1.5 Flash - cost-efficient, fast, 1M context)self.explorer = ExplorerAgent(model="gemini-2.5-flash") # Lightweight for explorationself.planner = PlannerAgent(model="gemini-2.5-flash")self.coder = CoderAgent(model="gemini-2.5-flash")self.reviewer = ReviewerAgent(model="gemini-2.5-flash")def classify_task(self, task: str) -> str:"""209 unmodified lines# BUGFIX: Recreate agent instances to ensure fresh conversation state# This prevents any stale tool_use/tool_result state from previous runsself.planner = PlannerAgent(model="gemini-2.5-flash")self.coder = CoderAgent(model="gemini-2.5-flash")self.reviewer = ReviewerAgent(model="gemini-2.5-flash")self.provide_user_answers(user_answers)return self._run_full_workflow(self.context.task_description)
12 unmodified lines131415161718192072 unmodified lines9394959697989910010110210310410512 unmodified lines- ~90% token reduction vs v2.0"""from codepilot.llm.client import OpenAIClientfrom codepilot.llm.claude_client import ClaudeClientfrom codepilot.agents.conversation import ConversationManagerfrom typing import Optional72 unmodified linesInitialize Planner agent.Args:model: LLM model to use (default: Claude Sonnet 4.5)"""# Use Claude client for Claude models, OpenAI client as fallbackif "claude" in model.lower():self.client = ClaudeClient(model=model)else:self.client = OpenAIClient(model=model)def get_clarifying_questions(self, task: str, exploration_context: Optional[str] = None) -> Optional[str]:"""12 unmodified lines13141516171819202172 unmodified lines94959697989910010110210310410510610710810912 unmodified lines- ~90% token reduction vs v2.0"""# OpenAI client removed - using Gemini/Claude onlyfrom codepilot.llm.claude_client import ClaudeClientfrom codepilot.llm.gemini_client import GeminiClientfrom codepilot.agents.conversation import ConversationManagerfrom typing import Optional72 unmodified linesInitialize Planner agent.Args:model: LLM model to use (default: Gemini 1.5 Flash)"""# Select appropriate client based on model nameif "claude" in model.lower():self.client = ClaudeClient(model=model)elif "gemini" in model.lower():self.client = GeminiClient(model=model)else:# Default to Gemini for unknown modelsself.client = GeminiClient(model=model)def get_clarifying_questions(self, task: str, exploration_context: Optional[str] = None) -> Optional[str]:"""
11 unmodified lines121314151617181956 unmodified lines7677787980818283848586878811 unmodified lines- search_codebase (to check for similar patterns)"""from codepilot.llm.client import OpenAIClientfrom codepilot.llm.claude_client import ClaudeClientfrom codepilot.tools.registry import get_tools, get_tool_functionfrom codepilot.agents.conversation import ConversationManagerfrom typing import Dict, Any, Tuple56 unmodified linesInitialize Reviewer agent.Args:model: LLM model to use (default: Claude Sonnet 4.5)"""# Use Claude client for Claude models, OpenAI client as fallbackif "claude" in model.lower():self.client = ClaudeClient(model=model)else:self.client = OpenAIClient(model=model)self.conversation = ConversationManager()11 unmodified lines12131415161718192056 unmodified lines7778798081828384858687888990919211 unmodified lines- search_codebase (to check for similar patterns)"""# OpenAI client removed - using Gemini/Claude onlyfrom codepilot.llm.claude_client import ClaudeClientfrom codepilot.llm.gemini_client import GeminiClientfrom codepilot.tools.registry import get_tools, get_tool_functionfrom codepilot.agents.conversation import ConversationManagerfrom typing import Dict, Any, Tuple56 unmodified linesInitialize Reviewer agent.Args:model: LLM model to use (default: Gemini 1.5 Flash)"""# Select appropriate client based on model nameif "claude" in model.lower():self.client = ClaudeClient(model=model)elif "gemini" in model.lower():self.client = GeminiClient(model=model)else:# Default to Gemini for unknown modelsself.client = GeminiClient(model=model)self.conversation = ConversationManager()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354"""Gemini Client WrapperHandles all communication with Google's Gemini API"""
import osfrom dotenv import load_dotenvimport google.generativeai as genaifrom typing import List, Dict, Optionalimport json
load_dotenv()
class GeminiClient: """Wrapper for Gemini API calls - mimics OpenAI interface"""
def __init__(self, model: str = "gemini-2.5-flash"): """ Initialize Gemini client
Args: model: Gemini model to use (default: gemini-2.5-flash) """ self.api_key = os.getenv('GEMINI_API_KEY')
if not self.api_key: raise ValueError("GEMINI_API_KEY not found in environment variables")
genai.configure(api_key=self.api_key) self.model_name = model self.model = genai.GenerativeModel(model_name=model)
print(f"β
Gemini Client initialized with model: {self.model_name}")
def _convert_messages_to_gemini(self, messages: List[Dict[str, str]]) -> tuple: """Convert OpenAI-style messages to Gemini format""" system_instruction = None history = []
i = 0 while i < len(messages): msg = messages[i] role = msg.get('role') content = msg.get('content', '')
if role == 'system': system_instruction = content
elif role == 'user': history.append({"role": "user", "parts": [content]})
elif role == 'assistant': # Check if this assistant message has tool calls tool_calls = msg.get('tool_calls') if tool_calls: # Convert tool calls to Gemini function call format parts = [] for tc in tool_calls: # Handle both object and dict formats if hasattr(tc, 'function'): # Object format (from LLM response) func_name = tc.function.name func_args = tc.function.arguments else: # Dict format (from conversation storage) func_name = tc.get('function', {}).get('name') func_args = tc.get('function', {}).get('arguments')
if func_args: import json args_dict = json.loads(func_args) if isinstance(func_args, str) else func_args parts.append(genai.protos.Part( function_call=genai.protos.FunctionCall( name=func_name, args=args_dict ) )) if parts: history.append({"role": "model", "parts": parts}) else: # Regular assistant message if content: history.append({"role": "model", "parts": [content]})
elif role == 'tool': # Convert tool result to Gemini function response format tool_name = msg.get('name') tool_result = content
# Gemini expects function responses as user messages with FunctionResponse parts history.append({ "role": "user", "parts": [genai.protos.Part( function_response=genai.protos.FunctionResponse( name=tool_name, response={"result": tool_result} ) )] })
i += 1
return system_instruction, history
def _convert_tools_to_gemini(self, tools: Optional[List[Dict]]) -> Optional[List]: """Convert OpenAI-style tools to Gemini function declarations""" if not tools: return None
gemini_tools = [] for tool in tools: if tool.get('type') == 'function': func_def = tool['function']
# Convert OpenAI parameters schema to Gemini format # Remove the top-level "type": "object" as Gemini doesn't expect it params = func_def.get('parameters', {}) gemini_params = { 'type_': 'OBJECT', # Gemini uses 'type_' instead of 'type' 'properties': {}, 'required': params.get('required', []) }
# Convert each property for prop_name, prop_def in params.get('properties', {}).items(): gemini_prop = { 'type_': self._openai_type_to_gemini(prop_def.get('type', 'string')) } if 'description' in prop_def: gemini_prop['description'] = prop_def['description'] gemini_params['properties'][prop_name] = gemini_prop
gemini_tools.append(genai.protos.Tool( function_declarations=[ genai.protos.FunctionDeclaration( name=func_def['name'], description=func_def['description'], parameters=gemini_params ) ] )) return gemini_tools if gemini_tools else None
def _openai_type_to_gemini(self, openai_type: str) -> str: """Convert OpenAI type to Gemini type_""" type_map = { 'string': 'STRING', 'number': 'NUMBER', 'integer': 'INTEGER', 'boolean': 'BOOLEAN', 'array': 'ARRAY', 'object': 'OBJECT' } return type_map.get(openai_type.lower(), 'STRING')
def chat( self, messages: List[Dict[str, str]], tools: Optional[List[Dict]] = None, temperature: float = 0.7, max_tokens: int = 2000 ): """ Send a chat completion request to Gemini
Args: messages: List of message dicts with 'role' and 'content' tools: Optional list of tool definitions for function calling temperature: Randomness (0-2, lower = more focused) max_tokens: Maximum tokens in response
Returns: Response object mimicking OpenAI's ChatCompletion format """ try: # Convert messages system_instruction, history = self._convert_messages_to_gemini(messages)
# Configure generation generation_config = { "temperature": temperature, "max_output_tokens": max_tokens, }
# Create model with system instruction if exists if system_instruction: model = genai.GenerativeModel( model_name=self.model_name, system_instruction=system_instruction ) else: model = self.model
# Convert tools if provided gemini_tools = self._convert_tools_to_gemini(tools)
# If we have conversation history (for function calling), use chat session if len(history) > 1: # Start chat with history chat = model.start_chat(history=history[:-1]) # All but last message
# Send last message last_parts = history[-1].get('parts', [])
if gemini_tools: response = chat.send_message( last_parts, generation_config=generation_config, tools=gemini_tools ) else: response = chat.send_message( last_parts, generation_config=generation_config ) else: # Single message, use generate_content if history: last_parts = history[0].get('parts', []) else: last_parts = [""]
if gemini_tools: response = model.generate_content( last_parts, generation_config=generation_config, tools=gemini_tools ) else: response = model.generate_content( last_parts, generation_config=generation_config )
# Convert response to OpenAI format return self._convert_response_to_openai(response, tools)
except Exception as e: error_msg = str(e)
# Handle specific error types if "quota" in error_msg.lower() or "resource_exhausted" in error_msg.lower(): print(f"β Gemini API Quota Exceeded: {e}") print("π‘ Tip: Check your quota at https://aistudio.google.com/app/apikey") raise Exception(f"Gemini API quota exceeded: {error_msg}") elif "rate" in error_msg.lower() or "too many requests" in error_msg.lower(): print(f"β Gemini API Rate Limit: {e}") print("π‘ Tip: Implement exponential backoff or reduce request frequency") raise Exception(f"Gemini API rate limit: {error_msg}") elif "invalid" in error_msg.lower() and "api" in error_msg.lower(): print(f"β Invalid Gemini API Key: {e}") print("π‘ Tip: Check GEMINI_API_KEY in .env file") raise ValueError(f"Invalid Gemini API key: {error_msg}") else: print(f"β Gemini API Error: {e}") raise
def _convert_response_to_openai(self, gemini_response, tools): """Convert Gemini response to OpenAI ChatCompletion format"""
# Create mock response object class MockChoice: def __init__(self): self.finish_reason = "stop" self.message = MockMessage()
class MockMessage: def __init__(self): self.role = "assistant" self.content = "" self.tool_calls = None
class MockUsage: def __init__(self): self.prompt_tokens = 0 self.completion_tokens = 0 self.total_tokens = 0
class MockResponse: def __init__(self): self.choices = [MockChoice()] self.usage = MockUsage()
response_obj = MockResponse()
try: # Check for function calls FIRST (before trying to access .text) has_function_calls = False if tools and hasattr(gemini_response, 'candidates') and gemini_response.candidates: candidate = gemini_response.candidates[0] if hasattr(candidate, 'content') and hasattr(candidate.content, 'parts'): try: for part in candidate.content.parts: # Check if this part has a function_call attribute AND it has a name # (Not just an empty function_call object) if hasattr(part, 'function_call') and hasattr(part.function_call, 'name') and part.function_call.name: has_function_calls = True # Convert to OpenAI tool call format class ToolCall: def __init__(self, fc): self.id = f"call_{fc.name}" self.type = "function" self.function = type('obj', (object,), { 'name': fc.name, 'arguments': json.dumps(dict(fc.args)) })()
if response_obj.choices[0].message.tool_calls is None: response_obj.choices[0].message.tool_calls = []
response_obj.choices[0].message.tool_calls.append( ToolCall(part.function_call) ) response_obj.choices[0].finish_reason = "tool_calls" except (TypeError, AttributeError): # Parts might not be iterable in some response formats pass
# Extract text content only if no function calls if not has_function_calls: if hasattr(gemini_response, 'text') and gemini_response.text: response_obj.choices[0].message.content = gemini_response.text elif hasattr(gemini_response, 'candidates') and gemini_response.candidates: # Extract from candidates structure (used in chat sessions) candidate = gemini_response.candidates[0] if hasattr(candidate, 'content') and hasattr(candidate.content, 'parts'): # Combine all text parts text_parts = [] for part in candidate.content.parts: if hasattr(part, 'text') and part.text: text_parts.append(part.text) if text_parts: response_obj.choices[0].message.content = ''.join(text_parts) elif hasattr(gemini_response, 'parts') and gemini_response.parts: response_obj.choices[0].message.content = gemini_response.parts[0].text
# Estimate token usage (Gemini doesn't provide exact counts in the same way) if hasattr(gemini_response, 'usage_metadata'): usage = gemini_response.usage_metadata response_obj.usage.prompt_tokens = getattr(usage, 'prompt_token_count', 0) response_obj.usage.completion_tokens = getattr(usage, 'candidates_token_count', 0) response_obj.usage.total_tokens = getattr(usage, 'total_token_count', 0)
# Print token usage print(f"π Tokens: {response_obj.usage.prompt_tokens} prompt + {response_obj.usage.completion_tokens} completion = {response_obj.usage.total_tokens} total")
except Exception as e: print(f"β οΈ Warning converting Gemini response: {e}") # Return basic response on error if not response_obj.choices[0].message.content: response_obj.choices[0].message.content = str(gemini_response)
return response_obj105 unmodified lines10610710810911011111211311411511611711811912012112212312422 unmodified lines1471481491501511521531541555 unmodified lines1611621631641651661671681691701711723 unmodified lines176177178179180181105 unmodified linesreturn f"Error executing command '{command}': {str(e)}"def search_code(pattern, path=".", file_extension=None):"""Search for a pattern in code files (like grep).Args:pattern: Text pattern to search forpath: Directory to search in (default: current directory)file_extension: Optional file extension filter (e.g., "py", "js")Returns:str: Search results or error message"""try:# Build grep commandcmd_parts = ["grep", "-r", "-n", "-i", pattern, path]22 unmodified lineslines = result.stdout.strip().split('\n')# Limit results to prevent overwhelming outputif len(lines) > 50:return f"Found {len(lines)} matches (showing first 50):\n\n" + '\n'.join(lines[:50])else:return f"Found {len(lines)} matches:\n\n{result.stdout}"elif result.returncode == 1:return f"No matches found for pattern '{pattern}' in {path}"else:5 unmodified linesreturn f"Error searching for pattern '{pattern}': {str(e)}"def list_files(path=".", pattern=None, show_hidden=False):"""List files and directories.Args:path: Directory path to list (default: current directory)pattern: Optional glob pattern to filter (e.g., "*.py", "test_*")show_hidden: Whether to show hidden files (default: False)3 unmodified linestry:import glob# Build the search patternif pattern:search_path = os.path.join(path, pattern)105 unmodified lines10610710810911011111211311411511611711811912012112212312412512612712822 unmodified lines1511521531541551561571581591601611621635 unmodified lines1691701711721731741751761771781791803 unmodified lines184185186187188189190191192193105 unmodified linesreturn f"Error executing command '{command}': {str(e)}"def search_code(pattern, path=None, file_extension=None):"""Search for a pattern in code files (like grep).Args:pattern: Text pattern to search forpath: Directory to search in (default: repository path from env or current directory)file_extension: Optional file extension filter (e.g., "py", "js")Returns:str: Search results or error message"""try:# Use repo path from environment if not specifiedif path is None:path = os.environ.get('CODEPILOT_REPO_PATH', '.')# Build grep commandcmd_parts = ["grep", "-r", "-n", "-i", pattern, path]22 unmodified lineslines = result.stdout.strip().split('\n')# Limit results to prevent overwhelming outputif len(lines) > 50:output = f"Found {len(lines)} matches (showing first 50):\n\n" + '\n'.join(lines[:50])else:output = f"Found {len(lines)} matches:\n\n{result.stdout}"# Add explicit instruction to stop searchingoutput += "\n\nβ SEARCH COMPLETE. You have all the information needed. Provide your answer now."return outputelif result.returncode == 1:return f"No matches found for pattern '{pattern}' in {path}"else:5 unmodified linesreturn f"Error searching for pattern '{pattern}': {str(e)}"def list_files(path=None, pattern=None, show_hidden=False):"""List files and directories.Args:path: Directory path to list (default: repository path from env or current directory)pattern: Optional glob pattern to filter (e.g., "*.py", "test_*")show_hidden: Whether to show hidden files (default: False)3 unmodified linestry:import glob# Use repo path from environment if not specifiedif path is None:path = os.environ.get('CODEPILOT_REPO_PATH', '.')# Build the search patternif pattern:search_path = os.path.join(path, pattern)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778version: '3.8'
################################################################################# CodePilot Production Docker Compose Configuration# Deploys Chainlit UI with Gemini integration on GCP VM################################################################################
services: codepilot: build: context: . dockerfile: Dockerfile container_name: codepilot # Restart policy - always restart unless explicitly stopped restart: unless-stopped # Port mapping: Host:Container # Chainlit runs on 7860 internally, exposed as 8000 externally ports: - "8000:7860" # Load environment variables from .env file env_file: - .env # Override specific environment variables environment: - PORT=7860 - HOST=0.0.0.0 - PYTHONUNBUFFERED=1 # Ensure logs appear in docker logs # Volume mounts for persistence volumes: # Persist cloned GitHub repositories - codepilot_data:/home/user/app/data # Optional: Mount logs directory - codepilot_logs:/home/user/app/logs # Resource limits to prevent OOM and CPU throttling deploy: resources: limits: memory: 4G # Maximum memory cpus: '2.0' # Maximum CPU cores reservations: memory: 2G # Guaranteed memory cpus: '1.0' # Guaranteed CPU cores # Health check to monitor service status healthcheck: test: ["CMD", "curl", "-f", "http://localhost:7860"] interval: 30s # Check every 30 seconds timeout: 10s # Wait 10s for response retries: 3 # Restart after 3 failed checks start_period: 40s # Give 40s for initial startup # Logging configuration logging: driver: "json-file" options: max-size: "10m" # Max 10MB per log file max-file: "3" # Keep 3 rotated log files
# Named volumes for data persistence (Docker-managed)volumes: codepilot_data: codepilot_logs:
################################################################################# Usage:# docker compose up -d # Start in background# docker compose logs -f # View logs# docker compose ps # Check status# docker compose down # Stop and remove# docker compose restart # Restart service################################################################################1234567896 unmodified lines16171819202122# Full deployment requirements with embeddings support# For HuggingFace Spaces with 16GB+ RAM# Coreopenai>=1.0.0anthropic>=0.25.0python-dotenv>=1.2.0# E2B Sandbox6 unmodified lines# Search - BM25 + Embeddingsrank-bm25>=0.2.2sentence-transformers>=2.2.0chromadb>=0.4.0# Chainlit UIchainlit>=1.0.0123456786 unmodified lines15161718192021# Full deployment requirements with embeddings support# For HuggingFace Spaces with 16GB+ RAM# Core - Gemini Migrationgoogle-generativeai>=0.3.0python-dotenv>=1.2.0# E2B Sandbox6 unmodified lines# Search - BM25 + Embeddingsrank-bm25>=0.2.2sentence-transformers>=2.2.0chromadb>=0.5.0# Chainlit UIchainlit>=1.0.0
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266#!/bin/bash################################################################################# CodePilot GCP Deployment Script# Deploys CodePilot to Google Cloud Platform VM with zero manual steps################################################################################
set -e # Exit on error
# Colors for outputRED='\033[0;31m'GREEN='\033[0;32m'YELLOW='\033[1;33m'BLUE='\033[0;34m'NC='\033[0m' # No Color
# ConfigurationTARBALL_NAME="codepilot-deployment.tar.gz"REMOTE_DIR="~/codepilot"BACKUP_DIR="~/codepilot_backup"
################################################################################# Helper Functions################################################################################
log_info() { echo -e "${BLUE}βΉοΈ $1${NC}"}
log_success() { echo -e "${GREEN}β
$1${NC}"}
log_warning() { echo -e "${YELLOW}β οΈ $1${NC}"}
log_error() { echo -e "${RED}β $1${NC}"}
################################################################################# Load and Validate Environment################################################################################
log_info "Loading environment configuration..."
# Load .env file if existsif [ -f .env ]; then source .env log_success "Loaded .env file"else log_warning ".env file not found - using environment variables only"fi
# Validate required variablesif [ -z "$GCP_VM_IP" ]; then log_error "GCP_VM_IP not set" echo "Please set GCP_VM_IP in .env file or environment" echo "Example: export GCP_VM_IP=34.123.45.67" exit 1fi
# Set defaultsGCP_SSH_USER=${GCP_SSH_USER:-$(whoami)}GCP_SSH_KEY=${GCP_SSH_KEY:-~/.ssh/google_compute_engine}
log_info "Deployment Configuration:"echo " β’ Target VM: $GCP_VM_IP"echo " β’ SSH User: $GCP_SSH_USER"echo " β’ SSH Key: $GCP_SSH_KEY"
# Verify SSH key existsif [ ! -f "$GCP_SSH_KEY" ]; then log_error "SSH key not found: $GCP_SSH_KEY" echo "Generate one with: ssh-keygen -t rsa -f $GCP_SSH_KEY" exit 1fi
################################################################################# Pre-Deployment Checks################################################################################
log_info "Running pre-deployment checks..."
# Test SSH connectivitylog_info "Testing SSH connection to $GCP_VM_IP..."if ssh -i "$GCP_SSH_KEY" -o ConnectTimeout=10 -o BatchMode=yes "$GCP_SSH_USER@$GCP_VM_IP" "echo 'SSH connection successful'" &>/dev/null; then log_success "SSH connection verified"else log_error "Cannot connect to $GCP_VM_IP" echo "Check that:" echo " 1. VM is running" echo " 2. Firewall allows SSH (port 22)" echo " 3. SSH key is added to VM" exit 1fi
################################################################################# Build Deployment Package################################################################################
log_info "Building deployment package..."
# Remove old tarball if existsrm -f "$TARBALL_NAME"
# Create tarball excluding unnecessary filestar -czf "$TARBALL_NAME" \ --exclude=venv \ --exclude=.git \ --exclude=__pycache__ \ --exclude='*.pyc' \ --exclude='*.pyo' \ --exclude='.pytest_cache' \ --exclude='*.egg-info' \ --exclude='.DS_Store' \ --exclude='node_modules' \ --exclude="$TARBALL_NAME" \ .
TARBALL_SIZE=$(du -h "$TARBALL_NAME" | cut -f1)log_success "Created tarball: $TARBALL_NAME ($TARBALL_SIZE)"
################################################################################# Upload to GCP VM################################################################################
log_info "Uploading to GCP VM..."
scp -i "$GCP_SSH_KEY" \ -o StrictHostKeyChecking=no \ "$TARBALL_NAME" \ "$GCP_SSH_USER@$GCP_VM_IP:/tmp/"
log_success "Upload complete"
################################################################################# Deploy on Remote VM################################################################################
log_info "Deploying on remote VM..."
ssh -i "$GCP_SSH_KEY" \ -o StrictHostKeyChecking=no \ "$GCP_SSH_USER@$GCP_VM_IP" << 'REMOTE_SCRIPT'
set -e # Exit on error
# Colors for remote outputRED='\033[0;31m'GREEN='\033[0;32m'YELLOW='\033[1;33m'BLUE='\033[0;34m'NC='\033[0m'
log_info() { echo -e "${BLUE}βΉοΈ $1${NC}"; }log_success() { echo -e "${GREEN}β
$1${NC}"; }log_warning() { echo -e "${YELLOW}β οΈ $1${NC}"; }log_error() { echo -e "${RED}β $1${NC}"; }
################################################################################# Backup existing deployment################################################################################
if [ -d ~/codepilot ]; then log_info "Backing up existing deployment..." # Stop current containers cd ~/codepilot if [ -f docker-compose.yml ]; then docker-compose down || log_warning "Failed to stop containers (may not be running)" fi # Create backup BACKUP_NAME="codepilot_backup_$(date +%Y%m%d_%H%M%S)" mv ~/codepilot ~/"$BACKUP_NAME" log_success "Backup created: ~/$BACKUP_NAME"fi
################################################################################# Extract new deployment################################################################################
log_info "Extracting deployment package..."mkdir -p ~/codepilotcd /tmptar -xzf codepilot-deployment.tar.gz -C ~/codepilotlog_success "Extracted to ~/codepilot"
################################################################################# Deploy with Docker Compose################################################################################
cd ~/codepilot
log_info "Starting Docker containers..."
# Check if docker-compose.yml existsif [ ! -f docker-compose.yml ]; then log_error "docker-compose.yml not found in deployment package" exit 1fi
# Pull latest images and startdocker-compose pull || log_warning "Failed to pull images (using cached)"docker-compose up -d
log_success "Docker containers started"
################################################################################# Health Check################################################################################
log_info "Running health check..."sleep 5 # Wait for containers to initialize
# Check if containers are runningRUNNING_CONTAINERS=$(docker-compose ps --services --filter "status=running" | wc -l)TOTAL_CONTAINERS=$(docker-compose ps --services | wc -l)
if [ "$RUNNING_CONTAINERS" -eq "$TOTAL_CONTAINERS" ]; then log_success "All containers healthy ($RUNNING_CONTAINERS/$TOTAL_CONTAINERS running)"else log_warning "Some containers not running ($RUNNING_CONTAINERS/$TOTAL_CONTAINERS)" docker-compose psfi
################################################################################# Cleanup################################################################################
log_info "Cleaning up..."rm -f /tmp/codepilot-deployment.tar.gzlog_success "Cleanup complete"
echo ""log_success "π Deployment successful!"echo "Access CodePilot at: http://$(hostname -I | awk '{print $1}'):8000"
REMOTE_SCRIPT
################################################################################# Local Cleanup################################################################################
log_info "Cleaning up local files..."rm -f "$TARBALL_NAME"log_success "Local cleanup complete"
################################################################################# Final Status################################################################################
echo ""echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"echo "β DEPLOYMENT SUCCESSFUL β"echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"echo ""log_success "CodePilot deployed to $GCP_VM_IP"echo ""echo "Next steps:"echo " 1. Access UI: http://$GCP_VM_IP:8000"echo " 2. Check logs: ssh $GCP_SSH_USER@$GCP_VM_IP 'cd ~/codepilot && docker-compose logs -f'"echo " 3. Stop: ssh $GCP_SSH_USER@$GCP_VM_IP 'cd ~/codepilot && docker-compose down'"echo ""