-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Prompt class + implementation in Context Precision #2428
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
rhlbhatnagar
wants to merge
1
commit into
explodinggradients:main
Choose a base branch
from
rhlbhatnagar:rbhatnagar/class_based_prmpts_context_precisiong
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.
+240
−126
Open
Changes from all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| """Base prompt class for metrics with structured input/output models.""" | ||
|
|
||
| import json | ||
| import typing as t | ||
| from abc import ABC | ||
|
|
||
| from pydantic import BaseModel | ||
|
|
||
| # Type variables for generics | ||
| InputModel = t.TypeVar("InputModel", bound=BaseModel) | ||
| OutputModel = t.TypeVar("OutputModel", bound=BaseModel) | ||
|
|
||
|
|
||
| class BasePrompt(ABC, t.Generic[InputModel, OutputModel]): | ||
| """ | ||
| Base class for structured prompts with type-safe input/output models. | ||
|
|
||
| Attributes: | ||
| input_model: Pydantic model class for input validation | ||
| output_model: Pydantic model class for output schema generation | ||
| instruction: Task description for the LLM | ||
| examples: List of (input, output) example pairs for few-shot learning | ||
| language: Language for the prompt (default: "english") | ||
| """ | ||
|
|
||
| # Must be set by subclasses | ||
| input_model: t.Type[InputModel] | ||
| output_model: t.Type[OutputModel] | ||
| instruction: str | ||
| examples: t.List[t.Tuple[InputModel, OutputModel]] | ||
| language: str = "english" | ||
|
|
||
| def to_string(self, data: InputModel) -> str: | ||
| """ | ||
| Convert prompt with input data to complete prompt string for LLM. | ||
|
|
||
| Args: | ||
| data: Input data instance (validated by input_model) | ||
|
|
||
| Returns: | ||
| Complete prompt string ready for LLM | ||
| """ | ||
| # Generate JSON schema for output | ||
| output_schema = json.dumps(self.output_model.model_json_schema()) | ||
|
|
||
| # Generate examples section | ||
| examples_str = self._generate_examples() | ||
|
|
||
| # Convert input data to JSON | ||
| input_json = data.model_dump_json(indent=4, exclude_none=True) | ||
|
|
||
| # Build complete prompt (matches existing function format) | ||
| return f"""{self.instruction} | ||
| Please return the output in a JSON format that complies with the following schema as specified in JSON Schema: | ||
| {output_schema}Do not use single quotes in your response but double quotes,properly escaped with a backslash. | ||
|
|
||
| {examples_str} | ||
| ----------------------------- | ||
|
|
||
| Now perform the same with the following input | ||
| input: {input_json} | ||
| Output: """ | ||
|
|
||
| def _generate_examples(self) -> str: | ||
| """ | ||
| Generate examples section of the prompt. | ||
|
|
||
| Returns: | ||
| Formatted examples string or empty string if no examples | ||
| """ | ||
| if not self.examples: | ||
| return "" | ||
|
|
||
| example_strings = [] | ||
| for idx, (input_data, output_data) in enumerate(self.examples): | ||
| example_strings.append( | ||
| f"Example {idx + 1}\n" | ||
| f"Input: {input_data.model_dump_json(indent=4)}\n" | ||
| f"Output: {output_data.model_dump_json(indent=4)}" | ||
| ) | ||
|
|
||
| return "--------EXAMPLES-----------\n" + "\n\n".join(example_strings) | ||
|
|
||
| async def adapt( | ||
| self, | ||
| target_language: str, | ||
| llm, | ||
| adapt_instruction: bool = False, | ||
| ) -> "BasePrompt[InputModel, OutputModel]": | ||
| """ | ||
| Adapt the prompt to a new language using minimal translation. | ||
|
|
||
| Args: | ||
| target_language: Target language (e.g., "spanish", "french") | ||
| llm: LLM instance for translation | ||
| adapt_instruction: Whether to adapt instruction text (default: False) | ||
|
|
||
| Returns: | ||
| New prompt instance adapted to the target language | ||
| """ | ||
| import copy | ||
|
|
||
| # Create adapted prompt | ||
| new_prompt = copy.deepcopy(self) | ||
| new_prompt.language = target_language | ||
|
|
||
| # Translate instruction if requested | ||
| if adapt_instruction: | ||
| instruction_prompt = f"Translate this to {target_language}, keep technical terms: {self.instruction}" | ||
| try: | ||
| response = await llm.agenerate(instruction_prompt) | ||
| new_prompt.instruction = str(response).strip() | ||
| except Exception: | ||
| # Keep original if translation fails | ||
| pass | ||
|
|
||
| # Translate examples (simplified approach) | ||
| translated_examples = [] | ||
| for input_ex, output_ex in self.examples: | ||
| try: | ||
| # Simple per-example translation | ||
| example_prompt = f"""Translate this example to {target_language}, keep the same structure: | ||
|
|
||
| Input: {input_ex.model_dump_json()} | ||
| Output: {output_ex.model_dump_json()} | ||
|
|
||
| Return as: Input: {{translated_input_json}} Output: {{translated_output_json}}""" | ||
|
|
||
| response = await llm.agenerate(example_prompt) | ||
|
|
||
| # Try to extract translated JSON (basic parsing) | ||
| response_str = str(response) | ||
| if "Input:" in response_str and "Output:" in response_str: | ||
| parts = response_str.split("Output:") | ||
| input_part = parts[0].replace("Input:", "").strip() | ||
| output_part = parts[1].strip() | ||
|
|
||
| translated_input = self.input_model.model_validate_json(input_part) | ||
| translated_output = self.output_model.model_validate_json( | ||
| output_part | ||
| ) | ||
| translated_examples.append((translated_input, translated_output)) | ||
| else: | ||
| # Fallback to original | ||
| translated_examples.append((input_ex, output_ex)) | ||
|
|
||
| except Exception: | ||
| # Fallback to original example if translation fails | ||
| translated_examples.append((input_ex, output_ex)) | ||
|
|
||
| new_prompt.examples = translated_examples | ||
| return new_prompt | ||
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.
Do we return a new prompt? Or should we replace the existing one.