|
| 1 | +"""AI client and GitHub API utilities.""" |
| 2 | +import os |
| 3 | +import sys |
| 4 | +import requests |
| 5 | +from anthropic import Anthropic |
| 6 | + |
| 7 | +try: |
| 8 | + from anthropic import AnthropicVertex |
| 9 | + |
| 10 | + VERTEX_AVAILABLE = True |
| 11 | +except ImportError: |
| 12 | + VERTEX_AVAILABLE = False |
| 13 | + |
| 14 | +# Hardcoded agent context for portability (template-friendly) |
| 15 | +AGENT_CONTEXT = """ |
| 16 | +**Your Role**: |
| 17 | +You are the Codebase Agent for this repository. You assist with code reviews, |
| 18 | +technical guidance, and maintaining code quality standards. |
| 19 | +
|
| 20 | +**Operating Principles**: |
| 21 | +
|
| 22 | +1. **Safety First** |
| 23 | + - Show plan before major changes |
| 24 | + - Explain reasoning and alternatives |
| 25 | + - Ask for clarification when requirements are ambiguous |
| 26 | +
|
| 27 | +2. **High Signal, Low Noise** |
| 28 | + - Only comment when adding unique value |
| 29 | + - Be concise and get to the point |
| 30 | + - Focus on critical issues, not minor style differences |
| 31 | +
|
| 32 | +**Code Review Focus**: |
| 33 | +When reviewing code, prioritize: |
| 34 | +- **Bugs**: Logic errors, edge cases, error handling |
| 35 | +- **Security**: Input validation, OWASP Top 10 vulnerabilities |
| 36 | +- **Performance**: Inefficient algorithms, unnecessary operations |
| 37 | +- **Style**: Code quality and maintainability |
| 38 | +- **Testing**: Coverage, missing test cases |
| 39 | +
|
| 40 | +**Feedback Guidelines**: |
| 41 | +- Be specific and actionable |
| 42 | +- Provide code examples for fixes |
| 43 | +- Explain "why" not just "what" |
| 44 | +- Prioritize critical issues |
| 45 | +- Acknowledge good practices |
| 46 | +
|
| 47 | +**Communication Style**: |
| 48 | +- Direct and technical (assume user has context) |
| 49 | +- Code-focused (show examples, not just descriptions) |
| 50 | +- Actionable (always provide next steps) |
| 51 | +- Honest (admit uncertainty, ask for clarification) |
| 52 | +
|
| 53 | +**What NOT to Do**: |
| 54 | +- No generic AI responses or "AI slop" |
| 55 | +- Don't state the obvious or add filler content |
| 56 | +- Don't make assumptions about ambiguous requirements |
| 57 | +- Don't include unnecessary praise or validation |
| 58 | +""" |
| 59 | + |
| 60 | + |
| 61 | +def _get_claude_client(): |
| 62 | + """Get Claude client with Vertex AI fallback to Anthropic API. |
| 63 | +
|
| 64 | + Tries Vertex AI first (if GCP_PROJECT_ID set), falls back to Anthropic API. |
| 65 | +
|
| 66 | + Returns: |
| 67 | + Anthropic or AnthropicVertex client |
| 68 | +
|
| 69 | + Raises: |
| 70 | + RuntimeError: If no credentials configured |
| 71 | + """ |
| 72 | + # Try Vertex AI first if credentials available |
| 73 | + if VERTEX_AVAILABLE: |
| 74 | + project_id = os.environ.get("GCP_PROJECT_ID") |
| 75 | + region = os.environ.get("GCP_REGION", "us-central1") |
| 76 | + |
| 77 | + if project_id: |
| 78 | + try: |
| 79 | + return AnthropicVertex(project_id=project_id, region=region) |
| 80 | + except Exception as e: |
| 81 | + print( |
| 82 | + f"⚠️ Vertex AI unavailable ({e}), falling back to Anthropic API", |
| 83 | + file=sys.stderr, |
| 84 | + ) |
| 85 | + |
| 86 | + # Fall back to Anthropic API |
| 87 | + api_key = os.environ.get("ANTHROPIC_API_KEY") |
| 88 | + if not api_key: |
| 89 | + raise RuntimeError( |
| 90 | + "No AI credentials found. Set either:\n" |
| 91 | + " - GCP_PROJECT_ID (for Vertex AI), or\n" |
| 92 | + " - ANTHROPIC_API_KEY (for Anthropic API)" |
| 93 | + ) |
| 94 | + |
| 95 | + return Anthropic(api_key=api_key) |
| 96 | + |
| 97 | + |
| 98 | +def call_claude(repo_name: str, command: str, url: str) -> str: |
| 99 | + """Call Claude API with context. |
| 100 | +
|
| 101 | + Args: |
| 102 | + repo_name: Repository name (owner/repo) |
| 103 | + command: User command to execute |
| 104 | + url: GitHub issue/PR URL |
| 105 | +
|
| 106 | + Returns: |
| 107 | + AI response text |
| 108 | +
|
| 109 | + Raises: |
| 110 | + RuntimeError: If AI API call fails |
| 111 | + """ |
| 112 | + client = _get_claude_client() |
| 113 | + |
| 114 | + prompt = f"""You are the Codebase Agent for {repo_name}. |
| 115 | +
|
| 116 | +{AGENT_CONTEXT} |
| 117 | +
|
| 118 | +--- |
| 119 | +
|
| 120 | +**Current Task**: |
| 121 | +Command: {command} |
| 122 | +Context: {url} |
| 123 | +
|
| 124 | +Provide a helpful, concise response following the operating principles above.""" |
| 125 | + |
| 126 | + try: |
| 127 | + message = client.messages.create( |
| 128 | + model="claude-sonnet-4-5-20250929", |
| 129 | + max_tokens=2000, |
| 130 | + messages=[{"role": "user", "content": prompt}], |
| 131 | + ) |
| 132 | + return message.content[0].text |
| 133 | + except Exception as e: |
| 134 | + raise RuntimeError(f"AI API error: {e}") |
| 135 | + |
| 136 | + |
| 137 | +def post_github_comment(repo: str, issue_number: int, body: str): |
| 138 | + """Post comment to GitHub issue/PR. |
| 139 | +
|
| 140 | + Args: |
| 141 | + repo: Repository name (owner/repo) |
| 142 | + issue_number: Issue or PR number |
| 143 | + body: Comment body text |
| 144 | +
|
| 145 | + Raises: |
| 146 | + requests.HTTPError: If GitHub API call fails |
| 147 | + """ |
| 148 | + token = os.environ.get("GITHUB_TOKEN") |
| 149 | + if not token: |
| 150 | + raise RuntimeError("GITHUB_TOKEN environment variable not set") |
| 151 | + |
| 152 | + url = f"https://api.github.com/repos/{repo}/issues/{issue_number}/comments" |
| 153 | + |
| 154 | + try: |
| 155 | + response = requests.post( |
| 156 | + url, |
| 157 | + headers={ |
| 158 | + "Authorization": f"token {token}", |
| 159 | + "Accept": "application/vnd.github.v3+json", |
| 160 | + }, |
| 161 | + json={"body": body}, |
| 162 | + timeout=30, |
| 163 | + ) |
| 164 | + response.raise_for_status() |
| 165 | + except requests.exceptions.RequestException as e: |
| 166 | + raise RuntimeError(f"GitHub API error: {e}") |
0 commit comments