-
Notifications
You must be signed in to change notification settings - Fork 1.4k
feat: add native Groq model integration for high-speed evaluations #2556
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
Jayachander123
wants to merge
5
commits into
confident-ai:main
Choose a base branch
from
Jayachander123:add-groq-integration
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 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
dc6df25
feat: add native Groq model integration for high-speed evaluations
Jayachander123 cde025c
refactor: address reviewer comments for Groq integration
Jayachander123 5e96919
docs: add comprehensive documentation for Groq model integration
Jayachander123 1d85b51
refactor: implement cost tracking, generation_kwargs, and remove env …
Jayachander123 a1b219f
chore: merge upstream main and resolve conflicts
Jayachander123 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
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
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,221 @@ | ||
| import os | ||
| from pydantic import BaseModel, SecretStr | ||
| from typing import TYPE_CHECKING, Optional, Tuple, Union | ||
|
|
||
| from deepeval.errors import DeepEvalError | ||
| from deepeval.config.settings import get_settings | ||
| from deepeval.models.utils import require_secret_api_key | ||
| from deepeval.models.retry_policy import create_retry_decorator | ||
| from deepeval.utils import require_dependency | ||
| from deepeval.models.base_model import DeepEvalBaseLLM | ||
| from deepeval.constants import ProviderSlug | ||
| from deepeval.models.llms.constants import GROQ_MODELS_DATA, make_model_data | ||
|
|
||
| if TYPE_CHECKING: | ||
| from groq import Groq, AsyncGroq | ||
|
|
||
| # ----------------------------------------------------------------------------- | ||
| # Constants & Defaults | ||
| # ----------------------------------------------------------------------------- | ||
| default_groq_model = "llama3-8b-8192" | ||
|
|
||
| # Use a standard string for the retry decorator if ProviderSlug.GROQ doesn't exist yet | ||
| retry_groq = create_retry_decorator(ProviderSlug.GROQ) | ||
|
|
||
|
|
||
| # ----------------------------------------------------------------------------- | ||
| # Model Implementation | ||
| # ----------------------------------------------------------------------------- | ||
| class GroqModel(DeepEvalBaseLLM): | ||
| """Class that implements Groq's LPU inference engine for high-speed evaluation. | ||
|
|
||
| This class provides native integration with Groq's ultra-fast API, supporting | ||
| both text generation and structured JSON outputs using Pydantic schemas. | ||
|
|
||
| Attributes: | ||
| model: Name of the Groq model to use (e.g., 'llama3-8b-8192', 'mixtral-8x7b-32768') | ||
| api_key: Groq API key for authentication | ||
| temperature: Sampling temperature for generation | ||
|
|
||
| Example: | ||
| ```python | ||
| from deepeval.models import GroqModel | ||
|
|
||
| # Initialize the model | ||
| model = GroqModel( | ||
| model="llama3-70b-8192", | ||
| api_key="gsk_..." | ||
| ) | ||
|
|
||
| # Generate text | ||
| response = model.generate("What is the capital of France?") | ||
| ``` | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| model: Optional[str] = None, | ||
| api_key: Optional[str] = None, | ||
| temperature: Optional[float] = None, | ||
| **kwargs, | ||
| ): | ||
| settings = get_settings() | ||
| self.model_name = model or default_groq_model | ||
|
|
||
| # Secure API Key handling: Check params -> Settings -> Environment | ||
| if api_key is not None: | ||
| self.api_key = ( | ||
| api_key | ||
| if isinstance(api_key, SecretStr) | ||
| else SecretStr(api_key) | ||
| ) | ||
| else: | ||
| env_key = getattr(settings, "GROQ_API_KEY", None) or os.environ.get( | ||
| "GROQ_API_KEY" | ||
| ) | ||
| self.api_key = ( | ||
| env_key | ||
| if isinstance(env_key, SecretStr) | ||
| else (SecretStr(env_key) if env_key else None) | ||
| ) | ||
|
|
||
| # Temperature handling | ||
| if temperature is not None: | ||
| self.temperature = float(temperature) | ||
| elif settings.TEMPERATURE is not None: | ||
| self.temperature = settings.TEMPERATURE | ||
| else: | ||
| self.temperature = 0.0 | ||
|
|
||
| if self.temperature < 0: | ||
| raise DeepEvalError("Temperature must be >= 0.") | ||
|
|
||
| self.kwargs = kwargs | ||
| self.model_data = GROQ_MODELS_DATA.get( | ||
| self.model_name, | ||
| make_model_data( | ||
| supports_log_probs=False, | ||
| supports_multimodal=False, | ||
| supports_structured_outputs=True, | ||
| supports_json=True, | ||
| input_price=None, | ||
| output_price=None, | ||
| ), | ||
| ) | ||
| self._module = self._require_module() | ||
|
|
||
| # Client caching for performance optimization | ||
| self._client: Optional["Groq"] = None | ||
| self._async_client: Optional["AsyncGroq"] = None | ||
| super().__init__(self.model_name) | ||
|
|
||
| def _require_module(self): | ||
| """Lazy loads the groq library to prevent import errors for non-Groq users.""" | ||
| return require_dependency( | ||
| "groq", | ||
| provider_label="GroqModel", | ||
| install_hint="Install it with `pip install groq`.", | ||
| ) | ||
|
|
||
| def load_model(self, async_mode: bool = False): | ||
| """Initializes and caches the Groq client.""" | ||
| if async_mode: | ||
| if self._async_client is not None: | ||
| return self._async_client | ||
| else: | ||
| if self._client is not None: | ||
| return self._client | ||
|
|
||
| api_key = require_secret_api_key( | ||
| self.api_key, | ||
| provider_label="Groq", | ||
| env_var_name="GROQ_API_KEY", | ||
| param_hint="`api_key` to GroqModel(...)", | ||
| ) | ||
|
|
||
| if hasattr(api_key, "get_secret_value"): | ||
| api_key = api_key.get_secret_value() | ||
|
|
||
| if async_mode: | ||
| self._async_client = self._module.AsyncGroq( | ||
| api_key=api_key, **self.kwargs | ||
| ) | ||
| return self._async_client | ||
| else: | ||
| self._client = self._module.Groq(api_key=api_key, **self.kwargs) | ||
| return self._client | ||
|
|
||
| # ------------------------------------------------------------------------- | ||
| # Generation Methods | ||
| # ------------------------------------------------------------------------- | ||
| @retry_groq | ||
| def generate( | ||
| self, prompt: str, schema: Optional[BaseModel] = None | ||
| ) -> Tuple[Union[str, BaseModel], float]: | ||
| """Generates text or structured output from a prompt.""" | ||
| client = self.load_model(async_mode=False) | ||
|
|
||
| chat_args = { | ||
| "model": self.model_name, | ||
| "messages": [{"role": "user", "content": prompt}], | ||
| "temperature": self.temperature, | ||
| } | ||
|
|
||
| if schema is not None: | ||
| chat_args["response_format"] = {"type": "json_object"} | ||
|
|
||
| response = client.chat.completions.create(**chat_args) | ||
| content = response.choices[0].message.content | ||
|
|
||
| if schema is not None: | ||
| return schema.model_validate_json(content), 0.0 | ||
|
|
||
| return content, 0.0 | ||
|
|
||
| @retry_groq | ||
| async def a_generate( | ||
| self, prompt: str, schema: Optional[BaseModel] = None | ||
| ) -> Tuple[Union[str, BaseModel], float]: | ||
| """Asynchronously generates text or structured output from a prompt.""" | ||
| async_client = self.load_model(async_mode=True) | ||
|
|
||
| chat_args = { | ||
| "model": self.model_name, | ||
| "messages": [{"role": "user", "content": prompt}], | ||
| "temperature": self.temperature, | ||
| } | ||
|
|
||
| if schema is not None: | ||
| chat_args["response_format"] = {"type": "json_object"} | ||
|
|
||
| response = await async_client.chat.completions.create(**chat_args) | ||
| content = response.choices[0].message.content | ||
|
|
||
| if schema is not None: | ||
| return schema.model_validate_json(content), 0.0 | ||
|
|
||
| return content, 0.0 | ||
|
|
||
| # ------------------------------------------------------------------------- | ||
| # Capabilities | ||
| # ------------------------------------------------------------------------- | ||
|
|
||
| def supports_log_probs(self) -> Union[bool, None]: | ||
| return self.model_data.supports_log_probs | ||
|
|
||
| def supports_temperature(self) -> Union[bool, None]: | ||
| # Uses getattr fallback because supports_temperature is not in make_model_data | ||
| return getattr(self.model_data, "supports_temperature", True) | ||
|
|
||
| def supports_multimodal(self) -> Union[bool, None]: | ||
| return self.model_data.supports_multimodal | ||
|
|
||
| def supports_structured_outputs(self) -> Union[bool, None]: | ||
| return self.model_data.supports_structured_outputs | ||
|
|
||
| def supports_json_mode(self) -> Union[bool, None]: | ||
| # Note: The property on make_model_data is called 'supports_json' | ||
| return self.model_data.supports_json | ||
|
|
||
| def get_model_name(self) -> str: | ||
| return f"{self.name} (Groq)" | ||
Oops, something went wrong.
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.
For the
generateanda_generatemethod, if you look at the other model examples, we have a way to support images inside them as well, an example for this is here: https://github.com/confident-ai/deepeval/blob/main/deepeval/models/llms/openai_model.py#L154I've looked through the official docs to see how to pass images, you can see them here: https://console.groq.com/docs/vision#how-to-pass-images-from-urls-as-input
It looks like the API is mostly similar to openai so the above shared example should help you implement this, don't worry about supporting images if it's too hard, you can safely ignore this comment :)
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.
Thank you for sharing the Groq vision docs! I will safely ignore this one for now just to keep this initial integration focused and stable, but we can definitely add multimodal support in a future PR.