-
Notifications
You must be signed in to change notification settings - Fork 223
feat(prompts): add util for variable name extraction #1046
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
Merged
Merged
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,7 @@ | ||
| """@private""" | ||
|
|
||
| from abc import ABC, abstractmethod | ||
| from typing import Optional, TypedDict, Any, Dict, Union, List | ||
| from typing import Optional, TypedDict, Any, Dict, Union, List, Tuple | ||
| import re | ||
|
|
||
| from langfuse.api.resources.commons.types.dataset import ( | ||
|
|
@@ -54,6 +54,72 @@ class ChatMessageDict(TypedDict): | |
| content: str | ||
|
|
||
|
|
||
| class TemplateParser: | ||
| OPENING = "{{" | ||
| CLOSING = "}}" | ||
|
|
||
| @staticmethod | ||
| def _parse_next_variable( | ||
| content: str, start_idx: int | ||
| ) -> Optional[Tuple[str, int, int]]: | ||
| """Returns (variable_name, start_pos, end_pos) or None if no variable found""" | ||
| var_start = content.find(TemplateParser.OPENING, start_idx) | ||
| if var_start == -1: | ||
| return None | ||
|
|
||
| var_end = content.find(TemplateParser.CLOSING, var_start) | ||
| if var_end == -1: | ||
| return None | ||
|
|
||
| variable_name = content[ | ||
| var_start + len(TemplateParser.OPENING) : var_end | ||
| ].strip() | ||
| return (variable_name, var_start, var_end + len(TemplateParser.CLOSING)) | ||
|
|
||
| @staticmethod | ||
| def find_variable_names(content: str) -> List[str]: | ||
| names = [] | ||
| curr_idx = 0 | ||
|
|
||
| while curr_idx < len(content): | ||
| result = TemplateParser._parse_next_variable(content, curr_idx) | ||
| if not result: | ||
| break | ||
| names.append(result[0]) | ||
| curr_idx = result[2] | ||
|
|
||
| return names | ||
|
|
||
| @staticmethod | ||
| def compile_template(content: str, data: Optional[Dict[str, Any]] = None) -> str: | ||
| if data is None: | ||
| return content | ||
|
|
||
| result_list = [] | ||
| curr_idx = 0 | ||
|
|
||
| while curr_idx < len(content): | ||
| result = TemplateParser._parse_next_variable(content, curr_idx) | ||
|
|
||
| if not result: | ||
| result_list.append(content[curr_idx:]) | ||
| break | ||
|
|
||
| variable_name, var_start, var_end = result | ||
| result_list.append(content[curr_idx:var_start]) | ||
|
|
||
| if variable_name in data: | ||
| result_list.append( | ||
| str(data[variable_name]) if data[variable_name] is not None else "" | ||
| ) | ||
| else: | ||
| result_list.append(content[var_start:var_end]) | ||
|
|
||
| curr_idx = var_end | ||
|
|
||
| return "".join(result_list) | ||
|
|
||
|
|
||
| class BasePromptClient(ABC): | ||
| name: str | ||
| version: int | ||
|
|
@@ -73,6 +139,11 @@ def __init__(self, prompt: Prompt, is_fallback: bool = False): | |
| def compile(self, **kwargs) -> Union[str, List[ChatMessage]]: | ||
| pass | ||
|
|
||
| @property | ||
| @abstractmethod | ||
| def variables(self) -> List[str]: | ||
| pass | ||
|
|
||
| @abstractmethod | ||
| def __eq__(self, other): | ||
| pass | ||
|
|
@@ -85,55 +156,19 @@ def get_langchain_prompt(self): | |
| def _get_langchain_prompt_string(content: str): | ||
| return re.sub(r"{{\s*(\w+)\s*}}", r"{\g<1>}", content) | ||
|
Comment on lines
156
to
157
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. logic: regex pattern \w+ only matches word chars - may need to support other valid variable name chars |
||
|
|
||
| @staticmethod | ||
| def _compile_template_string(content: str, data: Dict[str, Any] = {}) -> str: | ||
| opening = "{{" | ||
| closing = "}}" | ||
|
|
||
| result_list = [] | ||
| curr_idx = 0 | ||
|
|
||
| while curr_idx < len(content): | ||
| # Find the next opening tag | ||
| var_start = content.find(opening, curr_idx) | ||
|
|
||
| if var_start == -1: | ||
| result_list.append(content[curr_idx:]) | ||
| break | ||
|
|
||
| # Find the next closing tag | ||
| var_end = content.find(closing, var_start) | ||
|
|
||
| if var_end == -1: | ||
| result_list.append(content[curr_idx:]) | ||
| break | ||
|
|
||
| # Append the content before the variable | ||
| result_list.append(content[curr_idx:var_start]) | ||
|
|
||
| # Extract the variable name | ||
| variable_name = content[var_start + len(opening) : var_end].strip() | ||
|
|
||
| # Append the variable value | ||
| if variable_name in data: | ||
| result_list.append( | ||
| str(data[variable_name]) if data[variable_name] is not None else "" | ||
| ) | ||
| else: | ||
| result_list.append(content[var_start : var_end + len(closing)]) | ||
|
|
||
| curr_idx = var_end + len(closing) | ||
|
|
||
| return "".join(result_list) | ||
|
|
||
|
|
||
| class TextPromptClient(BasePromptClient): | ||
| def __init__(self, prompt: Prompt_Text, is_fallback: bool = False): | ||
| super().__init__(prompt, is_fallback) | ||
| self.prompt = prompt.prompt | ||
|
|
||
| def compile(self, **kwargs) -> str: | ||
| return self._compile_template_string(self.prompt, kwargs) | ||
| return TemplateParser.compile_template(self.prompt, kwargs) | ||
|
|
||
| @property | ||
| def variables(self) -> List[str]: | ||
| """Return all the variable names in the prompt template.""" | ||
| return TemplateParser.find_variable_names(self.prompt) | ||
|
|
||
| def __eq__(self, other): | ||
| if isinstance(self, other.__class__): | ||
|
|
@@ -160,7 +195,7 @@ def get_langchain_prompt(self, **kwargs) -> str: | |
| str: The string that can be plugged into Langchain's PromptTemplate. | ||
| """ | ||
| prompt = ( | ||
| self._compile_template_string(self.prompt, kwargs) | ||
| TemplateParser.compile_template(self.prompt, kwargs) | ||
| if kwargs | ||
| else self.prompt | ||
| ) | ||
|
|
@@ -178,12 +213,23 @@ def __init__(self, prompt: Prompt_Chat, is_fallback: bool = False): | |
| def compile(self, **kwargs) -> List[ChatMessageDict]: | ||
| return [ | ||
| ChatMessageDict( | ||
| content=self._compile_template_string(chat_message["content"], kwargs), | ||
| content=TemplateParser.compile_template( | ||
| chat_message["content"], kwargs | ||
| ), | ||
| role=chat_message["role"], | ||
| ) | ||
| for chat_message in self.prompt | ||
| ] | ||
|
|
||
| @property | ||
| def variables(self) -> List[str]: | ||
| """Return all the variable names in the chat prompt template.""" | ||
| return [ | ||
| variable | ||
| for chat_message in self.prompt | ||
| for variable in TemplateParser.find_variable_names(chat_message["content"]) | ||
| ] | ||
|
|
||
| def __eq__(self, other): | ||
| if isinstance(self, other.__class__): | ||
| return ( | ||
|
|
@@ -215,7 +261,7 @@ def get_langchain_prompt(self, **kwargs): | |
| ( | ||
| msg["role"], | ||
| self._get_langchain_prompt_string( | ||
| self._compile_template_string(msg["content"], kwargs) | ||
| TemplateParser.compile_template(msg["content"], kwargs) | ||
| if kwargs | ||
| else msg["content"] | ||
| ), | ||
|
|
||
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.
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.
Uh oh!
There was an error while loading. Please reload this page.