Skip to content

Epic: Claude-Powered GitHub Issue Processor - Stage 12: Cost Management and Optimization Framework #16

Closed

Description

@integry

General Goal of the Epic

To create an automated system that monitors GitHub issues, uses Anthropic's Claude Code to generate solutions, and automates the Git workflow including PR creation.

Current Stage (Issue 12 of N) - Future Enhancement

This issue focuses on establishing a framework for managing and optimizing the operational costs associated with running the Claude Code-powered system, particularly LLM API usage. (Refers to Proposal Section 6.3)

  • What's being done in this issue:
    1. Design a mechanism for detailed tracking of token consumption per issue processed, leveraging Claude Code's output metadata if available.
    2. Outline strategies for prompt optimization to reduce token usage.
    3. Discuss model selection strategies (e.g., using less expensive models for simpler tasks if applicable).
    4. Propose methods for setting budget controls and alerts.
  • What's been done (up to $PREVIOUS_ISSUE_11_ID_PLACEHOLDER): Core workflow, context optimization ideas, and advanced deployment strategies (Kubernetes) have been outlined.
  • What's remaining (for the epic): Implementation of this and other advanced enhancements, full operationalization.

Task Details

1. Token Usage Tracking (Sec 6.3, Ref 26)

  • Leverage Claude Output:
    • The Claude Code CLI's JSON output can provide metadata including cost or token usage (Sec 2.3.4). Investigate the exact structure of this metadata.
    • The worker script (`src/claude/claudeService.js`) should parse this metadata after each Claude run.
  • Logging and Aggregation:
    • Log the token usage (prompt tokens, completion tokens, total tokens) and associated cost (if provided by Claude) for each GitHub issue processed. Include the correlation ID.
    • Plan for how this data can be aggregated (e.g., in a database, or pushed to a metrics system like Prometheus/Grafana if K8s is used, or even a simple CSV/log file for analysis).
  • Claude's `/cost` command (Ref 25): While useful for interactive sessions, it's less applicable for non-interactive scripted runs unless there's a way to programmatically query it or its underlying data source. Focus on the JSON output from `claude -p ...`.

2. Prompt Optimization Strategies (Sec 6.3)

  • Conciseness:
    • Review existing prompts (initial prompt from Issue 5, slash command from Issue 9).
    • Identify areas where instructions can be made more concise without losing effectiveness.
    • Encourage use of few-shot examples within prompts if they prove more token-efficient than verbose instructions for certain tasks.
  • Contextual Filtering (Relates to Issue 10 - RAG):
    • Emphasize that providing only the most relevant code snippets (via RAG) is a key token optimization strategy.
  • Iterative Refinement:
    • Establish a process to regularly review high-token-usage tasks and refine their prompts.

3. Model Selection (Sec 6.3, Ref 36)

  • If Multiple Claude Models/Versions Available:
    • Research if different Claude models (e.g., Opus vs. Sonnet vs. Haiku for Claude 3 series, or different versions of Claude Code models if they exist) have different capabilities and cost structures.
    • Propose a strategy for selecting the most cost-effective model suitable for the task's complexity.
      • Example: Simpler linting fixes or doc generation might use a cheaper/faster model. Complex bug fixes might require a more powerful model.
    • This might involve an initial classification step for issues or configurable model selection per repository/issue type.
  • Configuration: Allow the Claude model to be configured (e.g., via environment variable or per-task parameter).

4. Budget Controls and Alerts (Sec 6.3)

  • Monitoring:
    • Based on aggregated token/cost data, set up monitoring dashboards (e.g., in Grafana, or a simpler alerting script).
  • Alerting:
    • Implement alerts (e.g., email, Slack) if:
      • Daily/weekly/monthly token usage exceeds predefined budgets.
      • Cost per resolved issue goes above a certain threshold.
      • A single issue processing consumes an unusually high number of tokens.
  • Rate Limiting / Throttling (System-Level):
    • Consider implementing system-level throttling if costs are a major concern (e.g., limit the number of issues processed per hour/day based on budget).
    • The `--max-turns` flag for Claude Code CLI (Sec 2.3.1) is a direct way to limit iterations and thus cost per task. Ensure this is used and configurable.

Acceptance Criteria

  • A design document outlining how token usage and costs will be tracked, logged, and aggregated.
  • Documented strategies for prompt optimization and model selection (if applicable).
  • A plan for implementing budget controls and alerts.
  • The worker's Claude execution module is updated to attempt parsing and logging of token/cost metadata from Claude's output.

Activity

  1. integry commented on May 24, 2025

    @integry
    OwnerAuthor

    Implementation Notes for Cost Management

    1. Parsing Claude's JSON Output for Cost/Tokens:

    • The exact structure of cost/token metadata in Claude Code CLI's JSON output needs to be verified by running test executions. (Ref: Proposal Sec 2.3.4 mentions JSON output includes metadata like cost and duration).
    • Example (Conceptual) in src/claude/claudeService.js:
      // Inside runClaudeToFixIssue, after JSON.parse(stdout):
      // let tokensUsed = null;
      // let costIncurred = null;
      //
      // // This is highly speculative and depends on actual Claude CLI output structure
      // if (claudeOutput.metadata && claudeOutput.metadata.usage) {
      //     tokensUsed = claudeOutput.metadata.usage.total_tokens;
      //     // Cost might not be directly available, or might be in a specific currency unit
      //     costIncurred = claudeOutput.metadata.usage.cost_usd; // Example field
      // } else if (Array.isArray(claudeOutput)) {
      //    // If output is an array of messages, iterate and sum up if token info is per message
      //    // This was mentioned as a possibility for stream-json, but json might be an array too.
      // }
      //
      // if (tokensUsed !== null) {
      //     log.info({ issueNumber: issue.number, tokensUsed, costIncurred }, 'Claude token usage recorded.');
      //     // Persist this data for aggregation (e.g., write to a metrics store or log for parsing)
      // }

    2. Model Selection Configuration:

    • If the Claude Code CLI supports specifying different model versions (e.g., via an environment variable like ANTHROPIC_MODEL_NAME or a CLI flag), the claudeService.js should allow this to be passed through.
    • The main worker loop could decide which model to use based on issue labels or other heuristics.

    3. Alerting Scripts (Conceptual):

    • A separate script (e.g., Node.js or Python) could run periodically (cron job):
      • Query the aggregated token/cost data (from logs, DB, or metrics system).
      • Compare against predefined budget thresholds.
      • Send alerts (e.g., using Nodemailer for email, or a Slack webhook library).

    4. Using --max-turns:

    • Ensure the docker run command for Claude in claudeService.js includes a configurable --max-turns argument.
      # Example part of dockerRunArgs in claudeService.js
      # maxTurns = process.env.CLAUDE_MAX_TURNS || '10'; // Default to 10 turns
      # dockerRunArgs.push('--max-turns', maxTurns);

    Focus on setting up the framework for tracking and analysis first. Actual optimization is an ongoing process.

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