-
Notifications
You must be signed in to change notification settings - Fork 223
feat(media): utility to resolve media references with media content #1036
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
Show all changes
5 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
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 |
|---|---|---|
|
|
@@ -4,11 +4,15 @@ | |
| import hashlib | ||
| import logging | ||
| import os | ||
| from typing import Optional, cast, Tuple | ||
| import re | ||
| import requests | ||
| from typing import Optional, cast, Tuple, Any, TypeVar, Literal | ||
|
|
||
| from langfuse.api import MediaContentType | ||
| from langfuse.types import ParsedMediaReference | ||
|
|
||
| T = TypeVar("T") | ||
|
|
||
|
|
||
| class LangfuseMedia: | ||
| """A class for wrapping media objects for upload to Langfuse. | ||
|
|
@@ -201,3 +205,116 @@ def _parse_base64_data_uri( | |
| self._log.error("Error parsing base64 data URI", exc_info=e) | ||
|
|
||
| return None, None | ||
|
|
||
| @staticmethod | ||
| def resolve_media_references( | ||
| *, | ||
| obj: T, | ||
| langfuse_client: Any, | ||
| resolve_with: Literal["base64_data_uri"], | ||
| max_depth: int = 10, | ||
| ) -> T: | ||
| """Replace media reference strings in an object with base64 data URIs. | ||
|
|
||
| This method recursively traverses an object (up to max_depth) looking for media reference strings | ||
| in the format "@@@langfuseMedia:...@@@". When found, it (synchronously) fetches the actual media content using | ||
| the provided Langfuse client and replaces the reference string with a base64 data URI. | ||
|
|
||
| If fetching media content fails for a reference string, a warning is logged and the reference | ||
| string is left unchanged. | ||
|
|
||
| Args: | ||
| obj: The object to process. Can be a primitive value, array, or nested object. | ||
| If the object has a __dict__ attribute, a dict will be returned instead of the original object type. | ||
| langfuse_client: Langfuse client instance used to fetch media content. | ||
| resolve_with: The representation of the media content to replace the media reference string with. | ||
| Currently only "base64_data_uri" is supported. | ||
| max_depth: Optional. Default is 10. The maximum depth to traverse the object. | ||
|
|
||
| Returns: | ||
| A deep copy of the input object with all media references replaced with base64 data URIs where possible. | ||
| If the input object has a __dict__ attribute, a dict will be returned instead of the original object type. | ||
|
|
||
| Example: | ||
| obj = { | ||
| "image": "@@@langfuseMedia:type=image/jpeg|id=123|source=bytes@@@", | ||
| "nested": { | ||
| "pdf": "@@@langfuseMedia:type=application/pdf|id=456|source=bytes@@@" | ||
| } | ||
| } | ||
|
|
||
| result = await LangfuseMedia.resolve_media_references(obj, langfuse_client) | ||
|
|
||
| # Result: | ||
| # { | ||
| # "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg...", | ||
| # "nested": { | ||
| # "pdf": "data:application/pdf;base64,JVBERi0xLjcK..." | ||
| # } | ||
| # } | ||
| """ | ||
|
|
||
| def traverse(obj: Any, depth: int) -> Any: | ||
| if depth > max_depth: | ||
| return obj | ||
|
|
||
| # Handle string with potential media references | ||
| if isinstance(obj, str): | ||
| regex = r"@@@langfuseMedia:.+?@@@" | ||
|
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 .+? is greedy and could match more than intended. Use [^@]+ instead |
||
| reference_string_matches = re.findall(regex, obj) | ||
| if len(reference_string_matches) == 0: | ||
| return obj | ||
|
|
||
| result = obj | ||
| reference_string_to_media_content = {} | ||
|
|
||
| for reference_string in reference_string_matches: | ||
| try: | ||
| parsed_media_reference = LangfuseMedia.parse_reference_string( | ||
| reference_string | ||
| ) | ||
| media_data = langfuse_client.fetch_media( | ||
| parsed_media_reference["media_id"] | ||
| ) | ||
| media_content = requests.get(media_data.url) | ||
hassiebp marked this conversation as resolved.
Show resolved
Hide resolved
hassiebp marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if not media_content.ok: | ||
| raise Exception("Failed to fetch media content") | ||
|
|
||
| base64_media_content = base64.b64encode( | ||
| media_content.content | ||
| ).decode() | ||
| base64_data_uri = f"data:{media_data.content_type};base64,{base64_media_content}" | ||
|
|
||
| reference_string_to_media_content[reference_string] = ( | ||
| base64_data_uri | ||
| ) | ||
| except Exception as e: | ||
| logging.warning( | ||
hassiebp marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| f"Error fetching media content for reference string {reference_string}: {e}" | ||
| ) | ||
| # Do not replace the reference string if there's an error | ||
| continue | ||
|
|
||
| for ref_str, media_content in reference_string_to_media_content.items(): | ||
| result = result.replace(ref_str, media_content) | ||
|
|
||
| return result | ||
|
|
||
| # Handle arrays | ||
| if isinstance(obj, list): | ||
| return [traverse(item, depth + 1) for item in obj] | ||
|
|
||
| # Handle dictionaries | ||
| if isinstance(obj, dict): | ||
| return {key: traverse(value, depth + 1) for key, value in obj.items()} | ||
|
|
||
| # Handle objects: | ||
| if hasattr(obj, "__dict__"): | ||
| return { | ||
| key: traverse(value, depth + 1) | ||
| for key, value in obj.__dict__.items() | ||
| } | ||
|
|
||
| return obj | ||
|
|
||
| return traverse(obj, 0) | ||
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.
Uh oh!
There was an error while loading. Please reload this page.