v3.3.0: Add clarifying questions before planning
Browse filesFiles changed (4)
12345# HuggingFace Spaces Dockerfile for CodePilot# BUILD_VERSION: 8 (v3.2.1 coder max 8 iterations)FROM python:3.11-slim# Set working directory12345# HuggingFace Spaces Dockerfile for CodePilot# BUILD_VERSION: 9 (v3.3.0 clarifying questions)FROM python:3.11-slim# Set working directory
19 unmodified lines202122232425262793 unmodified lines121122123124125126192 unmodified lines31932032132232332419 unmodified lines# ============================================================# STARTUP VERSION CHECK - Change this to detect if rebuild worked# ============================================================APP_VERSION = "3.2.1-coder-max8"BUILD_ID = "2024-12-19-v7"print("=" * 60)print(f"[STARTUP] CodePilot Chainlit App")print(f"[STARTUP] APP_VERSION: {APP_VERSION}")93 unmodified lines# Get orchestratororchestrator: Orchestrator = cl.user_session.get("orchestrator")# Check for GitHub URL in messagegithub_url = extract_github_url(message.content)task_context = ""192 unmodified lineslog_msg.content = f"## Execution Log\n```\n{final_logs}\n```"await log_msg.update()# Send results summarysummary_lines = []19 unmodified lines202122232425262793 unmodified lines121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203192 unmodified lines39639739839940040140240340440540640740840941041141241319 unmodified lines# ============================================================# STARTUP VERSION CHECK - Change this to detect if rebuild worked# ============================================================APP_VERSION = "3.3.0-clarify"BUILD_ID = "2024-12-19-v8"print("=" * 60)print(f"[STARTUP] CodePilot Chainlit App")print(f"[STARTUP] APP_VERSION: {APP_VERSION}")93 unmodified lines# Get orchestratororchestrator: Orchestrator = cl.user_session.get("orchestrator")# Check if we're waiting for clarification answersif cl.user_session.get("waiting_for_clarification"):cl.user_session.set("waiting_for_clarification", False)user_answers = message.contentawait cl.Message(content="Got it! Let me create the plan with your clarifications...").send()# Resume the orchestrator with user answerslog_msg = cl.Message(content="")await log_msg.send()try:captured_output = io.StringIO()def resume_orchestrator():with redirect_stdout(captured_output), redirect_stderr(captured_output):return orchestrator.resume_after_clarification(user_answers)loop = asyncio.get_event_loop()executor = ThreadPoolExecutor(max_workers=1)future = loop.run_in_executor(executor, resume_orchestrator)# Track tokenstotal_prompt_tokens = 0total_completion_tokens = 0total_tokens = 0seen_token_lines = set()# Stream logsaccumulated_logs = ""while not future.done():await asyncio.sleep(0.5)current_output = captured_output.getvalue()if current_output != accumulated_logs:accumulated_logs = current_outputfiltered_lines = []for line in accumulated_logs.split('\n'):if 'Tokens:' in line and line not in seen_token_lines:seen_token_lines.add(line)try:parts = line.split('Tokens:')[1].strip()prompt = int(parts.split('prompt')[0].strip())completion = int(parts.split('+')[1].split('completion')[0].strip())total_prompt_tokens += prompttotal_completion_tokens += completiontotal_tokens += (prompt + completion)except:passif any(skip in line for skip in ['Tokens:', 'Batches:', '|##', 'it/s]']):continueif any(keep in line for keep in ['[CLASSIFIER]', '[ORCHESTRATOR]', '[PLANNER]', '[CODER]', '[REVIEWER]','[EXPLORER]', 'Calling tool:', 'Transitioning', 'APPROVED', 'REJECTED']):filtered_lines.append(line)filtered_output = '\n'.join(filtered_lines)input_cost = (total_prompt_tokens / 1000000) * 3.0output_cost = (total_completion_tokens / 1000000) * 15.0total_cost = input_cost + output_costusage_summary = f"\n\nCREDITS: ${total_cost:.4f}"log_msg.content = f"```\n{filtered_output}{usage_summary}\n```"await log_msg.update()result = await future# Continue to show results (handled by falling through to normal result handling below)# For now, show summary directlysummary = f"## Result\n**Status:** {result.get('status')}\n"if result.get('code_changes'):summary += f"**Files created:** {len(result['code_changes'])}\n"summary += f"**Cost:** ${total_cost:.4f}"await cl.Message(content=summary).send()returnexcept Exception as e:await cl.Message(content=f"Error resuming: {str(e)}").send()return# Check for GitHub URL in messagegithub_url = extract_github_url(message.content)task_context = ""192 unmodified lineslog_msg.content = f"## Execution Log\n```\n{final_logs}\n```"await log_msg.update()# Check if we need clarification from userif result.get('status') == 'clarifying' and result.get('clarifying_questions'):questions = result['clarifying_questions']# Store that we're waiting for clarificationcl.user_session.set("waiting_for_clarification", True)await cl.Message(content=f"## Before I proceed, I have some questions:\n\n{questions}\n\n"f"**Please answer the questions above so I can create a better plan.**").send()return # Wait for user to respond# Send results summarysummary_lines = []
8 unmodified lines91011121314157 unmodified lines232425262728299 unmodified lines39404142434445192 unmodified lines2382392402412422432442452462472482492502512522532542552562575 unmodified lines2632642652662672682699 unmodified lines2792802812822832843 unmodified lines2882892902912922932944 unmodified lines2993003013023033043053063071 unmodified line30931031131231331431531631731831932032132232332432532676 unmodified lines4034044054064074088 unmodified lines"""# VERSION CHECK - If you see this, new code is running!ORCHESTRATOR_VERSION = "3.2.1-coder-max8"print(f"[ORCHESTRATOR] ========== LOADING VERSION {ORCHESTRATOR_VERSION} ==========")from enum import Enum7 unmodified linesclass AgentState(Enum):"""Possible states in the multi-agent workflow"""EXPLORING = "exploring" # NEW - Explorer gathers context firstPLANNING = "planning"CODING = "coding"REVIEWING = "reviewing"9 unmodified linesThink of this as a clipboard that agents write to and read from."""task_description: str # Original task from userexploration_context: Optional[str] = None # NEW - Created by Explorerplan: Optional[str] = None # Created by Planner (uses exploration_context)code_changes: Optional[Dict[str, str]] = None # Created by Coderreview_feedback: Optional[str] = None # Created by Reviewer192 unmodified linesdef _run_full_workflow(self, task: str) -> Dict[str, Any]:"""Run the full Explorer → Planner → Coder → Reviewer workflow.v3.0: Now starts with Explorer to gather context efficiently,then Planner creates plan based on exploration (no tools).Args:task: User's task descriptionReturns:Result dict with status, changes, and messages"""# Initialize contextself.context = TaskContext(task_description=task)self.state = AgentState.EXPLORING # v3.0: Start with EXPLORING# Main state machine loopwhile self.state not in [AgentState.COMPLETE, AgentState.FAILED]:5 unmodified lines# Execute current stateif self.state == AgentState.EXPLORING:self._execute_exploring() # NEW - Explorer firstelif self.state == AgentState.PLANNING:self._execute_planning()9 unmodified lines# Return final resultreturn self._build_result()def _execute_exploring(self):"""Execute exploring state: call Explorer agent to gather context.3 unmodified lines- Find relevant files, functions, and patterns- Return context summary for Planner to useTransition: Always go to PLANNING next"""print(f"\n[ORCHESTRATOR] State: EXPLORING")print(f"[ORCHESTRATOR] Running Explorer to gather codebase context...")4 unmodified lines# Store exploration context for Planner to useself.context.exploration_context = exploration_result# Transition to planningself.state = AgentState.PLANNINGprint(f"[ORCHESTRATOR] Exploration complete. Transitioning to PLANNING")def _execute_planning(self):"""1 unmodified linePlanner's job (v3.0):- Receive exploration context from Explorer- Create step-by-step plan based on exploration (NO TOOLS)- Pure LLM reasoning - no searchingTransition: Always go to CODING next"""print(f"\n[ORCHESTRATOR] State: PLANNING")print(f"[ORCHESTRATOR] Using exploration context to create plan (no tools)...")# Call the Planner with exploration context (v3.0: Planner has no tools)self.context.plan = self.planner.run(task=self.context.task_description,exploration_context=self.context.exploration_context)# Transition to coding76 unmodified lines'status': self.state.value,'success': self.state == AgentState.COMPLETE,'task': self.context.task_description,'plan': self.context.plan,'code_changes': self.context.code_changes,'review_feedback': self.context.review_feedback,8 unmodified lines91011121314157 unmodified lines23242526272829309 unmodified lines404142434445464748192 unmodified lines2412422432442452462472482492502512522532542552562572582592602615 unmodified lines2672682692702712722732742752762772782799 unmodified lines2892902912922932942952962972982993003013023033043053063073 unmodified lines3113123133143153163174 unmodified lines3223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713721 unmodified line37437537637737837938038138238338438538638738838939039139239339439539676 unmodified lines4734744754764774784794808 unmodified lines"""# VERSION CHECK - If you see this, new code is running!ORCHESTRATOR_VERSION = "3.3.0-clarify"print(f"[ORCHESTRATOR] ========== LOADING VERSION {ORCHESTRATOR_VERSION} ==========")from enum import Enum7 unmodified linesclass AgentState(Enum):"""Possible states in the multi-agent workflow"""EXPLORING = "exploring" # Explorer gathers context firstCLARIFYING = "clarifying" # NEW - Ask user clarifying questionsPLANNING = "planning"CODING = "coding"REVIEWING = "reviewing"9 unmodified linesThink of this as a clipboard that agents write to and read from."""task_description: str # Original task from userexploration_context: Optional[str] = None # Created by Explorerclarifying_questions: Optional[str] = None # NEW - Questions from Planneruser_answers: Optional[str] = None # NEW - User's answers to questionsplan: Optional[str] = None # Created by Planner (uses exploration_context)code_changes: Optional[Dict[str, str]] = None # Created by Coderreview_feedback: Optional[str] = None # Created by Reviewer192 unmodified linesdef _run_full_workflow(self, task: str) -> Dict[str, Any]:"""Run the full Explorer → Clarify → Planner → Coder → Reviewer workflow.v3.3: Now includes clarification step before planning.Args:task: User's task descriptionReturns:Result dict with status, changes, and messagesIf questions need to be asked, returns with state='clarifying'"""# Initialize context if not already doneif self.context is None:self.context = TaskContext(task_description=task)self.state = AgentState.EXPLORING# Main state machine loopwhile self.state not in [AgentState.COMPLETE, AgentState.FAILED]:5 unmodified lines# Execute current stateif self.state == AgentState.EXPLORING:self._execute_exploring()elif self.state == AgentState.CLARIFYING:self._execute_clarifying()# If questions were generated, pause and return to Chainlitif self.context.clarifying_questions and self.state == AgentState.CLARIFYING:return self._build_result() # Return with questions, Chainlit will resumeelif self.state == AgentState.PLANNING:self._execute_planning()9 unmodified lines# Return final resultreturn self._build_result()def resume_after_clarification(self, user_answers: str) -> Dict[str, Any]:"""Resume workflow after user provides answers to clarifying questions.Args:user_answers: User's answers to the questionsReturns:Result dict from continued workflow"""self.provide_user_answers(user_answers)return self._run_full_workflow(self.context.task_description)def _execute_exploring(self):"""Execute exploring state: call Explorer agent to gather context.3 unmodified lines- Find relevant files, functions, and patterns- Return context summary for Planner to useTransition: Always go to CLARIFYING next"""print(f"\n[ORCHESTRATOR] State: EXPLORING")print(f"[ORCHESTRATOR] Running Explorer to gather codebase context...")4 unmodified lines# Store exploration context for Planner to useself.context.exploration_context = exploration_result# Transition to clarifying (ask user questions before planning)self.state = AgentState.CLARIFYINGprint(f"[ORCHESTRATOR] Exploration complete. Transitioning to CLARIFYING")def _execute_clarifying(self):"""Execute clarifying state: ask user clarifying questions.Planner generates questions, user answers, then we proceed to planning.If no questions needed, skip straight to planning.Transition: Go to PLANNING (with or without answers)"""print(f"\n[ORCHESTRATOR] State: CLARIFYING")print(f"[ORCHESTRATOR] Generating clarifying questions...")# Get clarifying questions from Plannerquestions = self.planner.get_clarifying_questions(task=self.context.task_description,exploration_context=self.context.exploration_context)if questions:# Store questions - Chainlit will handle getting user answersself.context.clarifying_questions = questionsprint(f"[ORCHESTRATOR] Questions generated. Waiting for user answers...")# Note: We'll pause here and let Chainlit get user input# The state stays at CLARIFYING until user answers are providedelse:# No questions needed, go straight to planningprint(f"[ORCHESTRATOR] No clarifying questions needed. Transitioning to PLANNING")self.state = AgentState.PLANNINGdef provide_user_answers(self, answers: str):"""Provide user answers to clarifying questions and continue workflow.Called by Chainlit after user responds to questions.Args:answers: User's answers to the clarifying questions"""self.context.user_answers = answersself.state = AgentState.PLANNINGprint(f"[ORCHESTRATOR] User answers received. Transitioning to PLANNING")def _execute_planning(self):"""1 unmodified linePlanner's job (v3.0):- Receive exploration context from Explorer- Use user answers if clarifying questions were asked- Create step-by-step plan based on exploration (NO TOOLS)- Pure LLM reasoning - no searchingTransition: Always go to CODING next"""print(f"\n[ORCHESTRATOR] State: PLANNING")if self.context.user_answers:print(f"[ORCHESTRATOR] Using exploration context + user answers to create plan...")else:print(f"[ORCHESTRATOR] Using exploration context to create plan (no tools)...")# Call the Planner with exploration context and user answersself.context.plan = self.planner.run(task=self.context.task_description,exploration_context=self.context.exploration_context,user_answers=self.context.user_answers)# Transition to coding76 unmodified lines'status': self.state.value,'success': self.state == AgentState.COMPLETE,'task': self.context.task_description,'clarifying_questions': self.context.clarifying_questions, # NEW'user_answers': self.context.user_answers, # NEW'plan': self.context.plan,'code_changes': self.context.code_changes,'review_feedback': self.context.review_feedback,
18 unmodified lines19202122232446 unmodified lines717273747576772 unmodified lines8081828384857 unmodified lines939495969798991 unmodified line10110210310410510610718 unmodified linesfrom typing import Optional# Planner's system prompt (v3.0 - no tools, just planning)PLANNER_SYSTEM_PROMPT = """You are a senior software architect and planning expert.46 unmodified lineselse:self.client = OpenAIClient(model=model)def run(self, task: str, exploration_context: Optional[str] = None) -> str:"""Create a plan for the given task using exploration context.2 unmodified linesArgs:task: Task description (e.g., "Add login feature")exploration_context: Context gathered by Explorer agentReturns:Detailed implementation plan as a string7 unmodified lines=== TASK ==={task}Based on the exploration results above, create a detailed implementation plan.Include specific file paths, function names, and step-by-step instructions for the Coder agent."""1 unmodified line# Fallback if no exploration context (shouldn't happen in v3.0)user_prompt = f"""=== TASK ==={task}Create a detailed implementation plan for this task.Note: No exploration context was provided, so make reasonable assumptions about the codebase structure."""18 unmodified lines19202122232425262728293031323334353637383940414246 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461472 unmodified lines1501511521531541551567 unmodified lines1641651661671681691701711721731741751761771781 unmodified line18018118218318418518618718818919019119218 unmodified linesfrom typing import Optional# Planner's system prompt for asking clarifying questionsPLANNER_QUESTIONS_PROMPT = """You are a senior software architect helping clarify requirements.Based on the task and codebase exploration, generate 2-4 SHORT clarifying questions that will help create a better implementation plan.IMPORTANT:- Only ask questions if something is genuinely unclear or there are multiple valid approaches- Questions should be answerable in 1-2 sentences- Focus on: location, naming, behavior, edge cases- If the task is already clear, respond with: "NO_QUESTIONS_NEEDED"Format your response as a numbered list:1. Question one?2. Question two?Or just: NO_QUESTIONS_NEEDED"""# Planner's system prompt (v3.0 - no tools, just planning)PLANNER_SYSTEM_PROMPT = """You are a senior software architect and planning expert.46 unmodified lineselse:self.client = OpenAIClient(model=model)def get_clarifying_questions(self, task: str, exploration_context: Optional[str] = None) -> Optional[str]:"""Generate clarifying questions before creating the plan.Args:task: Task descriptionexploration_context: Context gathered by Explorer agentReturns:Questions as a string, or None if no questions needed"""print(f"[PLANNER] Generating clarifying questions...")# Build promptif exploration_context:user_prompt = f"""=== EXPLORATION RESULTS ==={exploration_context}=== TASK ==={task}Based on the above, what clarifying questions would help create a better implementation plan?"""else:user_prompt = f"""=== TASK ==={task}What clarifying questions would help create a better implementation plan?"""# Create conversationconversation = ConversationManager()conversation.add_message("system", PLANNER_QUESTIONS_PROMPT)conversation.add_message("user", user_prompt)# Single LLM callresponse = self.client.chat(messages=conversation.get_messages(),tools=None,max_tokens=500)questions = response.choices[0].message.content# Check if questions are neededif questions and "NO_QUESTIONS_NEEDED" in questions.upper():print(f"[PLANNER] No clarifying questions needed")return Noneprint(f"[PLANNER] Generated clarifying questions")return questionsdef run(self, task: str, exploration_context: Optional[str] = None, user_answers: Optional[str] = None) -> str:"""Create a plan for the given task using exploration context.2 unmodified linesArgs:task: Task description (e.g., "Add login feature")exploration_context: Context gathered by Explorer agentuser_answers: User's answers to clarifying questions (optional)Returns:Detailed implementation plan as a string7 unmodified lines=== TASK ==={task}"""# Add user answers if providedif user_answers:user_prompt += f"""=== USER CLARIFICATIONS ==={user_answers}"""user_prompt += """Based on the exploration results above, create a detailed implementation plan.Include specific file paths, function names, and step-by-step instructions for the Coder agent."""1 unmodified line# Fallback if no exploration context (shouldn't happen in v3.0)user_prompt = f"""=== TASK ==={task}"""if user_answers:user_prompt += f"""=== USER CLARIFICATIONS ==={user_answers}"""user_prompt += """Create a detailed implementation plan for this task.Note: No exploration context was provided, so make reasonable assumptions about the codebase structure."""
Dockerfile+1-1
chainlit_app.py+91-2
codepilot/agents/orchestrator.py+88-16
codepilot/agents/planner_agent.py+87-2