-
Notifications
You must be signed in to change notification settings - Fork 1.7k
integrate anthropic as LLM provider #501
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
DanielDCM212
wants to merge
3
commits into
AsyncFuncAI:main
Choose a base branch
from
DanielDCM212:feature/implemented-anthropic-as-provider
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
3 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| """Anthropic Claude ModelClient integration.""" | ||
|
|
||
| import os | ||
| import logging | ||
| import re | ||
| from typing import Dict, Optional, Any | ||
|
|
||
| from adalflow.core.model_client import ModelClient | ||
| from adalflow.core.types import ModelType, GeneratorOutput, CompletionUsage | ||
|
|
||
| log = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class AnthropicClient(ModelClient): | ||
| """AdalFlow ModelClient wrapper for the Anthropic Messages API.""" | ||
|
|
||
| def __init__(self, api_key: Optional[str] = None): | ||
| super().__init__() | ||
| self._api_key = api_key or os.getenv("ANTHROPIC_API_KEY") | ||
| if not self._api_key: | ||
| raise ValueError("ANTHROPIC_API_KEY environment variable must be set") | ||
| self.sync_client = self._init_client() | ||
| self._async_client = None | ||
|
|
||
| def _init_client(self): | ||
| import anthropic | ||
| return anthropic.Anthropic(api_key=self._api_key) | ||
|
|
||
| def convert_inputs_to_api_kwargs( | ||
| self, | ||
| input: Optional[Any] = None, | ||
| model_kwargs: Dict = {}, | ||
| model_type: ModelType = ModelType.UNDEFINED, | ||
| ) -> Dict: | ||
| if model_type != ModelType.LLM: | ||
| raise ValueError(f"AnthropicClient only supports LLM model type, got {model_type}") | ||
|
|
||
| kwargs = model_kwargs.copy() | ||
| kwargs.setdefault("max_tokens", 8096) | ||
|
|
||
| # Split system prompt from user content if AdalFlow injected the tags | ||
| system_tag_start = "<START_OF_SYSTEM_PROMPT>" | ||
| system_tag_end = "<END_OF_SYSTEM_PROMPT>" | ||
| user_tag_start = "<START_OF_USER_PROMPT>" | ||
| user_tag_end = "<END_OF_USER_PROMPT>" | ||
|
|
||
| system_prompt = None | ||
| user_content = input | ||
|
|
||
| if isinstance(input, str) and system_tag_start in input: | ||
| pattern = ( | ||
| rf"{system_tag_start}\s*(.*?)\s*{system_tag_end}\s*" | ||
| rf"{user_tag_start}\s*(.*?)\s*{user_tag_end}" | ||
| ) | ||
| match = re.search(pattern, input, re.DOTALL) | ||
| if match: | ||
| system_prompt = match.group(1).strip() | ||
| user_content = match.group(2).strip() | ||
|
|
||
| kwargs["messages"] = [{"role": "user", "content": user_content}] | ||
| if system_prompt: | ||
| kwargs["system"] = system_prompt | ||
|
|
||
| return kwargs | ||
|
|
||
| def parse_chat_completion(self, completion) -> GeneratorOutput: | ||
| try: | ||
| content = completion.content[0].text | ||
| usage = CompletionUsage( | ||
| prompt_tokens=completion.usage.input_tokens, | ||
| completion_tokens=completion.usage.output_tokens, | ||
| total_tokens=completion.usage.input_tokens + completion.usage.output_tokens, | ||
| ) | ||
| return GeneratorOutput(data=None, error=None, raw_response=content, usage=usage) | ||
| except Exception as e: | ||
| log.error(f"Error parsing Anthropic completion: {e}") | ||
| return GeneratorOutput(data=None, error=str(e), raw_response=str(completion)) | ||
|
|
||
| def call(self, api_kwargs: Dict = {}, model_type: ModelType = ModelType.UNDEFINED): | ||
| if model_type != ModelType.LLM: | ||
| raise ValueError(f"AnthropicClient only supports LLM, got {model_type}") | ||
|
|
||
| api_kwargs.pop("stream", None) # Anthropic streaming not used in sync path | ||
| return self.sync_client.messages.create(**api_kwargs) | ||
|
|
||
| async def acall(self, api_kwargs: Dict = {}, model_type: ModelType = ModelType.UNDEFINED): | ||
| if model_type != ModelType.LLM: | ||
| raise ValueError(f"AnthropicClient only supports LLM, got {model_type}") | ||
| if self._async_client is None: | ||
| import anthropic | ||
| self._async_client = anthropic.AsyncAnthropic(api_key=self._api_key) | ||
| return await self._async_client.messages.create(**api_kwargs) | ||
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The regex for splitting system and user prompts is quite fragile. It expects a very specific sequence of tags and whitespace. If the input string contains the system tag but doesn't match this exact pattern (e.g., if there is text before
<START_OF_SYSTEM_PROMPT>or if the user tags are missing), the match will fail. Consequently,system_promptwill remainNoneand the entire input (including the tags) will be sent as the user message. Consider using a more flexible parsing approach to extract the system and user parts independently.