|
4 | 4 | import hashlib |
5 | 5 | import logging |
6 | 6 | import os |
7 | | -from typing import Optional, cast, Tuple |
| 7 | +import re |
| 8 | +import requests |
| 9 | +from typing import Optional, cast, Tuple, Any, TypeVar, Literal |
8 | 10 |
|
9 | 11 | from langfuse.api import MediaContentType |
10 | 12 | from langfuse.types import ParsedMediaReference |
11 | 13 |
|
| 14 | +T = TypeVar("T") |
| 15 | + |
12 | 16 |
|
13 | 17 | class LangfuseMedia: |
14 | 18 | """A class for wrapping media objects for upload to Langfuse. |
@@ -201,3 +205,116 @@ def _parse_base64_data_uri( |
201 | 205 | self._log.error("Error parsing base64 data URI", exc_info=e) |
202 | 206 |
|
203 | 207 | return None, None |
| 208 | + |
| 209 | + @staticmethod |
| 210 | + def resolve_media_references( |
| 211 | + *, |
| 212 | + obj: T, |
| 213 | + langfuse_client: Any, |
| 214 | + resolve_with: Literal["base64_data_uri"], |
| 215 | + max_depth: int = 10, |
| 216 | + ) -> T: |
| 217 | + """Replace media reference strings in an object with base64 data URIs. |
| 218 | +
|
| 219 | + This method recursively traverses an object (up to max_depth) looking for media reference strings |
| 220 | + in the format "@@@langfuseMedia:...@@@". When found, it (synchronously) fetches the actual media content using |
| 221 | + the provided Langfuse client and replaces the reference string with a base64 data URI. |
| 222 | +
|
| 223 | + If fetching media content fails for a reference string, a warning is logged and the reference |
| 224 | + string is left unchanged. |
| 225 | +
|
| 226 | + Args: |
| 227 | + obj: The object to process. Can be a primitive value, array, or nested object. |
| 228 | + If the object has a __dict__ attribute, a dict will be returned instead of the original object type. |
| 229 | + langfuse_client: Langfuse client instance used to fetch media content. |
| 230 | + resolve_with: The representation of the media content to replace the media reference string with. |
| 231 | + Currently only "base64_data_uri" is supported. |
| 232 | + max_depth: Optional. Default is 10. The maximum depth to traverse the object. |
| 233 | +
|
| 234 | + Returns: |
| 235 | + A deep copy of the input object with all media references replaced with base64 data URIs where possible. |
| 236 | + If the input object has a __dict__ attribute, a dict will be returned instead of the original object type. |
| 237 | +
|
| 238 | + Example: |
| 239 | + obj = { |
| 240 | + "image": "@@@langfuseMedia:type=image/jpeg|id=123|source=bytes@@@", |
| 241 | + "nested": { |
| 242 | + "pdf": "@@@langfuseMedia:type=application/pdf|id=456|source=bytes@@@" |
| 243 | + } |
| 244 | + } |
| 245 | +
|
| 246 | + result = await LangfuseMedia.resolve_media_references(obj, langfuse_client) |
| 247 | +
|
| 248 | + # Result: |
| 249 | + # { |
| 250 | + # "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg...", |
| 251 | + # "nested": { |
| 252 | + # "pdf": "data:application/pdf;base64,JVBERi0xLjcK..." |
| 253 | + # } |
| 254 | + # } |
| 255 | + """ |
| 256 | + |
| 257 | + def traverse(obj: Any, depth: int) -> Any: |
| 258 | + if depth > max_depth: |
| 259 | + return obj |
| 260 | + |
| 261 | + # Handle string with potential media references |
| 262 | + if isinstance(obj, str): |
| 263 | + regex = r"@@@langfuseMedia:.+?@@@" |
| 264 | + reference_string_matches = re.findall(regex, obj) |
| 265 | + if len(reference_string_matches) == 0: |
| 266 | + return obj |
| 267 | + |
| 268 | + result = obj |
| 269 | + reference_string_to_media_content = {} |
| 270 | + |
| 271 | + for reference_string in reference_string_matches: |
| 272 | + try: |
| 273 | + parsed_media_reference = LangfuseMedia.parse_reference_string( |
| 274 | + reference_string |
| 275 | + ) |
| 276 | + media_data = langfuse_client.fetch_media( |
| 277 | + parsed_media_reference["media_id"] |
| 278 | + ) |
| 279 | + media_content = requests.get(media_data.url) |
| 280 | + if not media_content.ok: |
| 281 | + raise Exception("Failed to fetch media content") |
| 282 | + |
| 283 | + base64_media_content = base64.b64encode( |
| 284 | + media_content.content |
| 285 | + ).decode() |
| 286 | + base64_data_uri = f"data:{media_data.content_type};base64,{base64_media_content}" |
| 287 | + |
| 288 | + reference_string_to_media_content[reference_string] = ( |
| 289 | + base64_data_uri |
| 290 | + ) |
| 291 | + except Exception as e: |
| 292 | + logging.warning( |
| 293 | + f"Error fetching media content for reference string {reference_string}: {e}" |
| 294 | + ) |
| 295 | + # Do not replace the reference string if there's an error |
| 296 | + continue |
| 297 | + |
| 298 | + for ref_str, media_content in reference_string_to_media_content.items(): |
| 299 | + result = result.replace(ref_str, media_content) |
| 300 | + |
| 301 | + return result |
| 302 | + |
| 303 | + # Handle arrays |
| 304 | + if isinstance(obj, list): |
| 305 | + return [traverse(item, depth + 1) for item in obj] |
| 306 | + |
| 307 | + # Handle dictionaries |
| 308 | + if isinstance(obj, dict): |
| 309 | + return {key: traverse(value, depth + 1) for key, value in obj.items()} |
| 310 | + |
| 311 | + # Handle objects: |
| 312 | + if hasattr(obj, "__dict__"): |
| 313 | + return { |
| 314 | + key: traverse(value, depth + 1) |
| 315 | + for key, value in obj.__dict__.items() |
| 316 | + } |
| 317 | + |
| 318 | + return obj |
| 319 | + |
| 320 | + return traverse(obj, 0) |
0 commit comments