Skip to content

[FEATURE] Implement Model Selection in Claude Service #34

Closed

Description

@integry

Previous Issue ID

33

Epic

Enable Model-Specific AI Processing via Issue Labels

Current Stage

The worker can now handle model names. This critical task focuses on making claudeService.js actually use the specified model when invoking the claude-code CLI.

Description

The claudeService.js module executes the claude-code CLI in Docker. It currently doesn't explicitly select an Anthropic model. This issue requires:

  1. Investigating how claude-code CLI can be instructed to use a specific model (e.g., claude-3-opus-20240229).
  2. Modifying executeClaudeCode in src/claude/claudeService.js to pass the modelName from the worker to the Dockerized CLI execution.

Context

  • executeClaudeCode in src/claude/claudeService.js runs a Docker command.
  • The provided claude --help output lacks a direct model selection flag.
  • Config files (~/.claude/.credentials.json, ~/.claude.json) are mounted.

Implementation Steps

  1. Research claude-code CLI Model Selection:
    • Investigate if model selection is possible via: CLI argument (undocumented?), environment variable, or config file modification.
  2. Modify executeClaudeCode (src/claude/claudeService.js):
    • Add a modelToUse parameter.
    • Implement logic to pass modelToUse to claude-code based on research (e.g., Docker env var, dynamic config mount).
  3. Handle Infeasibility:
    • If direct model selection is impossible, document this. The modelName will then be for tracking/labeling, and PRs might use the default claude-code model.
  4. Update Claude Prompt (Optional):
    • Consider adding model name to the prompt (e.g., You are to act as ${modelToUse}).
  5. Testing:
    • Update test/claude.test.js. Focus on correct parameter passing. Manual testing will be crucial.

Suggested Implementation (Conceptual - src/claude/claudeService.js)

export async function executeClaudeCode({ /*...,*/ modelToUse }) {
    logger.info({ /*...,*/ modelToUse }, /*...*/);
    const prompt = customPrompt || generateClaudePrompt(issueRef, modelToUse);
    const dockerArgs = [ /*...*/ ];
    // *** CRITICAL INVESTIGATION AREA for model selection mechanism ***
    // Option A: Docker Env Var: dockerArgs.push('-e', `CLAUDE_MODEL_OVERRIDE=${modelToUse}`); (hypothetical)
    // Option B: CLI Arg: dockerArgs.push('--use-model', modelToUse); (hypothetical)
    // Option C: Dynamic Config File
    // *** END CRITICAL INVESTIGATION AREA ***
    dockerArgs.push(CLAUDE_DOCKER_IMAGE, 'claude', '-p', prompt, /*...*/);
    // ...
    // Log if actual model used (from claude-code output) matches intended modelToUse
}

function generateClaudePrompt(issueRef, modelName) {
    return `Please analyze and fix the GitHub issue: #${issueRef.number}. You are acting as model: ${modelName || 'default'}. ...`;
}

