-
Notifications
You must be signed in to change notification settings - Fork 2
feat: add Anthropic SDK evaluator (#11) #19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
don-petry
wants to merge
4
commits into
Joaolfelicio:main
Choose a base branch
from
don-petry:feat/anthropic-sdk-evaluator
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
a4b3052
feat: add Anthropic SDK evaluator as alternative to CLI subprocess
2fe4fe3
fix: address review feedback on Anthropic SDK evaluator
2d12d75
fix: update test_daemons.py to patch get_evaluator factory
628dd8b
fix: address second round of review feedback
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| import logging | ||
| import os | ||
|
|
||
| import anthropic | ||
|
|
||
| from context_scribe.evaluator.base_evaluator import BaseEvaluator | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class AnthropicEvaluator(BaseEvaluator): | ||
| """Evaluator that uses the Anthropic SDK directly for rule extraction. | ||
|
|
||
| Requires the ANTHROPIC_API_KEY environment variable to be set. | ||
| Uses claude-haiku by default for cost efficiency. | ||
| """ | ||
|
|
||
| def __init__(self, model: str = "claude-haiku-4-5-20251001"): | ||
| super().__init__() | ||
|
|
||
| api_key = os.environ.get("ANTHROPIC_API_KEY") | ||
| if not api_key: | ||
| raise ValueError( | ||
| "ANTHROPIC_API_KEY environment variable is required for AnthropicEvaluator." | ||
| ) | ||
|
|
||
| self._client = anthropic.Anthropic(api_key=api_key, timeout=120.0) | ||
| self._model = model | ||
|
|
||
| def _execute_cli(self, prompt: str) -> str: | ||
| """Call the Anthropic API instead of a CLI subprocess.""" | ||
| message = self._client.messages.create( | ||
| model=self._model, | ||
| max_tokens=4096, | ||
| messages=[{"role": "user", "content": prompt}], | ||
| ) | ||
don-petry marked this conversation as resolved.
Show resolved
Hide resolved
don-petry marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # Extract text from the response content blocks | ||
| return "".join( | ||
| block.text for block in message.content if block.type == "text" | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| import json | ||
| import sys | ||
| from unittest.mock import MagicMock, patch | ||
|
|
||
| import pytest | ||
|
|
||
| from context_scribe.models.interaction import Interaction | ||
| from datetime import datetime | ||
|
|
||
|
|
||
| def _make_interaction(content="I prefer tabs over spaces"): | ||
| return Interaction( | ||
| timestamp=datetime.now(), | ||
| role="user", | ||
| content=content, | ||
| project_name="test-project", | ||
| metadata={}, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_anthropic(): | ||
| """Mock the anthropic SDK at sys.modules level, then import AnthropicEvaluator.""" | ||
| mock_module = MagicMock() | ||
| mock_client = MagicMock() | ||
| mock_module.Anthropic.return_value = mock_client | ||
|
|
||
| with patch.dict(sys.modules, {"anthropic": mock_module}): | ||
| with patch.dict("os.environ", {"ANTHROPIC_API_KEY": "test-key"}): | ||
| # Force re-import so the module picks up our mock | ||
| if "context_scribe.evaluator.anthropic_llm" in sys.modules: | ||
| del sys.modules["context_scribe.evaluator.anthropic_llm"] | ||
| from context_scribe.evaluator.anthropic_llm import AnthropicEvaluator | ||
| evaluator = AnthropicEvaluator() | ||
| yield evaluator, mock_client | ||
|
|
||
|
|
||
| def test_anthropic_evaluator_extracts_rule(mock_anthropic): | ||
| evaluator, mock_client = mock_anthropic | ||
| rule_json = json.dumps({ | ||
| "scope": "GLOBAL", | ||
| "description": "Indentation preference", | ||
| "rules": ["- Use tabs for indentation"], | ||
| }) | ||
| text_block = MagicMock() | ||
| text_block.type = "text" | ||
| text_block.text = rule_json | ||
| mock_client.messages.create.return_value = MagicMock(content=[text_block]) | ||
|
|
||
| result = evaluator.evaluate_interaction(_make_interaction(), "", "") | ||
| assert result is not None | ||
| assert result.scope == "GLOBAL" | ||
| assert "tabs" in result.content | ||
|
|
||
|
|
||
| def test_anthropic_evaluator_returns_none_for_no_rule(mock_anthropic): | ||
| evaluator, mock_client = mock_anthropic | ||
| text_block = MagicMock() | ||
| text_block.type = "text" | ||
| text_block.text = "NO_RULE" | ||
| mock_client.messages.create.return_value = MagicMock(content=[text_block]) | ||
|
|
||
| result = evaluator.evaluate_interaction(_make_interaction("hello"), "", "") | ||
| assert result is None | ||
|
|
||
|
|
||
| def test_anthropic_evaluator_passes_correct_model(mock_anthropic): | ||
| evaluator, mock_client = mock_anthropic | ||
| text_block = MagicMock() | ||
| text_block.type = "text" | ||
| text_block.text = "NO_RULE" | ||
| mock_client.messages.create.return_value = MagicMock(content=[text_block]) | ||
|
|
||
| evaluator.evaluate_interaction(_make_interaction(), "", "") | ||
| call_kwargs = mock_client.messages.create.call_args[1] | ||
| assert call_kwargs["model"] == "claude-haiku-4-5-20251001" | ||
| assert call_kwargs["max_tokens"] == 4096 | ||
|
|
||
|
|
||
| def test_anthropic_evaluator_missing_api_key(): | ||
| mock_module = MagicMock() | ||
| with patch.dict(sys.modules, {"anthropic": mock_module}): | ||
| with patch.dict("os.environ", {}, clear=True): | ||
| if "context_scribe.evaluator.anthropic_llm" in sys.modules: | ||
| del sys.modules["context_scribe.evaluator.anthropic_llm"] | ||
| from context_scribe.evaluator.anthropic_llm import AnthropicEvaluator | ||
| with pytest.raises(ValueError, match="ANTHROPIC_API_KEY"): | ||
| AnthropicEvaluator() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.