Activity

  1. integry commented on May 28, 2025

    @integry
    OwnerAuthor

    Suggested conceptual implementation for src/claude/claudeService.js:

    // In src/claude/claudeService.js
    export async function executeClaudeCode({ worktreePath, issueRef, githubToken, customPrompt, isRetry = false, retryReason, modelToUse /* NEW PARAMETER from worker */ }) {
        const startTime = Date.now();
        
        logger.info({
            issueNumber: issueRef.number,
            repository: `${issueRef.repoOwner}/${issueRef.repoName}`,
            worktreePath,
            dockerImage: CLAUDE_DOCKER_IMAGE,
            isRetry,
            retryReason,
            intendedModel: modelToUse // Log the model we intend to use
        }, isRetry ? 'Starting Claude Code execution (RETRY)...' : 'Starting Claude Code execution...');
    
        try {
            // Pass modelToUse to generateClaudePrompt if it needs to be part of the text prompt
            const prompt = customPrompt || generateClaudePrompt(issueRef, modelToUse);
            
            const dockerArgs = [
                'run',
                '--rm',
                '--security-opt', 'no-new-privileges',
                '--cap-drop', 'ALL',
                '--network', 'bridge',
                '-v', `${worktreePath}:/home/node/workspace:rw`,
                '-v', `${CLAUDE_CONFIG_PATH}:/home/node/.claude:rw`,
                '-v', `${path.join(os.homedir(), '.claude.json')}:/home/node/.claude.json:rw`,
                '-e', `GH_TOKEN=${githubToken}`,
                // *** POTENTIAL MODEL SELECTION MECHANISM (NEEDS INVESTIGATION) ***
                // Example: If claude-code respects an env var like 'ANTHROPIC_MODEL_NAME'
                // This is HYPOTHETICAL and needs to be verified.
                // if (modelToUse) {
                //     dockerArgs.push('-e', `ANTHROPIC_MODEL_NAME=${modelToUse}`);
                // }
                // Another HYPOTHETICAL approach: mount a dynamic config if claude-code reads model from a specific file
                // String tempConfigFile = createTempClaudeConfigWithModel(modelToUse);
                // dockerArgs.push('-v', `${tempConfigFile}:/home/node/.claude/model_config.json:ro`);
                // And ensure claude-code CLI is told to use this ^ config. This is complex.
                // For now, the most direct approach is hoping for an env var or an undocumented CLI flag.
                // If neither, this 'modelToUse' parameter serves logging & downstream consistency,
                // while claude-code uses its own default/configured model.
                // ***********************************************************************
                '-w', '/home/node/workspace',
                CLAUDE_DOCKER_IMAGE,
                'claude', // The claude-code CLI command
                '-p', prompt,
                '--max-turns', CLAUDE_MAX_TURNS.toString(),
                '--output-format', 'stream-json',
                '--verbose',
                '--dangerously-skip-permissions'
                // Add other necessary claude-code CLI flags here
                // If a model flag for 'claude-code' CLI is found, add it here:
                // e.g., if there was a '--model', modelToUse (this is hypothetical)
            ];
    
            const result = await executeDockerCommand('docker', dockerArgs, { /* ... */ });
            // ... (parsing logic remains similar) ...
    
            // After parsing 'claudeOutput.model' from the result (as done currently):
            if (claudeOutput.model && modelToUse && claudeOutput.model !== modelToUse) {
                logger.warn({
                    issueNumber: issueRef.number,
                    intendedModel: modelToUse,
                    actualModelUsedByClaudeCode: claudeOutput.model
                }, "Model mismatch: Intended model differs from model reported by claude-code CLI.");
            }
            
            // Ensure 'model' field in response is the one reported by claude-code,
            // but also perhaps include 'intendedModel' for clarity.
            response.intendedModel = modelToUse; // Add this for downstream comparison
    
            return response;
    
        } catch (error) {
            // ... error handling ...
            return {
                success: false,
                error: error.message,
                executionTime: Date.now() - startTime,
                output: null,
                logs: error.stderr || error.message,
                intendedModel: modelToUse // Carry over intended model even on failure
            };
        }
    }
    
    // Modify generateClaudePrompt to optionally include the model name in the prompt text
    function generateClaudePrompt(issueRef, modelToUse) {
        const modelContext = modelToUse ? `You are to operate using the capabilities and persona of the ${modelToUse} model.` : '';
        return `Please analyze and fix the GitHub issue: #${issueRef.number}.
    ${modelContext}
    **REPOSITORY INFORMATION (CRITICAL - DO NOT HALLUCINATE):**
    - Repository Owner: ${issueRef.repoOwner}
    - Repository Name: ${issueRef.repoName}
    - Full Repository: ${issueRef.repoOwner}/${issueRef.repoName}
    ... rest of the prompt from src/claude/claudeService.js ...`;
    }

    Reasoning for Issue 3 code:
    The executeClaudeCode function now accepts a modelToUse parameter. The core of this task is the critical investigation area commented in the code. This is where the developer must determine how (or if) the claude-code CLI can be instructed to use a specific model. The code shows placeholders for potential mechanisms (environment variable, CLI argument, or dynamic config). If a mechanism is found, it should be implemented there. The prompt generation is also updated to optionally include the model name to potentially influence Claude's behavior. Finally, logging is added to compare the intendedModel with the model actually reported by the claude-code tool's output, which is crucial if direct control isn't possible.

  2. integry commented on May 29, 2025

    @integry
    OwnerAuthor

    already implemented

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions