repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
langfuse-python | github_2023 | python | 1,011 | langfuse | greptile-apps[bot] | @@ -220,7 +245,7 @@ def create(
Examples
--------
from finto import ChatMessage, CreatePromptRequest_Chat
- from finto.client import FernLangfuse
+ from langfuse.api.client import FernLangfuse | logic: still using 'from finto import ChatMessage, CreatePromptRequest_Chat' while other imports were updated to langfuse.api.client |
langfuse-python | github_2023 | python | 1,011 | langfuse | greptile-apps[bot] | @@ -53,7 +53,7 @@ def create(
Examples
--------
from finto import CreateScoreRequest
- from finto.client import FernLangfuse
+ from langfuse.api.client import FernLangfuse | logic: still importing CreateScoreRequest from 'finto' instead of 'langfuse.api' |
langfuse-python | github_2023 | python | 1,011 | langfuse | greptile-apps[bot] | @@ -426,7 +426,7 @@ async def create(
import asyncio
from finto import CreateScoreRequest
- from finto.client import AsyncFernLangfuse
+ from langfuse.api.client import AsyncFernLangfuse | logic: still importing CreateScoreRequest from 'finto' instead of 'langfuse.api' |
langfuse-python | github_2023 | python | 1,011 | langfuse | greptile-apps[bot] | @@ -45,7 +48,7 @@ def create(
Examples
--------
from finto import ConfigCategory, CreateScoreConfigRequest, ScoreDataType
- from finto.client import FernLangfuse
+ from langfuse.api.client import FernLangfuse | logic: The import statement still references 'finto' package but the client is imported from 'langfuse.api.client' |
langfuse-python | github_2023 | others | 1,011 | langfuse | greptile-apps[bot] | @@ -37,20 +37,20 @@ pytest-asyncio = ">=0.21.1,<0.24.0"
pytest-httpserver = "^1.0.8"
boto3 = "^1.28.59"
ruff = ">=0.1.8,<0.6.0"
-langchain-mistralai = ">=0.0.1,<0.1.8"
+langchain-mistralai = ">=0.0.1,<0.3"
google-cloud-aiplatform = "^1.38.1"
cohere = ">=4.46,<6.0"
-langchain-google-vertexai = ">=0.0.5,<1.0.5"
-langchain-openai = ">=0.0.5,<0.1.8"
+langchain-google-vertexai = ">=2.0.0,<3.0.0" | logic: Major version bump from <1.0.5 to >=2.0.0 for langchain-google-vertexai could introduce breaking changes. Verify compatibility. |
langfuse-python | github_2023 | others | 1,011 | langfuse | greptile-apps[bot] | @@ -27,8 +30,8 @@ Create a comment. Comments may be attached to different object types (trace, obs
<dd>
```python
-from finto import CreateCommentRequest
-from finto.client import FernLangfuse
+from langfuse.api import CreateCommentRequest
+from langfuse.api.client import FernLangfuse | logic: The import statement still uses 'from finto import CreateCommentRequest' while the FernLangfuse client import was updated. This should be updated to use langfuse.api for consistency. |
langfuse-python | github_2023 | others | 1,011 | langfuse | greptile-apps[bot] | @@ -296,8 +303,8 @@ Create a dataset item
<dd>
```python
-from finto import CreateDatasetItemRequest, DatasetStatus
-from finto.client import FernLangfuse
+from langfuse.api import CreateDatasetItemRequest, DatasetStatus
+from langfuse.api.client import FernLangfuse | logic: The import statement still uses 'from finto import CreateDatasetItemRequest, DatasetStatus' while the FernLangfuse client import was updated. This should be updated to use langfuse.api for consistency. |
langfuse-python | github_2023 | python | 1,011 | langfuse | greptile-apps[bot] | @@ -11,7 +11,7 @@ class HealthResponse(pydantic_v1.BaseModel):
"""
Examples
--------
- from finto import HealthResponse
+ from langfuse.api import HealthResponse | logic: import path should be updated from 'finto' to 'langfuse.api.client' to match other changes in the PR |
langfuse-python | github_2023 | python | 1,011 | langfuse | greptile-apps[bot] | @@ -13,7 +13,7 @@ class ScoreBody(pydantic_v1.BaseModel):
"""
Examples
--------
- from finto import ScoreBody
+ from langfuse.api import ScoreBody | logic: import path in example still uses 'finto' instead of 'langfuse.api.client' which is inconsistent with the PR's goal of updating import paths |
langfuse-python | github_2023 | python | 1,011 | langfuse | greptile-apps[bot] | @@ -13,7 +13,7 @@ class CreateScoreRequest(pydantic_v1.BaseModel):
"""
Examples
--------
- from finto import CreateScoreRequest
+ from langfuse.api import CreateScoreRequest | logic: import path in example still references 'finto' instead of 'langfuse.api.client' which is inconsistent with the PR's stated goal of updating import paths |
langfuse-python | github_2023 | others | 1,011 | langfuse | greptile-apps[bot] | @@ -1,5 +1,7 @@
# Reference
+
## Comments
+
<details><summary><code>client.comments.<a href="src/finto/resources/comments/client.py">create</a>(...)</code></summary> | logic: The href still points to 'src/finto/resources/comments/client.py' but should be updated to reflect the new path structure |
langfuse-python | github_2023 | python | 1,011 | langfuse | greptile-apps[bot] | @@ -69,27 +72,41 @@ def create(
)
"""
_response = self._client_wrapper.httpx_client.request(
- "api/public/dataset-items", method="POST", json=request, request_options=request_options, omit=OMIT
+ "api/public/dataset-items", | logic: API endpoint path missing leading forward slash which could cause request failures |
langfuse-python | github_2023 | others | 1,011 | langfuse | greptile-apps[bot] | @@ -37,20 +40,20 @@ pytest-asyncio = ">=0.21.1,<0.24.0"
pytest-httpserver = "^1.0.8"
boto3 = "^1.28.59"
ruff = ">=0.1.8,<0.6.0"
-langchain-mistralai = ">=0.0.1,<0.1.8"
+langchain-mistralai = ">=0.0.1,<0.3"
google-cloud-aiplatform = "^1.38.1"
cohere = ">=4.46,<6.0"
-langchain-google-vertexai = ">=0.0.5,<1.0.5"
-langchain-openai = ">=0.0.5,<0.1.8"
+langchain-google-vertexai = ">=1.0.0,<3.0.0"
+langchain-openai = ">=0.0.5,<0.3"
dashscope = "^1.14.1"
pymongo = "^4.6.1"
-llama-index-llms-anthropic = "^0.1.1"
+llama-index-llms-anthropic = ">=0.1.1,<0.6"
bson = "^0.5.10"
-langchain-anthropic = "^0.1.4"
-langchain-groq = "^0.1.3"
-langchain-aws = "^0.1.3"
+langchain-anthropic = ">=0.1.4,<0.4"
+langchain-groq = ">=0.1.3,<0.3"
+langchain-aws = ">=0.1.3,<0.3"
-langchain-community = "^0.2.14"
+langchain-community = ">=0.2.14,<0.4" | logic: langchain-community package is not properly placed under any section. Should be under [tool.poetry.dependencies] or [tool.poetry.group.dev.dependencies]. |
langfuse-python | github_2023 | others | 1,011 | langfuse | ellipsis-dev[bot] | @@ -19,6 +19,9 @@ packaging = ">=23.2,<25.0"
idna = "^3.7"
anyio = "^4.4.0"
requests = "^2"
+langchain-ollama = "^0.2.0" | Consider marking `langchain-ollama`, `langchain-cohere`, and `langchain-huggingface` as optional dependencies to avoid unnecessary installations for users who do not need these features. |
langfuse-python | github_2023 | python | 1,011 | langfuse | greptile-apps[bot] | @@ -68,24 +62,15 @@
"claude-3-sonnet-20240229",
ChatAnthropic(model="claude-3-sonnet-20240229"),
),
- ("anthropic", Anthropic()),
- ("anthropic", Anthropic()),
+ ("claude-2", Anthropic()),
+ ("claude-2", Anthropic()), | logic: duplicate test case for Anthropic() with default settings |
langfuse-python | github_2023 | others | 1,011 | langfuse | greptile-apps[bot] | @@ -38,10 +38,10 @@ jobs:
fail-fast: false
matrix:
python-version:
- - "3.8"
- "3.9"
- "3.10"
- "3.11"
+ | logic: Python 3.12 was removed from the test matrix. This seems inconsistent with the PR's goal of supporting Python versions '>=3.9,<4.0'. Consider keeping Python 3.12 in the test matrix to ensure compatibility. |
langfuse-python | github_2023 | python | 1,011 | langfuse | greptile-apps[bot] | @@ -46,4 +48,4 @@ def test_entire_llm_call_using_langchain_openai(expected_model, model):
assert len(trace.observations) == 1
generation = list(filter(lambda o: o.type == "GENERATION", trace.observations))[0] | logic: filter operation could return empty list if no GENERATION observations exist, causing IndexError on next line |
langfuse-python | github_2023 | python | 1,008 | langfuse | greptile-apps[bot] | @@ -200,6 +200,7 @@ def _process_upload_media_job(
headers={
"Content-Type": data["content_type"],
"x-amz-checksum-sha256": data["content_sha256_hash"],
+ "x-ms-blob-type": "BlockBlob", | logic: AWS and Azure headers are mixed together. Should conditionally set headers based on the storage provider to avoid sending AWS headers to Azure and vice versa. |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -1,56 +1,45 @@
-"""@private"""
-
-import atexit
import json
import logging
-import queue
import threading
-from queue import Empty, Queue
import time
-from typing import List, Any, Optional
import typing
+from queue import Empty, Queue
+from typing import Any, List, Optional
-from langfuse.Sampler import Sampler
-from langfuse.parse_error import handle_exception
-from langfuse.request import APIError
-from langfuse.utils import _get_timestamp
-from langfuse.types import MaskFunction
+import backoff
try:
- import pydantic.v1 as pydantic # type: ignore
+ import pydantic.v1 as pydantic
except ImportError:
- import pydantic # type: ignore
-
-
-import backoff
+ import pydantic
-from langfuse.request import LangfuseClient
+from langfuse.api.client import FernLangfuse
+from langfuse.parse_error import handle_exception
+from langfuse.request import APIError, LangfuseClient
+from langfuse.Sampler import Sampler
from langfuse.serializer import EventSerializer
+from langfuse.types import MaskFunction
-# largest message size in db is 331_000 bytes right now
-MAX_MSG_SIZE = 1_000_000
-
-# https://vercel.com/docs/functions/serverless-functions/runtimes#request-body-size
-# The maximum payload size for the request body or the response body of a Serverless Function is 4.5 MB
-# 4_500_000 Bytes = 4.5 MB
-# configured to be 3 MB to be safe
+from .media_manager import MediaManager
-BATCH_SIZE_LIMIT = 2_500_000
+MAX_EVENT_SIZE_BYTES = 1_000_000
+MAX_BATCH_SIZE_BYTES = 2_500_000
-class LangfuseMetadata(pydantic.BaseModel):
+class IngestionMetadata(pydantic.BaseModel):
batch_size: int
- sdk_integration: typing.Optional[str] = None
- sdk_name: str = None
- sdk_version: str = None
- public_key: str = None
+ sdk_integration: Optional[str] = None
+ sdk_name: Optional[str] = None
+ sdk_version: Optional[str] = None
+ public_key: Optional[str] = None
-class Consumer(threading.Thread):
+class IngestionConsumer(threading.Thread):
_log = logging.getLogger("langfuse")
- _queue: Queue
+ _ingestion_queue: Queue
_identifier: int
_client: LangfuseClient
+ _api_client: FernLangfuse | logic: _api_client is declared but never initialized or used |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,245 @@
+import base64
+import hashlib
+import logging
+from queue import Empty
+from typing import Literal
+
+import requests
+
+from langfuse.api import GetMediaUploadUrlRequest, PatchMediaBody
+from langfuse.api.client import FernLangfuse
+from langfuse.utils import _get_timestamp
+
+from .media_upload_queue import MediaUploadQueue, UploadMediaJob
+
+
+class MediaManager:
+ _log = logging.getLogger(__name__)
+
+ def __init__(
+ self, *, api_client: FernLangfuse, media_upload_queue: MediaUploadQueue
+ ):
+ self._api_client = api_client
+ self._queue = media_upload_queue
+
+ def process_next_media_upload(self):
+ try:
+ data = self._queue.get(block=True, timeout=1)
+ self._process_upload_media_job(data=data)
+
+ self._queue.task_done()
+ except Empty:
+ pass
+ except Exception as e:
+ self._log.error(f"Error uploading media: {e}")
+ self._queue.task_done()
+
+ def process_multimodal_event_in_place(self, event: dict):
+ try:
+ if "body" not in event:
+ return
+
+ body = event["body"]
+ multimodal_fields = ["input", "output"]
+
+ for field in multimodal_fields:
+ if field in body:
+ field_data = body[field]
+
+ if field == "output":
+ self._process_multimodal_message(
+ event=event, body=body, field=field, message=field_data
+ ) | logic: Inconsistent handling of output field - processes single output directly but also processes it again in list handling below |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,245 @@
+import base64
+import hashlib
+import logging
+from queue import Empty
+from typing import Literal
+
+import requests
+
+from langfuse.api import GetMediaUploadUrlRequest, PatchMediaBody
+from langfuse.api.client import FernLangfuse
+from langfuse.utils import _get_timestamp
+
+from .media_upload_queue import MediaUploadQueue, UploadMediaJob
+
+
+class MediaManager:
+ _log = logging.getLogger(__name__)
+
+ def __init__(
+ self, *, api_client: FernLangfuse, media_upload_queue: MediaUploadQueue
+ ):
+ self._api_client = api_client
+ self._queue = media_upload_queue
+
+ def process_next_media_upload(self):
+ try:
+ data = self._queue.get(block=True, timeout=1)
+ self._process_upload_media_job(data=data)
+
+ self._queue.task_done()
+ except Empty:
+ pass
+ except Exception as e:
+ self._log.error(f"Error uploading media: {e}")
+ self._queue.task_done()
+
+ def process_multimodal_event_in_place(self, event: dict):
+ try:
+ if "body" not in event:
+ return
+
+ body = event["body"]
+ multimodal_fields = ["input", "output"]
+
+ for field in multimodal_fields:
+ if field in body:
+ field_data = body[field]
+
+ if field == "output":
+ self._process_multimodal_message(
+ event=event, body=body, field=field, message=field_data
+ )
+
+ if isinstance(field_data, list):
+ for message in field_data:
+ self._process_multimodal_message(
+ event=event, body=body, field=field, message=message
+ )
+
+ except Exception as e:
+ self._log.error(f"Error processing multimodal event: {e}")
+
+ def _process_multimodal_message(
+ self, *, event: dict, body: dict, field: str, message: dict
+ ):
+ if isinstance(message, dict) and message.get("content", None) is not None:
+ content = message["content"]
+
+ for content_part in content:
+ if isinstance(content_part, dict): | logic: Missing validation that content is a list before iteration |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,245 @@
+import base64
+import hashlib
+import logging
+from queue import Empty
+from typing import Literal
+
+import requests
+
+from langfuse.api import GetMediaUploadUrlRequest, PatchMediaBody
+from langfuse.api.client import FernLangfuse
+from langfuse.utils import _get_timestamp
+
+from .media_upload_queue import MediaUploadQueue, UploadMediaJob
+
+
+class MediaManager:
+ _log = logging.getLogger(__name__)
+
+ def __init__(
+ self, *, api_client: FernLangfuse, media_upload_queue: MediaUploadQueue
+ ):
+ self._api_client = api_client
+ self._queue = media_upload_queue
+
+ def process_next_media_upload(self):
+ try:
+ data = self._queue.get(block=True, timeout=1)
+ self._process_upload_media_job(data=data)
+
+ self._queue.task_done()
+ except Empty:
+ pass
+ except Exception as e:
+ self._log.error(f"Error uploading media: {e}")
+ self._queue.task_done()
+
+ def process_multimodal_event_in_place(self, event: dict):
+ try:
+ if "body" not in event:
+ return
+
+ body = event["body"]
+ multimodal_fields = ["input", "output"]
+
+ for field in multimodal_fields:
+ if field in body:
+ field_data = body[field]
+
+ if field == "output":
+ self._process_multimodal_message(
+ event=event, body=body, field=field, message=field_data
+ )
+
+ if isinstance(field_data, list):
+ for message in field_data:
+ self._process_multimodal_message(
+ event=event, body=body, field=field, message=message
+ )
+
+ except Exception as e:
+ self._log.error(f"Error processing multimodal event: {e}")
+
+ def _process_multimodal_message(
+ self, *, event: dict, body: dict, field: str, message: dict
+ ):
+ if isinstance(message, dict) and message.get("content", None) is not None:
+ content = message["content"]
+
+ for content_part in content:
+ if isinstance(content_part, dict):
+ if content_part.get("image_url", None) is not None:
+ base64_data_uri = content_part["image_url"]["url"]
+ if base64_data_uri.startswith("data:"):
+ media_reference_string = self._enqueue_media_upload(
+ event=event,
+ body=body,
+ field=field,
+ base64_data_uri=base64_data_uri,
+ )
+
+ if media_reference_string:
+ content_part["image_url"]["url"] = (
+ media_reference_string
+ )
+
+ if content_part.get("input_audio", None) is not None:
+ base64_data_uri = (
+ f"data:audio/{content_part['input_audio']['format']};base64,"
+ + content_part["input_audio"]["data"]
+ )
+
+ media_reference_string = self._enqueue_media_upload(
+ event=event,
+ body=body,
+ field=field,
+ base64_data_uri=base64_data_uri,
+ )
+
+ if media_reference_string:
+ content_part["input_audio"]["data"] = media_reference_string
+
+ if content_part.get("output_audio", None) is not None:
+ base64_data_uri = (
+ f"data:audio/{content_part['output_audio']['format']};base64,"
+ + content_part["output_audio"]["data"]
+ )
+
+ media_reference_string = self._enqueue_media_upload(
+ event=event,
+ body=body,
+ field=field,
+ base64_data_uri=base64_data_uri,
+ )
+
+ if media_reference_string:
+ content_part["output_audio"]["data"] = (
+ media_reference_string
+ )
+
+ def _enqueue_media_upload(
+ self, *, event: dict, body: dict, field: str, base64_data_uri: str
+ ):
+ parsed_content = self._parse_base64_data_uri(base64_data_uri)
+ trace_id = body.get("traceId", None) or (
+ body.get("id", None)
+ if "type" in event and "trace" in event["type"]
+ else None
+ )
+
+ if trace_id is None:
+ raise ValueError("trace_id is required for media upload")
+
+ observation_id = (
+ body.get("id", None)
+ if "type" in event
+ and ("generation" in event["type"] or "span" in event["type"])
+ else None
+ )
+
+ if parsed_content:
+ content_length = parsed_content["content_length"]
+ content_type = parsed_content["content_type"]
+ content_sha256_hash = parsed_content["content_sha256_hash"]
+ content_bytes = parsed_content["content_bytes"]
+
+ upload_url_response = self._api_client.media.get_upload_url(
+ request=GetMediaUploadUrlRequest(
+ field=field,
+ contentLength=content_length,
+ contentType=content_type,
+ sha256Hash=content_sha256_hash,
+ traceId=trace_id,
+ observationId=observation_id,
+ )
+ )
+
+ upload_url = upload_url_response.upload_url
+ media_id = upload_url_response.media_id
+
+ if upload_url is not None:
+ self._queue.put(
+ item={
+ "content_bytes": content_bytes,
+ "content_type": content_type,
+ "content_sha256_hash": content_sha256_hash,
+ "upload_url": upload_url,
+ "media_id": media_id,
+ },
+ block=True,
+ )
+
+ return self._format_media_reference_string(
+ content_type=content_type,
+ media_id=media_id,
+ source="base64",
+ )
+
+ def _process_upload_media_job(
+ self,
+ *,
+ data: UploadMediaJob,
+ ):
+ upload_response = requests.put(
+ data["upload_url"],
+ headers={
+ "Content-Type": data["content_type"],
+ "x-amz-checksum-sha256": data["content_sha256_hash"],
+ },
+ data=data["content_bytes"],
+ ) | logic: No timeout set for PUT request - could hang indefinitely on slow uploads |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,245 @@
+import base64
+import hashlib
+import logging
+from queue import Empty
+from typing import Literal
+
+import requests
+
+from langfuse.api import GetMediaUploadUrlRequest, PatchMediaBody
+from langfuse.api.client import FernLangfuse
+from langfuse.utils import _get_timestamp
+
+from .media_upload_queue import MediaUploadQueue, UploadMediaJob
+
+
+class MediaManager:
+ _log = logging.getLogger(__name__)
+
+ def __init__(
+ self, *, api_client: FernLangfuse, media_upload_queue: MediaUploadQueue
+ ):
+ self._api_client = api_client
+ self._queue = media_upload_queue
+
+ def process_next_media_upload(self):
+ try:
+ data = self._queue.get(block=True, timeout=1)
+ self._process_upload_media_job(data=data)
+
+ self._queue.task_done()
+ except Empty:
+ pass
+ except Exception as e:
+ self._log.error(f"Error uploading media: {e}")
+ self._queue.task_done()
+
+ def process_multimodal_event_in_place(self, event: dict):
+ try:
+ if "body" not in event:
+ return
+
+ body = event["body"]
+ multimodal_fields = ["input", "output"]
+
+ for field in multimodal_fields:
+ if field in body:
+ field_data = body[field]
+
+ if field == "output":
+ self._process_multimodal_message(
+ event=event, body=body, field=field, message=field_data
+ )
+
+ if isinstance(field_data, list):
+ for message in field_data:
+ self._process_multimodal_message(
+ event=event, body=body, field=field, message=message
+ )
+
+ except Exception as e:
+ self._log.error(f"Error processing multimodal event: {e}")
+
+ def _process_multimodal_message(
+ self, *, event: dict, body: dict, field: str, message: dict
+ ):
+ if isinstance(message, dict) and message.get("content", None) is not None:
+ content = message["content"]
+
+ for content_part in content:
+ if isinstance(content_part, dict):
+ if content_part.get("image_url", None) is not None:
+ base64_data_uri = content_part["image_url"]["url"]
+ if base64_data_uri.startswith("data:"):
+ media_reference_string = self._enqueue_media_upload(
+ event=event,
+ body=body,
+ field=field,
+ base64_data_uri=base64_data_uri,
+ )
+
+ if media_reference_string:
+ content_part["image_url"]["url"] = (
+ media_reference_string
+ )
+
+ if content_part.get("input_audio", None) is not None:
+ base64_data_uri = (
+ f"data:audio/{content_part['input_audio']['format']};base64,"
+ + content_part["input_audio"]["data"]
+ )
+
+ media_reference_string = self._enqueue_media_upload(
+ event=event,
+ body=body,
+ field=field,
+ base64_data_uri=base64_data_uri,
+ )
+
+ if media_reference_string:
+ content_part["input_audio"]["data"] = media_reference_string
+
+ if content_part.get("output_audio", None) is not None:
+ base64_data_uri = (
+ f"data:audio/{content_part['output_audio']['format']};base64,"
+ + content_part["output_audio"]["data"]
+ )
+
+ media_reference_string = self._enqueue_media_upload(
+ event=event,
+ body=body,
+ field=field,
+ base64_data_uri=base64_data_uri,
+ )
+
+ if media_reference_string:
+ content_part["output_audio"]["data"] = (
+ media_reference_string
+ )
+
+ def _enqueue_media_upload(
+ self, *, event: dict, body: dict, field: str, base64_data_uri: str
+ ):
+ parsed_content = self._parse_base64_data_uri(base64_data_uri)
+ trace_id = body.get("traceId", None) or (
+ body.get("id", None)
+ if "type" in event and "trace" in event["type"]
+ else None
+ )
+
+ if trace_id is None:
+ raise ValueError("trace_id is required for media upload")
+
+ observation_id = (
+ body.get("id", None)
+ if "type" in event
+ and ("generation" in event["type"] or "span" in event["type"])
+ else None
+ )
+
+ if parsed_content:
+ content_length = parsed_content["content_length"]
+ content_type = parsed_content["content_type"]
+ content_sha256_hash = parsed_content["content_sha256_hash"]
+ content_bytes = parsed_content["content_bytes"]
+
+ upload_url_response = self._api_client.media.get_upload_url(
+ request=GetMediaUploadUrlRequest(
+ field=field,
+ contentLength=content_length,
+ contentType=content_type,
+ sha256Hash=content_sha256_hash,
+ traceId=trace_id,
+ observationId=observation_id,
+ )
+ )
+
+ upload_url = upload_url_response.upload_url
+ media_id = upload_url_response.media_id
+
+ if upload_url is not None:
+ self._queue.put(
+ item={
+ "content_bytes": content_bytes,
+ "content_type": content_type,
+ "content_sha256_hash": content_sha256_hash,
+ "upload_url": upload_url,
+ "media_id": media_id,
+ },
+ block=True,
+ ) | logic: Queue put() with block=True could deadlock if queue is full |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,41 @@
+import logging
+import threading
+
+from .media_manager import MediaManager
+
+
+class MediaUploadConsumer(threading.Thread):
+ _log = logging.getLogger(__name__)
+ _identifier: int
+ _max_retries: int
+ _media_manager: MediaManager | logic: max_retries is defined as a class attribute but never used in the implementation |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,41 @@
+import logging
+import threading
+
+from .media_manager import MediaManager
+
+
+class MediaUploadConsumer(threading.Thread):
+ _log = logging.getLogger(__name__)
+ _identifier: int
+ _max_retries: int
+ _media_manager: MediaManager
+
+ def __init__(
+ self,
+ *,
+ identifier: int,
+ max_retries: int,
+ media_manager: MediaManager,
+ ):
+ """Create a consumer thread."""
+ super().__init__()
+ # Make consumer a daemon thread so that it doesn't block program exit
+ self.daemon = True
+ # It's important to set running in the constructor: if we are asked to
+ # pause immediately after construction, we might set running to True in
+ # run() *after* we set it to False in pause... and keep running
+ # forever.
+ self.running = True
+ self._identifier = identifier
+ self._max_retries = max_retries
+ self._media_manager = media_manager
+
+ def run(self):
+ """Run the media upload consumer."""
+ self._log.debug("consumer is running...")
+ while self.running:
+ self._media_manager.process_next_media_upload() | logic: no error handling around process_next_media_upload() - unhandled exceptions will crash the thread |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,195 @@
+"""@private"""
+
+import atexit
+import logging
+import queue
+from queue import Queue
+from typing import List, Optional
+
+from langfuse.api.client import FernLangfuse
+from langfuse.request import LangfuseClient
+from langfuse.types import MaskFunction
+from langfuse.utils import _get_timestamp
+
+from .ingestion_consumer import IngestionConsumer
+from .media_manager import MediaManager
+from .media_upload_consumer import MediaUploadConsumer
+from .media_upload_queue import MediaUploadQueue
+
+
+class TaskManager(object):
+ _log = logging.getLogger(__name__)
+ _ingestion_consumers: List[IngestionConsumer]
+ _enabled: bool
+ _threads: int
+ _media_upload_threads: int
+ _max_task_queue_size: int
+ _ingestion_queue: Queue
+ _media_upload_queue: MediaUploadQueue
+ _client: LangfuseClient
+ _api_client: FernLangfuse
+ _flush_at: int
+ _flush_interval: float
+ _max_retries: int
+ _public_key: str
+ _sdk_name: str
+ _sdk_version: str
+ _sdk_integration: str
+ _sample_rate: float
+ _mask: Optional[MaskFunction]
+
+ def __init__(
+ self,
+ *,
+ client: LangfuseClient,
+ api_client: FernLangfuse,
+ flush_at: int,
+ flush_interval: float,
+ max_retries: int,
+ threads: int,
+ media_upload_threads: int = 1,
+ public_key: str,
+ sdk_name: str,
+ sdk_version: str,
+ sdk_integration: str,
+ enabled: bool = True,
+ max_task_queue_size: int = 100_000,
+ sample_rate: float = 1,
+ mask: Optional[MaskFunction] = None,
+ ):
+ self._max_task_queue_size = max_task_queue_size
+ self._threads = threads
+ self._media_upload_threads = media_upload_threads
+ self._ingestion_queue = queue.Queue(self._max_task_queue_size)
+ self._media_upload_queue = MediaUploadQueue(self._max_task_queue_size)
+ self._media_manager = MediaManager(
+ api_client=api_client, media_upload_queue=self._media_upload_queue
+ )
+ self._ingestion_consumers = []
+ self._media_upload_consumers = []
+ self._client = client
+ self._api_client = api_client
+ self._flush_at = flush_at
+ self._flush_interval = flush_interval
+ self._max_retries = max_retries
+ self._public_key = public_key
+ self._sdk_name = sdk_name
+ self._sdk_version = sdk_version
+ self._sdk_integration = sdk_integration
+ self._enabled = enabled
+ self._sample_rate = sample_rate
+ self._mask = mask
+
+ self.init_resources()
+
+ # cleans up when the python interpreter closes
+ atexit.register(self.join)
+
+ def init_resources(self):
+ for i in range(self._threads):
+ ingestion_consumer = IngestionConsumer(
+ ingestion_queue=self._ingestion_queue,
+ identifier=i,
+ client=self._client,
+ media_manager=self._media_manager,
+ flush_at=self._flush_at,
+ flush_interval=self._flush_interval,
+ max_retries=self._max_retries,
+ public_key=self._public_key,
+ sdk_name=self._sdk_name,
+ sdk_version=self._sdk_version,
+ sdk_integration=self._sdk_integration,
+ sample_rate=self._sample_rate,
+ mask=self._mask,
+ )
+ ingestion_consumer.start()
+ self._ingestion_consumers.append(ingestion_consumer)
+
+ for i in range(self._media_upload_threads):
+ media_upload_consumer = MediaUploadConsumer(
+ identifier=i,
+ max_retries=self._max_retries,
+ media_manager=self._media_manager,
+ )
+ media_upload_consumer.start()
+ self._media_upload_consumers.append(media_upload_consumer)
+
+ def add_task(self, event: dict):
+ if not self._enabled:
+ return
+
+ try:
+ event["timestamp"] = _get_timestamp()
+
+ self._ingestion_queue.put(event, block=False) | logic: Queue.put() with block=False can silently drop events. Consider using block=True with a timeout to ensure critical events aren't lost |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,195 @@
+"""@private"""
+
+import atexit
+import logging
+import queue
+from queue import Queue
+from typing import List, Optional
+
+from langfuse.api.client import FernLangfuse
+from langfuse.request import LangfuseClient
+from langfuse.types import MaskFunction
+from langfuse.utils import _get_timestamp
+
+from .ingestion_consumer import IngestionConsumer
+from .media_manager import MediaManager
+from .media_upload_consumer import MediaUploadConsumer
+from .media_upload_queue import MediaUploadQueue
+
+
+class TaskManager(object):
+ _log = logging.getLogger(__name__)
+ _ingestion_consumers: List[IngestionConsumer]
+ _enabled: bool
+ _threads: int
+ _media_upload_threads: int
+ _max_task_queue_size: int
+ _ingestion_queue: Queue
+ _media_upload_queue: MediaUploadQueue
+ _client: LangfuseClient
+ _api_client: FernLangfuse
+ _flush_at: int
+ _flush_interval: float
+ _max_retries: int
+ _public_key: str
+ _sdk_name: str
+ _sdk_version: str
+ _sdk_integration: str
+ _sample_rate: float
+ _mask: Optional[MaskFunction]
+
+ def __init__(
+ self,
+ *,
+ client: LangfuseClient,
+ api_client: FernLangfuse,
+ flush_at: int,
+ flush_interval: float,
+ max_retries: int,
+ threads: int,
+ media_upload_threads: int = 1,
+ public_key: str,
+ sdk_name: str,
+ sdk_version: str,
+ sdk_integration: str,
+ enabled: bool = True,
+ max_task_queue_size: int = 100_000,
+ sample_rate: float = 1,
+ mask: Optional[MaskFunction] = None,
+ ):
+ self._max_task_queue_size = max_task_queue_size
+ self._threads = threads
+ self._media_upload_threads = media_upload_threads
+ self._ingestion_queue = queue.Queue(self._max_task_queue_size)
+ self._media_upload_queue = MediaUploadQueue(self._max_task_queue_size)
+ self._media_manager = MediaManager(
+ api_client=api_client, media_upload_queue=self._media_upload_queue
+ )
+ self._ingestion_consumers = []
+ self._media_upload_consumers = []
+ self._client = client
+ self._api_client = api_client
+ self._flush_at = flush_at
+ self._flush_interval = flush_interval
+ self._max_retries = max_retries
+ self._public_key = public_key
+ self._sdk_name = sdk_name
+ self._sdk_version = sdk_version
+ self._sdk_integration = sdk_integration
+ self._enabled = enabled
+ self._sample_rate = sample_rate
+ self._mask = mask
+
+ self.init_resources()
+
+ # cleans up when the python interpreter closes
+ atexit.register(self.join)
+
+ def init_resources(self):
+ for i in range(self._threads):
+ ingestion_consumer = IngestionConsumer(
+ ingestion_queue=self._ingestion_queue,
+ identifier=i,
+ client=self._client,
+ media_manager=self._media_manager,
+ flush_at=self._flush_at,
+ flush_interval=self._flush_interval,
+ max_retries=self._max_retries,
+ public_key=self._public_key,
+ sdk_name=self._sdk_name,
+ sdk_version=self._sdk_version,
+ sdk_integration=self._sdk_integration,
+ sample_rate=self._sample_rate,
+ mask=self._mask,
+ )
+ ingestion_consumer.start()
+ self._ingestion_consumers.append(ingestion_consumer)
+
+ for i in range(self._media_upload_threads):
+ media_upload_consumer = MediaUploadConsumer(
+ identifier=i,
+ max_retries=self._max_retries,
+ media_manager=self._media_manager,
+ )
+ media_upload_consumer.start()
+ self._media_upload_consumers.append(media_upload_consumer)
+
+ def add_task(self, event: dict):
+ if not self._enabled:
+ return
+
+ try:
+ event["timestamp"] = _get_timestamp()
+
+ self._ingestion_queue.put(event, block=False)
+ except queue.Full:
+ self._log.warning("analytics-python queue is full")
+ return False
+ except Exception as e:
+ self._log.exception(f"Exception in adding task {e}")
+
+ return False
+
+ def flush(self):
+ """Force a flush from the internal queue to the server."""
+ self._log.debug("flushing ingestion and media upload queues")
+
+ # Ingestion queue
+ ingestion_queue_size = self._ingestion_queue.qsize()
+ self._ingestion_queue.join() | logic: qsize() followed by join() is not thread-safe - the logged size may be inaccurate by the time join() completes |
langfuse-python | github_2023 | others | 996 | langfuse | greptile-apps[bot] | @@ -27,16 +27,13 @@ client = FernLangfuse(
password="YOUR_PASSWORD",
base_url="https://yourhost.com/path/to/api",
)
-client.dataset_items.create(
- request=CreateDatasetItemRequest(
- dataset_name="string",
- input={"key": "value"},
- expected_output={"key": "value"},
- metadata={"key": "value"},
- source_trace_id="string",
- source_observation_id="string",
- id="string",
- status=DatasetStatus.ACTIVE,
+client.comments.create(
+ request=CreateCommentRequest(
+ project_id="string",
+ object_type="string",
+ object_id="string", | logic: object_type should be one of the enum values from CommentObjectType (TRACE, OBSERVATION, SESSION, PROMPT). Add example using actual enum value. |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,534 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import typing
+from json.decoder import JSONDecodeError
+
+from ...core.api_error import ApiError
+from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
+from ...core.jsonable_encoder import jsonable_encoder
+from ...core.pydantic_utilities import pydantic_v1
+from ...core.request_options import RequestOptions
+from ..commons.errors.access_denied_error import AccessDeniedError
+from ..commons.errors.error import Error
+from ..commons.errors.method_not_allowed_error import MethodNotAllowedError
+from ..commons.errors.not_found_error import NotFoundError
+from ..commons.errors.unauthorized_error import UnauthorizedError
+from ..commons.types.comment import Comment
+from .types.create_comment_request import CreateCommentRequest
+from .types.create_comment_response import CreateCommentResponse
+from .types.get_comments_response import GetCommentsResponse
+
+# this is used as the default value for optional parameters
+OMIT = typing.cast(typing.Any, ...)
+
+
+class CommentsClient:
+ def __init__(self, *, client_wrapper: SyncClientWrapper):
+ self._client_wrapper = client_wrapper
+
+ def create(
+ self,
+ *,
+ request: CreateCommentRequest,
+ request_options: typing.Optional[RequestOptions] = None,
+ ) -> CreateCommentResponse:
+ """
+ Create a comment. Comments may be attached to different object types (trace, observation, session, prompt).
+
+ Parameters
+ ----------
+ request : CreateCommentRequest
+
+ request_options : typing.Optional[RequestOptions]
+ Request-specific configuration.
+
+ Returns
+ -------
+ CreateCommentResponse
+
+ Examples
+ --------
+ from finto import CreateCommentRequest
+ from finto.client import FernLangfuse
+
+ client = FernLangfuse(
+ x_langfuse_sdk_name="YOUR_X_LANGFUSE_SDK_NAME",
+ x_langfuse_sdk_version="YOUR_X_LANGFUSE_SDK_VERSION",
+ x_langfuse_public_key="YOUR_X_LANGFUSE_PUBLIC_KEY",
+ username="YOUR_USERNAME",
+ password="YOUR_PASSWORD",
+ base_url="https://yourhost.com/path/to/api",
+ )
+ client.comments.create(
+ request=CreateCommentRequest(
+ project_id="string",
+ object_type="string",
+ object_id="string",
+ content="string",
+ author_user_id="string",
+ ),
+ )
+ """
+ _response = self._client_wrapper.httpx_client.request(
+ "api/public/comments",
+ method="POST",
+ json=request,
+ request_options=request_options,
+ omit=OMIT,
+ )
+ try:
+ if 200 <= _response.status_code < 300:
+ return pydantic_v1.parse_obj_as(CreateCommentResponse, _response.json()) # type: ignore
+ if _response.status_code == 400:
+ raise Error(pydantic_v1.parse_obj_as(typing.Any, _response.json())) # type: ignore
+ if _response.status_code == 401:
+ raise UnauthorizedError(
+ pydantic_v1.parse_obj_as(typing.Any, _response.json())
+ ) # type: ignore
+ if _response.status_code == 403:
+ raise AccessDeniedError(
+ pydantic_v1.parse_obj_as(typing.Any, _response.json())
+ ) # type: ignore
+ if _response.status_code == 405:
+ raise MethodNotAllowedError(
+ pydantic_v1.parse_obj_as(typing.Any, _response.json())
+ ) # type: ignore
+ if _response.status_code == 404:
+ raise NotFoundError(
+ pydantic_v1.parse_obj_as(typing.Any, _response.json())
+ ) # type: ignore
+ _response_json = _response.json()
+ except JSONDecodeError:
+ raise ApiError(status_code=_response.status_code, body=_response.text)
+ raise ApiError(status_code=_response.status_code, body=_response_json)
+
+ def get(
+ self,
+ *,
+ page: typing.Optional[int] = None,
+ limit: typing.Optional[int] = None,
+ object_type: typing.Optional[str] = None,
+ object_id: typing.Optional[str] = None,
+ author_user_id: typing.Optional[str] = None,
+ request_options: typing.Optional[RequestOptions] = None,
+ ) -> GetCommentsResponse:
+ """
+ Get all comments
+
+ Parameters
+ ----------
+ page : typing.Optional[int]
+ Page number, starts at 1.
+
+ limit : typing.Optional[int]
+ Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit
+
+ object_type : typing.Optional[str]
+ Filter comments by object type (trace, observation, session, prompt).
+
+ object_id : typing.Optional[str]
+ Filter comments by object id. If objectType is not provided, an error will be thrown. | logic: Documentation indicates objectType is required when objectId is provided, but no validation is implemented |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,69 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import datetime as dt
+import typing
+
+from ....core.datetime_utils import serialize_datetime
+from ....core.pydantic_utilities import deep_union_pydantic_dicts, pydantic_v1
+
+
+class CreateCommentRequest(pydantic_v1.BaseModel):
+ project_id: str = pydantic_v1.Field(alias="projectId")
+ """
+ The id of the project to attach the comment to.
+ """
+
+ object_type: str = pydantic_v1.Field(alias="objectType") | logic: object_type should use the CommentObjectType enum instead of str to ensure valid values |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,69 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import datetime as dt
+import typing
+
+from ....core.datetime_utils import serialize_datetime
+from ....core.pydantic_utilities import deep_union_pydantic_dicts, pydantic_v1
+
+
+class CreateCommentRequest(pydantic_v1.BaseModel):
+ project_id: str = pydantic_v1.Field(alias="projectId")
+ """
+ The id of the project to attach the comment to.
+ """
+
+ object_type: str = pydantic_v1.Field(alias="objectType")
+ """
+ The type of the object to attach the comment to (trace, observation, session, prompt).
+ """
+
+ object_id: str = pydantic_v1.Field(alias="objectId")
+ """
+ The id of the object to attach the comment to. If this does not reference a valid existing object, an error will be thrown.
+ """
+
+ content: str = pydantic_v1.Field()
+ """
+ The content of the comment. May include markdown. Currently limited to 500 characters.
+ """ | logic: content field needs max_length=500 validator to enforce character limit mentioned in docstring |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,29 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import enum
+import typing
+
+T_Result = typing.TypeVar("T_Result")
+
+
+class CommentObjectType(str, enum.Enum):
+ TRACE = "TRACE"
+ OBSERVATION = "OBSERVATION"
+ SESSION = "SESSION"
+ PROMPT = "PROMPT"
+
+ def visit(
+ self,
+ trace: typing.Callable[[], T_Result],
+ observation: typing.Callable[[], T_Result],
+ session: typing.Callable[[], T_Result],
+ prompt: typing.Callable[[], T_Result],
+ ) -> T_Result: | logic: visit method lacks exhaustive pattern matching - could raise undefined behavior if new enum values are added. Consider adding an else clause that raises NotImplementedError |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,509 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import typing
+from json.decoder import JSONDecodeError
+
+from ...core.api_error import ApiError
+from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
+from ...core.jsonable_encoder import jsonable_encoder
+from ...core.pydantic_utilities import pydantic_v1
+from ...core.request_options import RequestOptions
+from ..commons.errors.access_denied_error import AccessDeniedError
+from ..commons.errors.error import Error
+from ..commons.errors.method_not_allowed_error import MethodNotAllowedError
+from ..commons.errors.not_found_error import NotFoundError
+from ..commons.errors.unauthorized_error import UnauthorizedError
+from .types.get_media_response import GetMediaResponse
+from .types.get_media_upload_url_request import GetMediaUploadUrlRequest
+from .types.get_media_upload_url_response import GetMediaUploadUrlResponse
+from .types.patch_media_body import PatchMediaBody
+
+# this is used as the default value for optional parameters
+OMIT = typing.cast(typing.Any, ...)
+
+
+class MediaClient:
+ def __init__(self, *, client_wrapper: SyncClientWrapper):
+ self._client_wrapper = client_wrapper
+
+ def get(
+ self, media_id: str, *, request_options: typing.Optional[RequestOptions] = None
+ ) -> GetMediaResponse:
+ """
+ Get a media record
+
+ Parameters
+ ----------
+ media_id : str
+ The unique langfuse identifier of a media record
+
+ request_options : typing.Optional[RequestOptions]
+ Request-specific configuration.
+
+ Returns
+ -------
+ GetMediaResponse
+
+ Examples
+ --------
+ from finto.client import FernLangfuse
+
+ client = FernLangfuse(
+ x_langfuse_sdk_name="YOUR_X_LANGFUSE_SDK_NAME",
+ x_langfuse_sdk_version="YOUR_X_LANGFUSE_SDK_VERSION",
+ x_langfuse_public_key="YOUR_X_LANGFUSE_PUBLIC_KEY",
+ username="YOUR_USERNAME",
+ password="YOUR_PASSWORD",
+ base_url="https://yourhost.com/path/to/api",
+ )
+ client.media.get(
+ media_id="string",
+ )
+ """
+ _response = self._client_wrapper.httpx_client.request(
+ f"api/public/media/{jsonable_encoder(media_id)}",
+ method="GET",
+ request_options=request_options,
+ )
+ try:
+ if 200 <= _response.status_code < 300:
+ return pydantic_v1.parse_obj_as(GetMediaResponse, _response.json()) # type: ignore
+ if _response.status_code == 400:
+ raise Error(pydantic_v1.parse_obj_as(typing.Any, _response.json())) # type: ignore
+ if _response.status_code == 401:
+ raise UnauthorizedError(
+ pydantic_v1.parse_obj_as(typing.Any, _response.json())
+ ) # type: ignore
+ if _response.status_code == 403:
+ raise AccessDeniedError(
+ pydantic_v1.parse_obj_as(typing.Any, _response.json())
+ ) # type: ignore
+ if _response.status_code == 405:
+ raise MethodNotAllowedError(
+ pydantic_v1.parse_obj_as(typing.Any, _response.json())
+ ) # type: ignore
+ if _response.status_code == 404:
+ raise NotFoundError(
+ pydantic_v1.parse_obj_as(typing.Any, _response.json())
+ ) # type: ignore
+ _response_json = _response.json()
+ except JSONDecodeError:
+ raise ApiError(status_code=_response.status_code, body=_response.text)
+ raise ApiError(status_code=_response.status_code, body=_response_json) | logic: Consider handling the case where response.json() fails but status code is not in the expected range - currently it will raise an ApiError with potentially invalid json |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,509 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import typing
+from json.decoder import JSONDecodeError
+
+from ...core.api_error import ApiError
+from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
+from ...core.jsonable_encoder import jsonable_encoder
+from ...core.pydantic_utilities import pydantic_v1
+from ...core.request_options import RequestOptions
+from ..commons.errors.access_denied_error import AccessDeniedError
+from ..commons.errors.error import Error
+from ..commons.errors.method_not_allowed_error import MethodNotAllowedError
+from ..commons.errors.not_found_error import NotFoundError
+from ..commons.errors.unauthorized_error import UnauthorizedError
+from .types.get_media_response import GetMediaResponse
+from .types.get_media_upload_url_request import GetMediaUploadUrlRequest
+from .types.get_media_upload_url_response import GetMediaUploadUrlResponse
+from .types.patch_media_body import PatchMediaBody
+
+# this is used as the default value for optional parameters
+OMIT = typing.cast(typing.Any, ...)
+
+
+class MediaClient:
+ def __init__(self, *, client_wrapper: SyncClientWrapper):
+ self._client_wrapper = client_wrapper
+
+ def get(
+ self, media_id: str, *, request_options: typing.Optional[RequestOptions] = None
+ ) -> GetMediaResponse:
+ """
+ Get a media record
+
+ Parameters
+ ----------
+ media_id : str
+ The unique langfuse identifier of a media record
+
+ request_options : typing.Optional[RequestOptions]
+ Request-specific configuration.
+
+ Returns
+ -------
+ GetMediaResponse
+
+ Examples
+ --------
+ from finto.client import FernLangfuse
+
+ client = FernLangfuse(
+ x_langfuse_sdk_name="YOUR_X_LANGFUSE_SDK_NAME",
+ x_langfuse_sdk_version="YOUR_X_LANGFUSE_SDK_VERSION",
+ x_langfuse_public_key="YOUR_X_LANGFUSE_PUBLIC_KEY",
+ username="YOUR_USERNAME",
+ password="YOUR_PASSWORD",
+ base_url="https://yourhost.com/path/to/api",
+ )
+ client.media.get(
+ media_id="string",
+ )
+ """
+ _response = self._client_wrapper.httpx_client.request(
+ f"api/public/media/{jsonable_encoder(media_id)}",
+ method="GET",
+ request_options=request_options,
+ ) | logic: API endpoints should start with a leading slash - change to '/api/public/media/' |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,72 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import datetime as dt
+import typing
+
+from ....core.datetime_utils import serialize_datetime
+from ....core.pydantic_utilities import deep_union_pydantic_dicts, pydantic_v1
+
+
+class GetMediaResponse(pydantic_v1.BaseModel):
+ media_id: str = pydantic_v1.Field(alias="mediaId")
+ """
+ The unique langfuse identifier of a media record
+ """
+
+ content_type: str = pydantic_v1.Field(alias="contentType")
+ """
+ The MIME type of the media record
+ """
+
+ content_length: int = pydantic_v1.Field(alias="contentLength")
+ """
+ The size of the media record in bytes
+ """
+
+ uploaded_at: dt.datetime = pydantic_v1.Field(alias="uploadedAt")
+ """
+ The date and time when the media record was uploaded
+ """
+
+ url: str = pydantic_v1.Field()
+ """
+ The download URL of the media record
+ """
+
+ url_expiry: str = pydantic_v1.Field(alias="urlExpiry")
+ """
+ The expiry date and time of the media record download URL
+ """ | logic: url_expiry should be dt.datetime type since it represents a timestamp, not a string. This ensures proper date validation and handling. |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,74 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import datetime as dt
+import typing
+
+from ....core.datetime_utils import serialize_datetime
+from ....core.pydantic_utilities import deep_union_pydantic_dicts, pydantic_v1
+
+
+class GetMediaUploadUrlRequest(pydantic_v1.BaseModel):
+ trace_id: str = pydantic_v1.Field(alias="traceId")
+ """
+ The trace ID associated with the media record
+ """
+
+ observation_id: typing.Optional[str] = pydantic_v1.Field(
+ alias="observationId", default=None
+ )
+ """
+ The observation ID associated with the media record. If the media record is associated directly with a trace, this will be null.
+ """
+
+ content_type: str = pydantic_v1.Field(alias="contentType")
+ """
+ The MIME type of the media record
+ """
+
+ content_length: int = pydantic_v1.Field(alias="contentLength")
+ """
+ The size of the media record in bytes
+ """
+
+ sha_256_hash: str = pydantic_v1.Field(alias="sha256Hash")
+ """
+ The SHA-256 hash of the media record
+ """
+
+ field: str = pydantic_v1.Field()
+ """
+ The trace / observation field the media record is associated with. This can be one of `input`, `output`, `metadata`
+ """ | logic: field should be constrained to only allow 'input', 'output', or 'metadata' values using Literal type |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,74 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import datetime as dt
+import typing
+
+from ....core.datetime_utils import serialize_datetime
+from ....core.pydantic_utilities import deep_union_pydantic_dicts, pydantic_v1
+
+
+class GetMediaUploadUrlRequest(pydantic_v1.BaseModel):
+ trace_id: str = pydantic_v1.Field(alias="traceId")
+ """
+ The trace ID associated with the media record
+ """
+
+ observation_id: typing.Optional[str] = pydantic_v1.Field(
+ alias="observationId", default=None
+ )
+ """
+ The observation ID associated with the media record. If the media record is associated directly with a trace, this will be null.
+ """
+
+ content_type: str = pydantic_v1.Field(alias="contentType")
+ """
+ The MIME type of the media record
+ """
+
+ content_length: int = pydantic_v1.Field(alias="contentLength")
+ """
+ The size of the media record in bytes
+ """ | logic: content_length should have a minimum value of 0 to prevent negative sizes |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,191 @@
+# This file was auto-generated by Fern from our API Definition.
+
+from __future__ import annotations
+
+import datetime as dt
+import typing
+
+from ....core.datetime_utils import serialize_datetime
+from ....core.pydantic_utilities import deep_union_pydantic_dicts, pydantic_v1
+from ...commons.types.score_source import ScoreSource
+from .get_scores_response_trace_data import GetScoresResponseTraceData
+
+
+class GetScoresResponseData_Numeric(pydantic_v1.BaseModel):
+ trace: GetScoresResponseTraceData
+ value: float
+ id: str
+ trace_id: str = pydantic_v1.Field(alias="traceId")
+ name: str
+ source: ScoreSource
+ observation_id: typing.Optional[str] = pydantic_v1.Field(
+ alias="observationId", default=None
+ )
+ timestamp: dt.datetime
+ created_at: dt.datetime = pydantic_v1.Field(alias="createdAt")
+ updated_at: dt.datetime = pydantic_v1.Field(alias="updatedAt")
+ author_user_id: typing.Optional[str] = pydantic_v1.Field(
+ alias="authorUserId", default=None
+ )
+ comment: typing.Optional[str] = None
+ config_id: typing.Optional[str] = pydantic_v1.Field(alias="configId", default=None)
+ queue_id: typing.Optional[str] = pydantic_v1.Field(alias="queueId", default=None)
+ data_type: typing.Literal["NUMERIC"] = pydantic_v1.Field(
+ alias="dataType", default="NUMERIC"
+ )
+
+ def json(self, **kwargs: typing.Any) -> str:
+ kwargs_with_defaults: typing.Any = {
+ "by_alias": True,
+ "exclude_unset": True,
+ **kwargs,
+ }
+ return super().json(**kwargs_with_defaults)
+
+ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]:
+ kwargs_with_defaults_exclude_unset: typing.Any = {
+ "by_alias": True,
+ "exclude_unset": True,
+ **kwargs,
+ }
+ kwargs_with_defaults_exclude_none: typing.Any = {
+ "by_alias": True,
+ "exclude_none": True,
+ **kwargs,
+ }
+
+ return deep_union_pydantic_dicts(
+ super().dict(**kwargs_with_defaults_exclude_unset),
+ super().dict(**kwargs_with_defaults_exclude_none),
+ )
+
+ class Config:
+ frozen = True
+ smart_union = True
+ allow_population_by_field_name = True
+ populate_by_name = True
+ extra = pydantic_v1.Extra.allow
+ json_encoders = {dt.datetime: serialize_datetime}
+
+
+class GetScoresResponseData_Categorical(pydantic_v1.BaseModel):
+ trace: GetScoresResponseTraceData
+ value: typing.Optional[float] = None
+ string_value: str = pydantic_v1.Field(alias="stringValue")
+ id: str
+ trace_id: str = pydantic_v1.Field(alias="traceId")
+ name: str
+ source: ScoreSource
+ observation_id: typing.Optional[str] = pydantic_v1.Field(
+ alias="observationId", default=None
+ )
+ timestamp: dt.datetime
+ created_at: dt.datetime = pydantic_v1.Field(alias="createdAt")
+ updated_at: dt.datetime = pydantic_v1.Field(alias="updatedAt")
+ author_user_id: typing.Optional[str] = pydantic_v1.Field(
+ alias="authorUserId", default=None
+ )
+ comment: typing.Optional[str] = None
+ config_id: typing.Optional[str] = pydantic_v1.Field(alias="configId", default=None)
+ queue_id: typing.Optional[str] = pydantic_v1.Field(alias="queueId", default=None)
+ data_type: typing.Literal["CATEGORICAL"] = pydantic_v1.Field(
+ alias="dataType", default="CATEGORICAL"
+ )
+
+ def json(self, **kwargs: typing.Any) -> str:
+ kwargs_with_defaults: typing.Any = {
+ "by_alias": True,
+ "exclude_unset": True,
+ **kwargs,
+ }
+ return super().json(**kwargs_with_defaults)
+
+ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]:
+ kwargs_with_defaults_exclude_unset: typing.Any = {
+ "by_alias": True,
+ "exclude_unset": True,
+ **kwargs,
+ }
+ kwargs_with_defaults_exclude_none: typing.Any = {
+ "by_alias": True,
+ "exclude_none": True,
+ **kwargs,
+ }
+
+ return deep_union_pydantic_dicts(
+ super().dict(**kwargs_with_defaults_exclude_unset),
+ super().dict(**kwargs_with_defaults_exclude_none),
+ )
+
+ class Config:
+ frozen = True
+ smart_union = True
+ allow_population_by_field_name = True
+ populate_by_name = True
+ extra = pydantic_v1.Extra.allow
+ json_encoders = {dt.datetime: serialize_datetime}
+
+
+class GetScoresResponseData_Boolean(pydantic_v1.BaseModel):
+ trace: GetScoresResponseTraceData
+ value: float
+ string_value: str = pydantic_v1.Field(alias="stringValue") | logic: Boolean score model has inconsistent value types - using both float and string_value for what should be a boolean value. This could cause data integrity issues. |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -1,8 +1,7 @@
# This file was auto-generated by Fern from our API Definition.
-
-from langfuse.api.core.http_client import get_request_body
-from langfuse.api.core.request_options import RequestOptions
+from finto.core.http_client import get_request_body
+from finto.core.request_options import RequestOptions | logic: Import paths changed from 'langfuse.api.core' to 'finto.core' - this seems incorrect as it's importing from a different package namespace. Should these still be using the langfuse namespace? |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -215,15 +213,31 @@ def _extract_chat_response(kwargs: any):
"role": kwargs.get("role", None),
}
+ audio_content = None
+
if kwargs.get("function_call") is not None:
response.update({"function_call": kwargs["function_call"]})
if kwargs.get("tool_calls") is not None:
response.update({"tool_calls": kwargs["tool_calls"]})
+ if kwargs.get("audio") is not None:
+ audio = kwargs["audio"].__dict__
+
+ audio_content = [
+ {"type": "text", "text": audio.get("transcript", None)},
+ {
+ "type": "output_audio",
+ "output_audio": {
+ "data": audio.get("data", None),
+ "format": audio.get("format", "wav"),
+ },
+ },
+ ] | logic: Audio content extraction assumes audio object has __dict__ attribute - may fail for custom audio response objects |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -215,15 +213,31 @@ def _extract_chat_response(kwargs: any):
"role": kwargs.get("role", None),
}
+ audio_content = None
+
if kwargs.get("function_call") is not None:
response.update({"function_call": kwargs["function_call"]})
if kwargs.get("tool_calls") is not None:
response.update({"tool_calls": kwargs["tool_calls"]})
+ if kwargs.get("audio") is not None:
+ audio = kwargs["audio"].__dict__
+
+ audio_content = [
+ {"type": "text", "text": audio.get("transcript", None)},
+ {
+ "type": "output_audio",
+ "output_audio": {
+ "data": audio.get("data", None),
+ "format": audio.get("format", "wav"),
+ },
+ },
+ ]
+
response.update(
{
- "content": kwargs.get("content", None),
+ "content": kwargs.get("content", None) or audio_content,
} | logic: Using 'or' operator for content fallback could cause issues if content is an empty string or false-y value |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -2211,3 +2210,36 @@ def _generate_random_dict(n: int, key_length: int = 8) -> Dict[str, Any]:
print(f"Full execution took {duration_full}ms")
assert duration_full > 1000, "Full execution should take longer than 1 second"
+
+
+def test_multimodal():
+ import base64
+
+ from langsmith.wrappers import wrap_openai
+ from openai import OpenAI
+
+ client = wrap_openai(OpenAI())
+
+ def encode_image(image_path):
+ with open(image_path, "rb") as image_file:
+ return base64.b64encode(image_file.read()).decode("utf-8")
+
+ image_path = "static/puton.jpg"
+ base64_image = encode_image(image_path)
+
+ response = client.chat.completions.create(
+ model="gpt-4o-mini",
+ messages=[ | logic: model='gpt-4o-mini' appears to be a typo - should likely be 'gpt-4-vision-preview' |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -2211,3 +2210,36 @@ def _generate_random_dict(n: int, key_length: int = 8) -> Dict[str, Any]:
print(f"Full execution took {duration_full}ms")
assert duration_full > 1000, "Full execution should take longer than 1 second"
+
+
+def test_multimodal(): | logic: test_multimodal() lacks assertions to verify the response and proper error handling for file operations |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -205,16 +205,16 @@ def _truncate_item_in_place(
break
# if item does not have body or input/output fields, drop the event
- if "body" not in item or (
- "input" not in item["body"] and "output" not in item["body"]
+ if "body" not in event or (
+ "input" not in event["body"] and "output" not in event["body"]
): | logic: this check drops events that only have metadata, which may be valid events |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,196 @@
+"""@private"""
+
+import atexit
+import logging
+import queue
+from queue import Queue
+from typing import List, Optional
+
+from langfuse.api.client import FernLangfuse
+from langfuse.request import LangfuseClient
+from langfuse.types import MaskFunction
+from langfuse.utils import _get_timestamp
+
+from .ingestion_consumer import IngestionConsumer
+from .media_manager import MediaManager
+from .media_upload_consumer import MediaUploadConsumer
+from .media_upload_queue import MediaUploadQueue
+
+
+class TaskManager(object):
+ _log = logging.getLogger(__name__)
+ _ingestion_consumers: List[IngestionConsumer]
+ _enabled: bool
+ _threads: int
+ _media_upload_threads: int
+ _max_task_queue_size: int
+ _ingestion_queue: Queue
+ _media_upload_queue: MediaUploadQueue
+ _client: LangfuseClient
+ _api_client: FernLangfuse
+ _flush_at: int
+ _flush_interval: float
+ _max_retries: int
+ _public_key: str
+ _sdk_name: str
+ _sdk_version: str
+ _sdk_integration: str
+ _sample_rate: float
+ _mask: Optional[MaskFunction]
+
+ def __init__(
+ self,
+ *,
+ client: LangfuseClient,
+ api_client: FernLangfuse,
+ flush_at: int,
+ flush_interval: float,
+ max_retries: int,
+ threads: int,
+ media_upload_threads: int = 1,
+ public_key: str,
+ sdk_name: str,
+ sdk_version: str,
+ sdk_integration: str,
+ enabled: bool = True,
+ max_task_queue_size: int = 100_000,
+ sample_rate: float = 1,
+ mask: Optional[MaskFunction] = None,
+ ):
+ self._max_task_queue_size = max_task_queue_size
+ self._threads = threads
+ self._media_upload_threads = media_upload_threads
+ self._ingestion_queue = queue.Queue(self._max_task_queue_size)
+ self._media_upload_queue = MediaUploadQueue(self._max_task_queue_size)
+ self._media_manager = MediaManager(
+ api_client=api_client,
+ media_upload_queue=self._media_upload_queue,
+ max_retries=max_retries,
+ )
+ self._ingestion_consumers = []
+ self._media_upload_consumers = []
+ self._client = client
+ self._api_client = api_client
+ self._flush_at = flush_at
+ self._flush_interval = flush_interval
+ self._max_retries = max_retries
+ self._public_key = public_key
+ self._sdk_name = sdk_name
+ self._sdk_version = sdk_version
+ self._sdk_integration = sdk_integration
+ self._enabled = enabled
+ self._sample_rate = sample_rate
+ self._mask = mask
+
+ self.init_resources() | logic: init_resources() is called before atexit.register(), meaning cleanup could be registered before resources are fully initialized |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,196 @@
+"""@private"""
+
+import atexit
+import logging
+import queue
+from queue import Queue
+from typing import List, Optional
+
+from langfuse.api.client import FernLangfuse
+from langfuse.request import LangfuseClient
+from langfuse.types import MaskFunction
+from langfuse.utils import _get_timestamp
+
+from .ingestion_consumer import IngestionConsumer
+from .media_manager import MediaManager
+from .media_upload_consumer import MediaUploadConsumer
+from .media_upload_queue import MediaUploadQueue
+
+
+class TaskManager(object):
+ _log = logging.getLogger(__name__)
+ _ingestion_consumers: List[IngestionConsumer]
+ _enabled: bool
+ _threads: int
+ _media_upload_threads: int
+ _max_task_queue_size: int
+ _ingestion_queue: Queue
+ _media_upload_queue: MediaUploadQueue
+ _client: LangfuseClient
+ _api_client: FernLangfuse
+ _flush_at: int
+ _flush_interval: float
+ _max_retries: int
+ _public_key: str
+ _sdk_name: str
+ _sdk_version: str
+ _sdk_integration: str
+ _sample_rate: float
+ _mask: Optional[MaskFunction]
+
+ def __init__(
+ self,
+ *,
+ client: LangfuseClient,
+ api_client: FernLangfuse,
+ flush_at: int,
+ flush_interval: float,
+ max_retries: int,
+ threads: int,
+ media_upload_threads: int = 1,
+ public_key: str,
+ sdk_name: str,
+ sdk_version: str,
+ sdk_integration: str,
+ enabled: bool = True,
+ max_task_queue_size: int = 100_000,
+ sample_rate: float = 1,
+ mask: Optional[MaskFunction] = None,
+ ):
+ self._max_task_queue_size = max_task_queue_size
+ self._threads = threads
+ self._media_upload_threads = media_upload_threads
+ self._ingestion_queue = queue.Queue(self._max_task_queue_size)
+ self._media_upload_queue = MediaUploadQueue(self._max_task_queue_size)
+ self._media_manager = MediaManager(
+ api_client=api_client,
+ media_upload_queue=self._media_upload_queue,
+ max_retries=max_retries,
+ )
+ self._ingestion_consumers = []
+ self._media_upload_consumers = []
+ self._client = client
+ self._api_client = api_client
+ self._flush_at = flush_at
+ self._flush_interval = flush_interval
+ self._max_retries = max_retries
+ self._public_key = public_key
+ self._sdk_name = sdk_name
+ self._sdk_version = sdk_version
+ self._sdk_integration = sdk_integration
+ self._enabled = enabled
+ self._sample_rate = sample_rate
+ self._mask = mask
+
+ self.init_resources()
+
+ # cleans up when the python interpreter closes
+ atexit.register(self.join)
+
+ def init_resources(self):
+ for i in range(self._threads):
+ ingestion_consumer = IngestionConsumer(
+ ingestion_queue=self._ingestion_queue,
+ identifier=i,
+ client=self._client,
+ media_manager=self._media_manager,
+ flush_at=self._flush_at,
+ flush_interval=self._flush_interval,
+ max_retries=self._max_retries,
+ public_key=self._public_key,
+ sdk_name=self._sdk_name,
+ sdk_version=self._sdk_version,
+ sdk_integration=self._sdk_integration,
+ sample_rate=self._sample_rate,
+ mask=self._mask,
+ )
+ ingestion_consumer.start()
+ self._ingestion_consumers.append(ingestion_consumer) | logic: No error handling if thread.start() fails - could leave system in inconsistent state |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,196 @@
+"""@private"""
+
+import atexit
+import logging
+import queue
+from queue import Queue
+from typing import List, Optional
+
+from langfuse.api.client import FernLangfuse
+from langfuse.request import LangfuseClient
+from langfuse.types import MaskFunction
+from langfuse.utils import _get_timestamp
+
+from .ingestion_consumer import IngestionConsumer
+from .media_manager import MediaManager
+from .media_upload_consumer import MediaUploadConsumer
+from .media_upload_queue import MediaUploadQueue
+
+
+class TaskManager(object):
+ _log = logging.getLogger(__name__)
+ _ingestion_consumers: List[IngestionConsumer]
+ _enabled: bool
+ _threads: int
+ _media_upload_threads: int
+ _max_task_queue_size: int
+ _ingestion_queue: Queue
+ _media_upload_queue: MediaUploadQueue
+ _client: LangfuseClient
+ _api_client: FernLangfuse
+ _flush_at: int
+ _flush_interval: float
+ _max_retries: int
+ _public_key: str
+ _sdk_name: str
+ _sdk_version: str
+ _sdk_integration: str
+ _sample_rate: float
+ _mask: Optional[MaskFunction]
+
+ def __init__(
+ self,
+ *,
+ client: LangfuseClient,
+ api_client: FernLangfuse,
+ flush_at: int,
+ flush_interval: float,
+ max_retries: int,
+ threads: int,
+ media_upload_threads: int = 1,
+ public_key: str,
+ sdk_name: str,
+ sdk_version: str,
+ sdk_integration: str,
+ enabled: bool = True,
+ max_task_queue_size: int = 100_000,
+ sample_rate: float = 1,
+ mask: Optional[MaskFunction] = None,
+ ):
+ self._max_task_queue_size = max_task_queue_size
+ self._threads = threads
+ self._media_upload_threads = media_upload_threads
+ self._ingestion_queue = queue.Queue(self._max_task_queue_size)
+ self._media_upload_queue = MediaUploadQueue(self._max_task_queue_size)
+ self._media_manager = MediaManager(
+ api_client=api_client,
+ media_upload_queue=self._media_upload_queue,
+ max_retries=max_retries,
+ )
+ self._ingestion_consumers = []
+ self._media_upload_consumers = []
+ self._client = client
+ self._api_client = api_client
+ self._flush_at = flush_at
+ self._flush_interval = flush_interval
+ self._max_retries = max_retries
+ self._public_key = public_key
+ self._sdk_name = sdk_name
+ self._sdk_version = sdk_version
+ self._sdk_integration = sdk_integration
+ self._enabled = enabled
+ self._sample_rate = sample_rate
+ self._mask = mask
+
+ self.init_resources()
+
+ # cleans up when the python interpreter closes
+ atexit.register(self.join)
+
+ def init_resources(self):
+ for i in range(self._threads):
+ ingestion_consumer = IngestionConsumer(
+ ingestion_queue=self._ingestion_queue,
+ identifier=i,
+ client=self._client,
+ media_manager=self._media_manager,
+ flush_at=self._flush_at,
+ flush_interval=self._flush_interval,
+ max_retries=self._max_retries,
+ public_key=self._public_key,
+ sdk_name=self._sdk_name,
+ sdk_version=self._sdk_version,
+ sdk_integration=self._sdk_integration,
+ sample_rate=self._sample_rate,
+ mask=self._mask,
+ )
+ ingestion_consumer.start()
+ self._ingestion_consumers.append(ingestion_consumer)
+
+ for i in range(self._media_upload_threads):
+ media_upload_consumer = MediaUploadConsumer(
+ identifier=i,
+ media_manager=self._media_manager,
+ )
+ media_upload_consumer.start()
+ self._media_upload_consumers.append(media_upload_consumer)
+
+ def add_task(self, event: dict):
+ if not self._enabled:
+ return
+
+ try:
+ event["timestamp"] = _get_timestamp()
+
+ self._ingestion_queue.put(event, block=False)
+ except queue.Full:
+ self._log.warning("analytics-python queue is full")
+ return False
+ except Exception as e:
+ self._log.exception(f"Exception in adding task {e}")
+
+ return False
+
+ def flush(self):
+ """Force a flush from the internal queue to the server."""
+ self._log.debug("flushing ingestion and media upload queues")
+
+ # Ingestion queue
+ ingestion_queue_size = self._ingestion_queue.qsize()
+ self._ingestion_queue.join()
+ self._log.debug(
+ f"Successfully flushed ~{ingestion_queue_size} items from ingestion queue"
+ )
+
+ # Media upload queue
+ media_upload_queue_size = self._media_upload_queue.qsize()
+ self._media_upload_queue.join()
+ self._log.debug(
+ f"Successfully flushed ~{media_upload_queue_size} items from media upload queue"
+ )
+
+ def join(self):
+ """End the consumer threads once the queue is empty.
+
+ Blocks execution until finished
+ """
+ self._log.debug(f"joining {len(self._ingestion_consumers)} consumer threads")
+
+ # pause all consumers before joining them so we don't have to wait for multiple
+ # flush intervals to join them all.
+ for ingestion_consumer in self._ingestion_consumers:
+ ingestion_consumer.pause()
+
+ for media_upload_consumer in self._media_upload_consumers:
+ media_upload_consumer.pause() | logic: Race condition possible between pausing consumers and joining them - consumers could process new items after pause |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,196 @@
+"""@private"""
+
+import atexit
+import logging
+import queue
+from queue import Queue
+from typing import List, Optional
+
+from langfuse.api.client import FernLangfuse
+from langfuse.request import LangfuseClient
+from langfuse.types import MaskFunction
+from langfuse.utils import _get_timestamp
+
+from .ingestion_consumer import IngestionConsumer
+from .media_manager import MediaManager
+from .media_upload_consumer import MediaUploadConsumer
+from .media_upload_queue import MediaUploadQueue
+
+
+class TaskManager(object):
+ _log = logging.getLogger(__name__)
+ _ingestion_consumers: List[IngestionConsumer]
+ _enabled: bool
+ _threads: int
+ _media_upload_threads: int
+ _max_task_queue_size: int
+ _ingestion_queue: Queue
+ _media_upload_queue: MediaUploadQueue
+ _client: LangfuseClient
+ _api_client: FernLangfuse
+ _flush_at: int
+ _flush_interval: float
+ _max_retries: int
+ _public_key: str
+ _sdk_name: str
+ _sdk_version: str
+ _sdk_integration: str
+ _sample_rate: float
+ _mask: Optional[MaskFunction]
+
+ def __init__(
+ self,
+ *,
+ client: LangfuseClient,
+ api_client: FernLangfuse,
+ flush_at: int,
+ flush_interval: float,
+ max_retries: int,
+ threads: int,
+ media_upload_threads: int = 1,
+ public_key: str,
+ sdk_name: str,
+ sdk_version: str,
+ sdk_integration: str,
+ enabled: bool = True,
+ max_task_queue_size: int = 100_000,
+ sample_rate: float = 1,
+ mask: Optional[MaskFunction] = None,
+ ):
+ self._max_task_queue_size = max_task_queue_size
+ self._threads = threads
+ self._media_upload_threads = media_upload_threads
+ self._ingestion_queue = queue.Queue(self._max_task_queue_size)
+ self._media_upload_queue = MediaUploadQueue(self._max_task_queue_size)
+ self._media_manager = MediaManager(
+ api_client=api_client,
+ media_upload_queue=self._media_upload_queue,
+ max_retries=max_retries,
+ )
+ self._ingestion_consumers = []
+ self._media_upload_consumers = []
+ self._client = client
+ self._api_client = api_client
+ self._flush_at = flush_at
+ self._flush_interval = flush_interval
+ self._max_retries = max_retries
+ self._public_key = public_key
+ self._sdk_name = sdk_name
+ self._sdk_version = sdk_version
+ self._sdk_integration = sdk_integration
+ self._enabled = enabled
+ self._sample_rate = sample_rate
+ self._mask = mask
+
+ self.init_resources()
+
+ # cleans up when the python interpreter closes
+ atexit.register(self.join)
+
+ def init_resources(self):
+ for i in range(self._threads):
+ ingestion_consumer = IngestionConsumer(
+ ingestion_queue=self._ingestion_queue,
+ identifier=i,
+ client=self._client,
+ media_manager=self._media_manager,
+ flush_at=self._flush_at,
+ flush_interval=self._flush_interval,
+ max_retries=self._max_retries,
+ public_key=self._public_key,
+ sdk_name=self._sdk_name,
+ sdk_version=self._sdk_version,
+ sdk_integration=self._sdk_integration,
+ sample_rate=self._sample_rate,
+ mask=self._mask,
+ )
+ ingestion_consumer.start()
+ self._ingestion_consumers.append(ingestion_consumer)
+
+ for i in range(self._media_upload_threads):
+ media_upload_consumer = MediaUploadConsumer(
+ identifier=i,
+ media_manager=self._media_manager,
+ )
+ media_upload_consumer.start()
+ self._media_upload_consumers.append(media_upload_consumer)
+
+ def add_task(self, event: dict):
+ if not self._enabled:
+ return
+
+ try:
+ event["timestamp"] = _get_timestamp()
+
+ self._ingestion_queue.put(event, block=False)
+ except queue.Full:
+ self._log.warning("analytics-python queue is full")
+ return False
+ except Exception as e:
+ self._log.exception(f"Exception in adding task {e}")
+
+ return False
+
+ def flush(self):
+ """Force a flush from the internal queue to the server."""
+ self._log.debug("flushing ingestion and media upload queues")
+
+ # Ingestion queue
+ ingestion_queue_size = self._ingestion_queue.qsize()
+ self._ingestion_queue.join()
+ self._log.debug(
+ f"Successfully flushed ~{ingestion_queue_size} items from ingestion queue"
+ )
+
+ # Media upload queue
+ media_upload_queue_size = self._media_upload_queue.qsize()
+ self._media_upload_queue.join()
+ self._log.debug(
+ f"Successfully flushed ~{media_upload_queue_size} items from media upload queue"
+ )
+
+ def join(self):
+ """End the consumer threads once the queue is empty.
+
+ Blocks execution until finished
+ """
+ self._log.debug(f"joining {len(self._ingestion_consumers)} consumer threads")
+
+ # pause all consumers before joining them so we don't have to wait for multiple
+ # flush intervals to join them all.
+ for ingestion_consumer in self._ingestion_consumers:
+ ingestion_consumer.pause()
+
+ for media_upload_consumer in self._media_upload_consumers:
+ media_upload_consumer.pause()
+
+ for ingestion_consumer in self._ingestion_consumers:
+ try:
+ ingestion_consumer.join()
+ except RuntimeError:
+ # consumer thread has not started
+ pass
+
+ self._log.debug(
+ f"IngestionConsumer thread {ingestion_consumer._identifier} joined"
+ )
+
+ for media_upload_consumer in self._media_upload_consumers:
+ try:
+ media_upload_consumer.join()
+ except RuntimeError:
+ # consumer thread has not started
+ pass
+
+ self._log.debug(
+ f"MediaUploadConsumer thread {media_upload_consumer._identifier} joined"
+ )
+
+ def shutdown(self):
+ """Flush all messages and cleanly shutdown the client."""
+ self._log.debug("shutdown initiated")
+
+ self.flush()
+ self.join() | logic: flush() and join() could raise exceptions, leaving system in partially shutdown state |
langfuse-python | github_2023 | others | 996 | langfuse | greptile-apps[bot] | @@ -949,6 +1218,258 @@ client.ingestion.batch(
</dl>
+</dd>
+</dl>
+</details>
+
+## Media
+<details><summary><code>client.media.<a href="src/finto/resources/media/client.py">get</a>(...)</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Get a media record
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```python
+from finto.client import FernLangfuse
+
+client = FernLangfuse(
+ x_langfuse_sdk_name="YOUR_X_LANGFUSE_SDK_NAME",
+ x_langfuse_sdk_version="YOUR_X_LANGFUSE_SDK_VERSION",
+ x_langfuse_public_key="YOUR_X_LANGFUSE_PUBLIC_KEY",
+ username="YOUR_USERNAME",
+ password="YOUR_PASSWORD",
+ base_url="https://yourhost.com/path/to/api",
+)
+client.media.get(
+ media_id="string",
+)
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**media_id:** `str` — The unique langfuse identifier of a media record
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**request_options:** `typing.Optional[RequestOptions]` — Request-specific configuration.
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.media.<a href="src/finto/resources/media/client.py">patch</a>(...)</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Patch a media record
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```python
+import datetime
+
+from finto import PatchMediaBody
+from finto.client import FernLangfuse
+
+client = FernLangfuse(
+ x_langfuse_sdk_name="YOUR_X_LANGFUSE_SDK_NAME",
+ x_langfuse_sdk_version="YOUR_X_LANGFUSE_SDK_VERSION",
+ x_langfuse_public_key="YOUR_X_LANGFUSE_PUBLIC_KEY",
+ username="YOUR_USERNAME",
+ password="YOUR_PASSWORD",
+ base_url="https://yourhost.com/path/to/api",
+)
+client.media.patch(
+ media_id="string",
+ request=PatchMediaBody(
+ uploaded_at=datetime.datetime.fromisoformat(
+ "2024-01-15 09:30:00+00:00",
+ ),
+ upload_http_status=1,
+ upload_http_error="string",
+ upload_time_ms=1,
+ ),
+)
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**media_id:** `str` — The unique langfuse identifier of a media record
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**request:** `PatchMediaBody`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**request_options:** `typing.Optional[RequestOptions]` — Request-specific configuration.
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.media.<a href="src/finto/resources/media/client.py">get_upload_url</a>(...)</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Get a presigned upload URL for a media record
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```python
+from finto import GetMediaUploadUrlRequest
+from finto.client import FernLangfuse
+
+client = FernLangfuse(
+ x_langfuse_sdk_name="YOUR_X_LANGFUSE_SDK_NAME",
+ x_langfuse_sdk_version="YOUR_X_LANGFUSE_SDK_VERSION",
+ x_langfuse_public_key="YOUR_X_LANGFUSE_PUBLIC_KEY",
+ username="YOUR_USERNAME",
+ password="YOUR_PASSWORD",
+ base_url="https://yourhost.com/path/to/api",
+)
+client.media.get_upload_url(
+ request=GetMediaUploadUrlRequest(
+ trace_id="string",
+ observation_id="string",
+ content_length=1,
+ sha_256_hash="string",
+ field="string",
+ ), | logic: content_type parameter is missing from GetMediaUploadUrlRequest example, which is required for multimodal uploads |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,534 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import typing
+from json.decoder import JSONDecodeError
+
+from ...core.api_error import ApiError
+from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
+from ...core.jsonable_encoder import jsonable_encoder
+from ...core.pydantic_utilities import pydantic_v1
+from ...core.request_options import RequestOptions
+from ..commons.errors.access_denied_error import AccessDeniedError
+from ..commons.errors.error import Error
+from ..commons.errors.method_not_allowed_error import MethodNotAllowedError
+from ..commons.errors.not_found_error import NotFoundError
+from ..commons.errors.unauthorized_error import UnauthorizedError
+from ..commons.types.comment import Comment
+from .types.create_comment_request import CreateCommentRequest
+from .types.create_comment_response import CreateCommentResponse
+from .types.get_comments_response import GetCommentsResponse
+
+# this is used as the default value for optional parameters
+OMIT = typing.cast(typing.Any, ...)
+
+
+class CommentsClient:
+ def __init__(self, *, client_wrapper: SyncClientWrapper):
+ self._client_wrapper = client_wrapper
+
+ def create(
+ self,
+ *,
+ request: CreateCommentRequest,
+ request_options: typing.Optional[RequestOptions] = None,
+ ) -> CreateCommentResponse:
+ """
+ Create a comment. Comments may be attached to different object types (trace, observation, session, prompt).
+
+ Parameters
+ ----------
+ request : CreateCommentRequest
+
+ request_options : typing.Optional[RequestOptions]
+ Request-specific configuration.
+
+ Returns
+ -------
+ CreateCommentResponse
+
+ Examples
+ --------
+ from finto import CreateCommentRequest
+ from finto.client import FernLangfuse
+
+ client = FernLangfuse(
+ x_langfuse_sdk_name="YOUR_X_LANGFUSE_SDK_NAME",
+ x_langfuse_sdk_version="YOUR_X_LANGFUSE_SDK_VERSION",
+ x_langfuse_public_key="YOUR_X_LANGFUSE_PUBLIC_KEY",
+ username="YOUR_USERNAME",
+ password="YOUR_PASSWORD",
+ base_url="https://yourhost.com/path/to/api",
+ )
+ client.comments.create(
+ request=CreateCommentRequest(
+ project_id="string",
+ object_type="string",
+ object_id="string",
+ content="string",
+ author_user_id="string",
+ ),
+ )
+ """
+ _response = self._client_wrapper.httpx_client.request(
+ "api/public/comments",
+ method="POST",
+ json=request,
+ request_options=request_options,
+ omit=OMIT,
+ ) | logic: Request path should start with a forward slash ('/api/public/comments') to ensure consistent URL construction across different client configurations |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,534 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import typing
+from json.decoder import JSONDecodeError
+
+from ...core.api_error import ApiError
+from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
+from ...core.jsonable_encoder import jsonable_encoder
+from ...core.pydantic_utilities import pydantic_v1
+from ...core.request_options import RequestOptions
+from ..commons.errors.access_denied_error import AccessDeniedError
+from ..commons.errors.error import Error
+from ..commons.errors.method_not_allowed_error import MethodNotAllowedError
+from ..commons.errors.not_found_error import NotFoundError
+from ..commons.errors.unauthorized_error import UnauthorizedError
+from ..commons.types.comment import Comment
+from .types.create_comment_request import CreateCommentRequest
+from .types.create_comment_response import CreateCommentResponse
+from .types.get_comments_response import GetCommentsResponse
+
+# this is used as the default value for optional parameters
+OMIT = typing.cast(typing.Any, ...)
+
+
+class CommentsClient:
+ def __init__(self, *, client_wrapper: SyncClientWrapper):
+ self._client_wrapper = client_wrapper
+
+ def create(
+ self,
+ *,
+ request: CreateCommentRequest,
+ request_options: typing.Optional[RequestOptions] = None,
+ ) -> CreateCommentResponse:
+ """
+ Create a comment. Comments may be attached to different object types (trace, observation, session, prompt).
+
+ Parameters
+ ----------
+ request : CreateCommentRequest
+
+ request_options : typing.Optional[RequestOptions]
+ Request-specific configuration.
+
+ Returns
+ -------
+ CreateCommentResponse
+
+ Examples
+ --------
+ from finto import CreateCommentRequest
+ from finto.client import FernLangfuse
+
+ client = FernLangfuse(
+ x_langfuse_sdk_name="YOUR_X_LANGFUSE_SDK_NAME",
+ x_langfuse_sdk_version="YOUR_X_LANGFUSE_SDK_VERSION",
+ x_langfuse_public_key="YOUR_X_LANGFUSE_PUBLIC_KEY",
+ username="YOUR_USERNAME",
+ password="YOUR_PASSWORD",
+ base_url="https://yourhost.com/path/to/api",
+ )
+ client.comments.create(
+ request=CreateCommentRequest(
+ project_id="string",
+ object_type="string",
+ object_id="string",
+ content="string",
+ author_user_id="string",
+ ),
+ )
+ """
+ _response = self._client_wrapper.httpx_client.request(
+ "api/public/comments",
+ method="POST",
+ json=request,
+ request_options=request_options,
+ omit=OMIT,
+ )
+ try:
+ if 200 <= _response.status_code < 300:
+ return pydantic_v1.parse_obj_as(CreateCommentResponse, _response.json()) # type: ignore
+ if _response.status_code == 400:
+ raise Error(pydantic_v1.parse_obj_as(typing.Any, _response.json())) # type: ignore
+ if _response.status_code == 401:
+ raise UnauthorizedError(
+ pydantic_v1.parse_obj_as(typing.Any, _response.json())
+ ) # type: ignore
+ if _response.status_code == 403:
+ raise AccessDeniedError(
+ pydantic_v1.parse_obj_as(typing.Any, _response.json())
+ ) # type: ignore
+ if _response.status_code == 405:
+ raise MethodNotAllowedError(
+ pydantic_v1.parse_obj_as(typing.Any, _response.json())
+ ) # type: ignore
+ if _response.status_code == 404:
+ raise NotFoundError(
+ pydantic_v1.parse_obj_as(typing.Any, _response.json())
+ ) # type: ignore
+ _response_json = _response.json()
+ except JSONDecodeError:
+ raise ApiError(status_code=_response.status_code, body=_response.text)
+ raise ApiError(status_code=_response.status_code, body=_response_json) | logic: Final ApiError is raised unconditionally, which means successful responses in the 200-299 range will still raise an error if they reach this point |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,54 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import datetime as dt
+import typing
+
+from ....core.datetime_utils import serialize_datetime
+from ....core.pydantic_utilities import deep_union_pydantic_dicts, pydantic_v1
+from .comment_object_type import CommentObjectType
+
+
+class Comment(pydantic_v1.BaseModel):
+ id: str
+ project_id: str = pydantic_v1.Field(alias="projectId")
+ created_at: dt.datetime = pydantic_v1.Field(alias="createdAt")
+ updated_at: dt.datetime = pydantic_v1.Field(alias="updatedAt")
+ object_type: CommentObjectType = pydantic_v1.Field(alias="objectType")
+ object_id: str = pydantic_v1.Field(alias="objectId")
+ content: str
+ author_user_id: typing.Optional[str] = pydantic_v1.Field(
+ alias="authorUserId", default=None
+ )
+
+ def json(self, **kwargs: typing.Any) -> str:
+ kwargs_with_defaults: typing.Any = {
+ "by_alias": True,
+ "exclude_unset": True,
+ **kwargs,
+ }
+ return super().json(**kwargs_with_defaults)
+
+ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: | logic: Merging two dicts with different exclude settings could lead to unexpected behavior if fields are present in one but not the other |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,66 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import datetime as dt
+import typing
+
+from ....core.datetime_utils import serialize_datetime
+from ....core.pydantic_utilities import deep_union_pydantic_dicts, pydantic_v1
+
+
+class PatchMediaBody(pydantic_v1.BaseModel):
+ uploaded_at: dt.datetime = pydantic_v1.Field(alias="uploadedAt")
+ """
+ The date and time when the media record was uploaded
+ """
+
+ upload_http_status: int = pydantic_v1.Field(alias="uploadHttpStatus")
+ """
+ The HTTP status code of the upload
+ """ | logic: HTTP status field should have validation to ensure it's a valid HTTP status code (100-599) |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,66 @@
+# This file was auto-generated by Fern from our API Definition.
+
+import datetime as dt
+import typing
+
+from ....core.datetime_utils import serialize_datetime
+from ....core.pydantic_utilities import deep_union_pydantic_dicts, pydantic_v1
+
+
+class PatchMediaBody(pydantic_v1.BaseModel):
+ uploaded_at: dt.datetime = pydantic_v1.Field(alias="uploadedAt")
+ """
+ The date and time when the media record was uploaded
+ """
+
+ upload_http_status: int = pydantic_v1.Field(alias="uploadHttpStatus")
+ """
+ The HTTP status code of the upload
+ """
+
+ upload_http_error: typing.Optional[str] = pydantic_v1.Field(
+ alias="uploadHttpError", default=None
+ )
+ """
+ The HTTP error message of the upload
+ """
+
+ upload_time_ms: typing.Optional[int] = pydantic_v1.Field(
+ alias="uploadTimeMs", default=None
+ )
+ """
+ The time in milliseconds it took to upload the media record
+ """ | logic: upload_time_ms should have validation to ensure it's a positive integer |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,200 @@
+"""This module contains the LangfuseMedia class, which is used to wrap media objects for upload to Langfuse."""
+
+import base64
+import hashlib
+import logging
+import os
+from typing import Optional, cast
+
+from langfuse.api import MediaContentType
+from langfuse.types import ParsedMediaReference
+
+
+class LangfuseMedia:
+ """A class for wrapping media objects for upload to Langfuse.
+
+ This class handles the preparation and formatting of media content for Langfuse,
+ supporting both base64 data URIs and raw content bytes.
+
+ Args:
+ obj (Optional[object]): The source object to be wrapped. Can be accessed via the `obj` attribute.
+ base64_data_uri (Optional[str]): A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type (Optional[str]): The MIME type of the media content when providing raw bytes.
+ content_bytes (Optional[bytes]): Raw bytes of the media content.
+ file_path (Optional[str]): The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+
+ Raises:
+ ValueError: If neither base64_data_uri or the combination of content_bytes
+ and content_type is provided.
+ """
+
+ obj: object
+
+ _log = logging.getLogger(__name__)
+ _content_bytes: Optional[bytes]
+ _content_type: Optional[MediaContentType]
+ _source: Optional[str]
+ _media_id: Optional[str]
+
+ def __init__(
+ self,
+ *,
+ obj: Optional[object] = None,
+ base64_data_uri: Optional[str] = None,
+ content_type: Optional[MediaContentType] = None,
+ content_bytes: Optional[bytes] = None,
+ file_path: Optional[str] = None,
+ ):
+ """Initialize a LangfuseMedia object.
+
+ Args:
+ obj: The object to wrap.
+
+ base64_data_uri: A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type: The MIME type of the media content when providing raw bytes or reading from a file.
+ content_bytes: Raw bytes of the media content.
+ file_path: The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+ """
+ self.obj = obj
+ self._media_id = None
+
+ if base64_data_uri is not None:
+ parsed_data = self._parse_base64_data_uri(base64_data_uri)
+ self._content_bytes, self._content_type = parsed_data
+ self._source = "base64_data_uri"
+
+ elif content_bytes is not None and content_type is not None:
+ self._content_type = content_type
+ self._content_bytes = content_bytes
+ self._source = "bytes"
+ elif (
+ file_path is not None
+ and content_type is not None
+ and os.path.exists(file_path)
+ ):
+ self._content_bytes = self._read_file(file_path)
+ self._content_type = content_type if self._content_bytes else None
+ self._source = "file" if self._content_bytes else None
+ else:
+ self._log.error(
+ "base64_data_uri, or content_bytes and content_type, or file_path must be provided to LangfuseMedia"
+ )
+
+ self._content_bytes = None
+ self._content_type = None
+ self._source = None
+
+ def _read_file(self, file_path: str) -> Optional[bytes]:
+ try:
+ with open(file_path, "rb") as file:
+ return file.read()
+ except Exception as e:
+ self._log.error(f"Error reading file at path {file_path}", exc_info=e)
+
+ return None
+
+ @property
+ def _content_length(self) -> int | None:
+ return len(self._content_bytes) if self._content_bytes else None
+
+ @property
+ def _content_sha256_hash(self) -> str | None:
+ if self._content_bytes is None:
+ return None
+
+ sha256_hash_bytes = hashlib.sha256(self._content_bytes).digest()
+
+ return base64.b64encode(sha256_hash_bytes).decode("utf-8")
+
+ @property
+ def _reference_string(self) -> str | None:
+ if self._content_type is None or self._source is None or self._media_id is None:
+ return None
+
+ return f"@@@langfuseMedia:type={self._content_type}|id={self._media_id}|source={self._source}@@@"
+
+ @staticmethod
+ def parse_reference_string(reference_string: str) -> ParsedMediaReference:
+ """Parse a media reference string into a ParsedMediaReference.
+
+ Example reference string:
+ "@@@langfuseMedia:type=image/jpeg|id=some-uuid|source=base64_data_uri@@@"
+
+ Args:
+ reference_string: The reference string to parse.
+
+ Returns:
+ A TypedDict with the media_id, source, and content_type.
+
+ Raises:
+ ValueError: If the reference string is empty or not a string.
+ ValueError: If the reference string does not start with "@@@langfuseMedia:type=".
+ ValueError: If the reference string does not end with "@@@".
+ ValueError: If the reference string is missing required fields.
+ """
+ if not reference_string:
+ raise ValueError("Reference string is empty")
+
+ if not isinstance(reference_string, str):
+ raise ValueError("Reference string is not a string")
+
+ if not reference_string.startswith("@@@langfuseMedia:type="):
+ raise ValueError(
+ "Reference string does not start with '@@@langfuseMedia:type='"
+ )
+
+ if not reference_string.endswith("@@@"):
+ raise ValueError("Reference string does not end with '@@@'")
+
+ content = reference_string.removeprefix("@@@langfuseMedia:").removesuffix("@@@")
+
+ # Split into key-value pairs
+ pairs = content.split("|")
+ parsed_data = {}
+
+ for pair in pairs:
+ key, value = pair.split("=", 1)
+ parsed_data[key] = value | logic: no validation of key/value format - could raise unhandled exception if = is missing |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,200 @@
+"""This module contains the LangfuseMedia class, which is used to wrap media objects for upload to Langfuse."""
+
+import base64
+import hashlib
+import logging
+import os
+from typing import Optional, cast
+
+from langfuse.api import MediaContentType
+from langfuse.types import ParsedMediaReference
+
+
+class LangfuseMedia:
+ """A class for wrapping media objects for upload to Langfuse.
+
+ This class handles the preparation and formatting of media content for Langfuse,
+ supporting both base64 data URIs and raw content bytes.
+
+ Args:
+ obj (Optional[object]): The source object to be wrapped. Can be accessed via the `obj` attribute.
+ base64_data_uri (Optional[str]): A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type (Optional[str]): The MIME type of the media content when providing raw bytes.
+ content_bytes (Optional[bytes]): Raw bytes of the media content.
+ file_path (Optional[str]): The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+
+ Raises:
+ ValueError: If neither base64_data_uri or the combination of content_bytes
+ and content_type is provided.
+ """
+
+ obj: object
+
+ _log = logging.getLogger(__name__)
+ _content_bytes: Optional[bytes]
+ _content_type: Optional[MediaContentType]
+ _source: Optional[str]
+ _media_id: Optional[str]
+
+ def __init__(
+ self,
+ *,
+ obj: Optional[object] = None,
+ base64_data_uri: Optional[str] = None,
+ content_type: Optional[MediaContentType] = None,
+ content_bytes: Optional[bytes] = None,
+ file_path: Optional[str] = None,
+ ):
+ """Initialize a LangfuseMedia object.
+
+ Args:
+ obj: The object to wrap.
+
+ base64_data_uri: A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type: The MIME type of the media content when providing raw bytes or reading from a file.
+ content_bytes: Raw bytes of the media content.
+ file_path: The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+ """
+ self.obj = obj
+ self._media_id = None
+
+ if base64_data_uri is not None:
+ parsed_data = self._parse_base64_data_uri(base64_data_uri)
+ self._content_bytes, self._content_type = parsed_data
+ self._source = "base64_data_uri"
+
+ elif content_bytes is not None and content_type is not None:
+ self._content_type = content_type
+ self._content_bytes = content_bytes
+ self._source = "bytes"
+ elif (
+ file_path is not None
+ and content_type is not None
+ and os.path.exists(file_path)
+ ):
+ self._content_bytes = self._read_file(file_path)
+ self._content_type = content_type if self._content_bytes else None
+ self._source = "file" if self._content_bytes else None
+ else:
+ self._log.error(
+ "base64_data_uri, or content_bytes and content_type, or file_path must be provided to LangfuseMedia"
+ )
+
+ self._content_bytes = None
+ self._content_type = None
+ self._source = None
+
+ def _read_file(self, file_path: str) -> Optional[bytes]:
+ try:
+ with open(file_path, "rb") as file:
+ return file.read()
+ except Exception as e:
+ self._log.error(f"Error reading file at path {file_path}", exc_info=e)
+
+ return None
+
+ @property
+ def _content_length(self) -> int | None:
+ return len(self._content_bytes) if self._content_bytes else None
+
+ @property
+ def _content_sha256_hash(self) -> str | None:
+ if self._content_bytes is None:
+ return None
+
+ sha256_hash_bytes = hashlib.sha256(self._content_bytes).digest()
+
+ return base64.b64encode(sha256_hash_bytes).decode("utf-8")
+
+ @property
+ def _reference_string(self) -> str | None:
+ if self._content_type is None or self._source is None or self._media_id is None:
+ return None
+
+ return f"@@@langfuseMedia:type={self._content_type}|id={self._media_id}|source={self._source}@@@"
+
+ @staticmethod
+ def parse_reference_string(reference_string: str) -> ParsedMediaReference:
+ """Parse a media reference string into a ParsedMediaReference.
+
+ Example reference string:
+ "@@@langfuseMedia:type=image/jpeg|id=some-uuid|source=base64_data_uri@@@"
+
+ Args:
+ reference_string: The reference string to parse.
+
+ Returns:
+ A TypedDict with the media_id, source, and content_type.
+
+ Raises:
+ ValueError: If the reference string is empty or not a string.
+ ValueError: If the reference string does not start with "@@@langfuseMedia:type=".
+ ValueError: If the reference string does not end with "@@@".
+ ValueError: If the reference string is missing required fields.
+ """
+ if not reference_string:
+ raise ValueError("Reference string is empty")
+
+ if not isinstance(reference_string, str):
+ raise ValueError("Reference string is not a string")
+
+ if not reference_string.startswith("@@@langfuseMedia:type="):
+ raise ValueError(
+ "Reference string does not start with '@@@langfuseMedia:type='"
+ )
+
+ if not reference_string.endswith("@@@"):
+ raise ValueError("Reference string does not end with '@@@'")
+
+ content = reference_string.removeprefix("@@@langfuseMedia:").removesuffix("@@@")
+
+ # Split into key-value pairs
+ pairs = content.split("|")
+ parsed_data = {}
+
+ for pair in pairs:
+ key, value = pair.split("=", 1)
+ parsed_data[key] = value
+
+ # Verify all required fields are present
+ if not all(key in parsed_data for key in ["type", "id", "source"]):
+ raise ValueError("Missing required fields in reference string")
+
+ return ParsedMediaReference(
+ media_id=parsed_data["id"],
+ source=parsed_data["source"],
+ content_type=parsed_data["type"],
+ )
+
+ def _parse_base64_data_uri(
+ self, data: str
+ ) -> tuple[Optional[bytes], Optional[MediaContentType]]:
+ try:
+ if not data or not isinstance(data, str):
+ raise ValueError("Data URI is not a string")
+
+ if not data.startswith("data:"):
+ raise ValueError("Data URI does not start with 'data:'")
+
+ header, _, actual_data = data[5:].partition(",")
+ if not header or not actual_data:
+ raise ValueError("Invalid URI")
+
+ is_base64 = header.endswith(";base64")
+ if not is_base64:
+ raise ValueError("Data is not base64 encoded")
+
+ content_type = header[:-7] | logic: content_type extraction assumes ;base64 suffix - could break with additional parameters |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -40,6 +43,12 @@ def default(self, obj: Any):
# Timezone-awareness check
return serialize_datetime(obj)
+ if isinstance(obj, LangfuseMedia):
+ return (
+ obj._reference_string
+ or "<Failed to generate reference string for LangfuseMediaWrapper>"
+ ) | logic: Consider adding error handling for when _reference_string is None but the object exists. The current fallback message doesn't provide enough context about why the reference string generation failed. |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -1457,3 +1460,28 @@ def main():
if o.parent_observation_id == mock_parent_observation_id
]
assert len(child_observations) == 2
+
+
+def test_pdf_in_metadata():
+ mock_trace_id = create_uuid()
+
+ with open("static/bitcoin.pdf", "rb") as pdf_file:
+ pdf_bytes = pdf_file.read()
+
+ @observe()
+ def main():
+ langfuse_context.update_current_trace(
+ metadata={
+ "context": LangfuseMedia(
+ pdf_bytes, content_bytes=pdf_bytes, content_type="application/pdf"
+ ) | logic: Incorrect constructor usage - first positional argument is unused but passed. Remove pdf_bytes from first position. |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,106 @@
+import base64
+import pytest
+from langfuse.media import LangfuseMedia
+
+# Test data
+SAMPLE_JPEG_BYTES = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00"
+SAMPLE_BASE64_DATA_URI = (
+ "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QBARXhpZgAA"
+)
+
+
+def test_init_with_base64_data_uri():
+ media = LangfuseMedia(base64_data_uri=SAMPLE_BASE64_DATA_URI)
+ assert media._source == "base64_data_uri"
+ assert media._content_type == "image/jpeg"
+ assert media._content_bytes is not None
+
+
+def test_init_with_content_bytes():
+ media = LangfuseMedia(content_bytes=SAMPLE_JPEG_BYTES, content_type="image/jpeg")
+ assert media._source == "bytes"
+ assert media._content_type == "image/jpeg"
+ assert media._content_bytes == SAMPLE_JPEG_BYTES
+
+
+def test_init_with_invalid_input(): | logic: silently failing without raising errors on invalid initialization is dangerous - should test that appropriate warnings are logged |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,106 @@
+import base64
+import pytest
+from langfuse.media import LangfuseMedia
+
+# Test data
+SAMPLE_JPEG_BYTES = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00"
+SAMPLE_BASE64_DATA_URI = (
+ "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QBARXhpZgAA"
+)
+
+
+def test_init_with_base64_data_uri():
+ media = LangfuseMedia(base64_data_uri=SAMPLE_BASE64_DATA_URI)
+ assert media._source == "base64_data_uri"
+ assert media._content_type == "image/jpeg"
+ assert media._content_bytes is not None
+
+
+def test_init_with_content_bytes():
+ media = LangfuseMedia(content_bytes=SAMPLE_JPEG_BYTES, content_type="image/jpeg")
+ assert media._source == "bytes"
+ assert media._content_type == "image/jpeg"
+ assert media._content_bytes == SAMPLE_JPEG_BYTES
+
+
+def test_init_with_invalid_input():
+ # LangfuseMedia logs error but doesn't raise ValueError when initialized without required params
+ media = LangfuseMedia()
+ assert media._source is None
+ assert media._content_type is None
+ assert media._content_bytes is None
+
+ media = LangfuseMedia(content_bytes=SAMPLE_JPEG_BYTES) # Missing content_type
+ assert media._source is None
+ assert media._content_type is None
+ assert media._content_bytes is None
+
+ media = LangfuseMedia(content_type="image/jpeg") # Missing content_bytes
+ assert media._source is None
+ assert media._content_type is None
+ assert media._content_bytes is None
+
+
+def test_content_length():
+ media = LangfuseMedia(content_bytes=SAMPLE_JPEG_BYTES, content_type="image/jpeg")
+ assert media._content_length == len(SAMPLE_JPEG_BYTES)
+
+
+def test_content_sha256_hash():
+ media = LangfuseMedia(content_bytes=SAMPLE_JPEG_BYTES, content_type="image/jpeg")
+ assert media._content_sha256_hash is not None
+ # Hash should be base64 encoded
+ assert base64.b64decode(media._content_sha256_hash)
+ | logic: test only verifies hash is base64 decodable, but not that it's actually a valid SHA-256 hash of the content |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -390,15 +388,11 @@ def _get_input_from_func_args(
) -> Any:
# Remove implicitly passed "self" or "cls" argument for instance or class methods
logged_args = func_args[1:] if is_method else func_args
- raw_input = {
+ return {
"args": logged_args,
"kwargs": func_kwargs,
} | logic: Removing JSON serialization could allow non-serializable objects to pass through. Consider adding validation or documentation about supported input types. |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -446,13 +440,10 @@ def _handle_call_result(
)
end_time = observation_params["end_time"] or _get_timestamp()
- raw_output = observation_params["output"] or (
+ output = observation_params["output"] or (
result if result and capture_output else None
) | logic: Same concern with output handling - need to ensure non-serializable outputs are handled appropriately by downstream components. |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,202 @@
+"""@private"""
+
+import atexit
+import logging
+import queue
+from queue import Queue
+from typing import List, Optional
+
+from langfuse.api.client import FernLangfuse
+from langfuse.request import LangfuseClient
+from langfuse.types import MaskFunction
+from langfuse.utils import _get_timestamp
+
+from .ingestion_consumer import IngestionConsumer
+from .media_manager import MediaManager
+from .media_upload_consumer import MediaUploadConsumer
+from .media_upload_queue import MediaUploadQueue
+
+
+class TaskManager(object):
+ _log = logging.getLogger(__name__)
+ _ingestion_consumers: List[IngestionConsumer]
+ _enabled: bool
+ _threads: int
+ _media_upload_threads: int
+ _max_task_queue_size: int
+ _ingestion_queue: Queue
+ _media_upload_queue: MediaUploadQueue
+ _client: LangfuseClient
+ _api_client: FernLangfuse
+ _flush_at: int
+ _flush_interval: float
+ _max_retries: int
+ _public_key: str
+ _sdk_name: str
+ _sdk_version: str
+ _sdk_integration: str
+ _sample_rate: float
+ _mask: Optional[MaskFunction]
+
+ def __init__(
+ self,
+ *,
+ client: LangfuseClient,
+ api_client: FernLangfuse,
+ flush_at: int,
+ flush_interval: float,
+ max_retries: int,
+ threads: int,
+ media_upload_threads: int = 1,
+ public_key: str,
+ sdk_name: str,
+ sdk_version: str,
+ sdk_integration: str,
+ enabled: bool = True,
+ max_task_queue_size: int = 100_000,
+ sample_rate: float = 1,
+ mask: Optional[MaskFunction] = None,
+ ):
+ self._max_task_queue_size = max_task_queue_size
+ self._threads = threads
+ self._media_upload_threads = media_upload_threads
+ self._ingestion_queue = queue.Queue(self._max_task_queue_size)
+ self._media_upload_queue = MediaUploadQueue(self._max_task_queue_size)
+ self._media_manager = MediaManager(
+ api_client=api_client,
+ media_upload_queue=self._media_upload_queue,
+ max_retries=max_retries,
+ )
+ self._ingestion_consumers = []
+ self._media_upload_consumers = []
+ self._client = client
+ self._api_client = api_client
+ self._flush_at = flush_at
+ self._flush_interval = flush_interval
+ self._max_retries = max_retries
+ self._public_key = public_key
+ self._sdk_name = sdk_name
+ self._sdk_version = sdk_version
+ self._sdk_integration = sdk_integration
+ self._enabled = enabled
+ self._sample_rate = sample_rate
+ self._mask = mask
+
+ self.init_resources()
+
+ # cleans up when the python interpreter closes
+ atexit.register(self.join)
+
+ def init_resources(self):
+ for i in range(self._threads):
+ ingestion_consumer = IngestionConsumer(
+ ingestion_queue=self._ingestion_queue,
+ identifier=i,
+ client=self._client,
+ media_manager=self._media_manager,
+ flush_at=self._flush_at,
+ flush_interval=self._flush_interval,
+ max_retries=self._max_retries,
+ public_key=self._public_key,
+ sdk_name=self._sdk_name,
+ sdk_version=self._sdk_version,
+ sdk_integration=self._sdk_integration,
+ sample_rate=self._sample_rate,
+ mask=self._mask,
+ )
+ ingestion_consumer.start()
+ self._ingestion_consumers.append(ingestion_consumer)
+
+ for i in range(self._media_upload_threads):
+ media_upload_consumer = MediaUploadConsumer(
+ identifier=i,
+ media_manager=self._media_manager,
+ )
+ media_upload_consumer.start()
+ self._media_upload_consumers.append(media_upload_consumer)
+
+ def add_task(self, event: dict):
+ if not self._enabled:
+ return
+
+ try:
+ event["timestamp"] = _get_timestamp()
+
+ self._ingestion_queue.put(event, block=False)
+ except queue.Full:
+ self._log.warning("analytics-python queue is full")
+ return False
+ except Exception as e:
+ self._log.exception(f"Exception in adding task {e}")
+
+ return False
+
+ def flush(self):
+ """Force a flush from the internal queue to the server."""
+ self._log.debug("flushing ingestion and media upload queues")
+
+ # Ingestion queue
+ ingestion_queue_size = self._ingestion_queue.qsize()
+ self._ingestion_queue.join()
+ self._log.debug(
+ f"Successfully flushed ~{ingestion_queue_size} items from ingestion queue"
+ )
+
+ # Media upload queue
+ media_upload_queue_size = self._media_upload_queue.qsize()
+ self._media_upload_queue.join()
+ self._log.debug(
+ f"Successfully flushed ~{media_upload_queue_size} items from media upload queue"
+ )
+
+ def join(self):
+ """End the consumer threads once the queue is empty.
+
+ Blocks execution until finished
+ """
+ self._log.debug(
+ f"joining {len(self._ingestion_consumers)} ingestion consumer threads"
+ )
+
+ # pause all consumers before joining them so we don't have to wait for multiple
+ # flush intervals to join them all.
+ for ingestion_consumer in self._ingestion_consumers:
+ ingestion_consumer.pause()
+
+ for media_upload_consumer in self._media_upload_consumers:
+ media_upload_consumer.pause() | logic: Pause media upload consumers after ingestion consumers - could cause deadlock if media upload depends on ingestion |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,200 @@
+"""This module contains the LangfuseMedia class, which is used to wrap media objects for upload to Langfuse."""
+
+import base64
+import hashlib
+import logging
+import os
+from typing import Optional, cast
+
+from langfuse.api import MediaContentType
+from langfuse.types import ParsedMediaReference
+
+
+class LangfuseMedia:
+ """A class for wrapping media objects for upload to Langfuse.
+
+ This class handles the preparation and formatting of media content for Langfuse,
+ supporting both base64 data URIs and raw content bytes.
+
+ Args:
+ obj (Optional[object]): The source object to be wrapped. Can be accessed via the `obj` attribute.
+ base64_data_uri (Optional[str]): A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type (Optional[str]): The MIME type of the media content when providing raw bytes.
+ content_bytes (Optional[bytes]): Raw bytes of the media content.
+ file_path (Optional[str]): The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+
+ Raises:
+ ValueError: If neither base64_data_uri or the combination of content_bytes
+ and content_type is provided.
+ """
+
+ obj: object
+
+ _log = logging.getLogger(__name__)
+ _content_bytes: Optional[bytes]
+ _content_type: Optional[MediaContentType]
+ _source: Optional[str]
+ _media_id: Optional[str]
+
+ def __init__(
+ self,
+ *,
+ obj: Optional[object] = None,
+ base64_data_uri: Optional[str] = None,
+ content_type: Optional[MediaContentType] = None,
+ content_bytes: Optional[bytes] = None,
+ file_path: Optional[str] = None,
+ ):
+ """Initialize a LangfuseMedia object.
+
+ Args:
+ obj: The object to wrap.
+
+ base64_data_uri: A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type: The MIME type of the media content when providing raw bytes or reading from a file.
+ content_bytes: Raw bytes of the media content.
+ file_path: The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+ """
+ self.obj = obj
+ self._media_id = None
+
+ if base64_data_uri is not None:
+ parsed_data = self._parse_base64_data_uri(base64_data_uri)
+ self._content_bytes, self._content_type = parsed_data
+ self._source = "base64_data_uri"
+
+ elif content_bytes is not None and content_type is not None:
+ self._content_type = content_type
+ self._content_bytes = content_bytes
+ self._source = "bytes"
+ elif (
+ file_path is not None
+ and content_type is not None
+ and os.path.exists(file_path)
+ ): | logic: file_path existence check should happen after content_type check to avoid unnecessary filesystem access |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,200 @@
+"""This module contains the LangfuseMedia class, which is used to wrap media objects for upload to Langfuse."""
+
+import base64
+import hashlib
+import logging
+import os
+from typing import Optional, cast
+
+from langfuse.api import MediaContentType
+from langfuse.types import ParsedMediaReference
+
+
+class LangfuseMedia:
+ """A class for wrapping media objects for upload to Langfuse.
+
+ This class handles the preparation and formatting of media content for Langfuse,
+ supporting both base64 data URIs and raw content bytes.
+
+ Args:
+ obj (Optional[object]): The source object to be wrapped. Can be accessed via the `obj` attribute.
+ base64_data_uri (Optional[str]): A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type (Optional[str]): The MIME type of the media content when providing raw bytes.
+ content_bytes (Optional[bytes]): Raw bytes of the media content.
+ file_path (Optional[str]): The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+
+ Raises:
+ ValueError: If neither base64_data_uri or the combination of content_bytes
+ and content_type is provided.
+ """
+
+ obj: object
+
+ _log = logging.getLogger(__name__)
+ _content_bytes: Optional[bytes]
+ _content_type: Optional[MediaContentType]
+ _source: Optional[str]
+ _media_id: Optional[str]
+
+ def __init__(
+ self,
+ *,
+ obj: Optional[object] = None,
+ base64_data_uri: Optional[str] = None,
+ content_type: Optional[MediaContentType] = None,
+ content_bytes: Optional[bytes] = None,
+ file_path: Optional[str] = None,
+ ):
+ """Initialize a LangfuseMedia object.
+
+ Args:
+ obj: The object to wrap.
+
+ base64_data_uri: A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type: The MIME type of the media content when providing raw bytes or reading from a file.
+ content_bytes: Raw bytes of the media content.
+ file_path: The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+ """
+ self.obj = obj
+ self._media_id = None
+
+ if base64_data_uri is not None:
+ parsed_data = self._parse_base64_data_uri(base64_data_uri)
+ self._content_bytes, self._content_type = parsed_data
+ self._source = "base64_data_uri"
+
+ elif content_bytes is not None and content_type is not None:
+ self._content_type = content_type
+ self._content_bytes = content_bytes
+ self._source = "bytes"
+ elif (
+ file_path is not None
+ and content_type is not None
+ and os.path.exists(file_path)
+ ):
+ self._content_bytes = self._read_file(file_path)
+ self._content_type = content_type if self._content_bytes else None
+ self._source = "file" if self._content_bytes else None
+ else:
+ self._log.error(
+ "base64_data_uri, or content_bytes and content_type, or file_path must be provided to LangfuseMedia"
+ )
+
+ self._content_bytes = None
+ self._content_type = None
+ self._source = None
+
+ def _read_file(self, file_path: str) -> Optional[bytes]:
+ try:
+ with open(file_path, "rb") as file:
+ return file.read()
+ except Exception as e:
+ self._log.error(f"Error reading file at path {file_path}", exc_info=e)
+
+ return None
+
+ @property
+ def _content_length(self) -> Optional[int]:
+ return len(self._content_bytes) if self._content_bytes else None
+
+ @property
+ def _content_sha256_hash(self) -> Optional[str]:
+ if self._content_bytes is None:
+ return None
+
+ sha256_hash_bytes = hashlib.sha256(self._content_bytes).digest()
+
+ return base64.b64encode(sha256_hash_bytes).decode("utf-8")
+
+ @property
+ def _reference_string(self) -> Optional[str]:
+ if self._content_type is None or self._source is None or self._media_id is None:
+ return None
+
+ return f"@@@langfuseMedia:type={self._content_type}|id={self._media_id}|source={self._source}@@@"
+
+ @staticmethod
+ def parse_reference_string(reference_string: str) -> ParsedMediaReference:
+ """Parse a media reference string into a ParsedMediaReference.
+
+ Example reference string:
+ "@@@langfuseMedia:type=image/jpeg|id=some-uuid|source=base64_data_uri@@@"
+
+ Args:
+ reference_string: The reference string to parse.
+
+ Returns:
+ A TypedDict with the media_id, source, and content_type.
+
+ Raises:
+ ValueError: If the reference string is empty or not a string.
+ ValueError: If the reference string does not start with "@@@langfuseMedia:type=".
+ ValueError: If the reference string does not end with "@@@".
+ ValueError: If the reference string is missing required fields.
+ """
+ if not reference_string:
+ raise ValueError("Reference string is empty")
+
+ if not isinstance(reference_string, str):
+ raise ValueError("Reference string is not a string")
+
+ if not reference_string.startswith("@@@langfuseMedia:type="):
+ raise ValueError(
+ "Reference string does not start with '@@@langfuseMedia:type='"
+ )
+
+ if not reference_string.endswith("@@@"):
+ raise ValueError("Reference string does not end with '@@@'")
+
+ content = reference_string.removeprefix("@@@langfuseMedia:").removesuffix("@@@")
+
+ # Split into key-value pairs
+ pairs = content.split("|")
+ parsed_data = {}
+
+ for pair in pairs:
+ key, value = pair.split("=", 1)
+ parsed_data[key] = value
+
+ # Verify all required fields are present
+ if not all(key in parsed_data for key in ["type", "id", "source"]):
+ raise ValueError("Missing required fields in reference string")
+
+ return ParsedMediaReference(
+ media_id=parsed_data["id"],
+ source=parsed_data["source"],
+ content_type=parsed_data["type"],
+ )
+
+ def _parse_base64_data_uri(
+ self, data: str
+ ) -> tuple[Optional[bytes], Optional[MediaContentType]]:
+ try:
+ if not data or not isinstance(data, str):
+ raise ValueError("Data URI is not a string")
+
+ if not data.startswith("data:"):
+ raise ValueError("Data URI does not start with 'data:'")
+
+ header, _, actual_data = data[5:].partition(",")
+ if not header or not actual_data:
+ raise ValueError("Invalid URI")
+
+ is_base64 = header.endswith(";base64")
+ if not is_base64:
+ raise ValueError("Data is not base64 encoded") | logic: should handle case where header contains base64 but not at the end (e.g. base64;charset=utf-8) |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,243 @@
+import logging
+from queue import Empty
+from typing import Any, Callable, Optional, TypeVar
+from typing_extensions import ParamSpec
+
+import time
+import requests
+import backoff
+
+from langfuse.api import GetMediaUploadUrlRequest, PatchMediaBody
+from langfuse.api.core import ApiError
+from langfuse.api.client import FernLangfuse
+from langfuse.media import LangfuseMedia
+from langfuse.utils import _get_timestamp
+
+from .media_upload_queue import MediaUploadQueue, UploadMediaJob
+
+
+T = TypeVar("T")
+P = ParamSpec("P")
+
+
+class MediaManager:
+ _log = logging.getLogger(__name__)
+
+ def __init__(
+ self,
+ *,
+ api_client: FernLangfuse,
+ media_upload_queue: MediaUploadQueue,
+ max_retries: Optional[int] = 3,
+ ):
+ self._api_client = api_client
+ self._queue = media_upload_queue
+ self._max_retries = max_retries
+
+ def process_next_media_upload(self):
+ try:
+ upload_job = self._queue.get(block=True, timeout=1)
+ self._log.debug(f"Processing upload for {upload_job['media_id']}")
+ self._process_upload_media_job(data=upload_job)
+
+ self._queue.task_done()
+ except Empty:
+ self._log.debug("Media upload queue is empty")
+ pass
+ except Exception as e:
+ self._log.error(f"Error uploading media: {e}")
+ self._queue.task_done()
+
+ def process_media_in_event(self, event: dict):
+ try:
+ if "body" not in event:
+ return
+
+ body = event["body"]
+ trace_id = body.get("traceId", None) or (
+ body.get("id", None)
+ if "type" in event and "trace" in event["type"]
+ else None
+ )
+
+ if trace_id is None:
+ raise ValueError("trace_id is required for media upload")
+
+ observation_id = (
+ body.get("id", None)
+ if "type" in event
+ and ("generation" in event["type"] or "span" in event["type"])
+ else None
+ )
+
+ multimodal_fields = ["input", "output", "metadata"]
+
+ for field in multimodal_fields:
+ if field in body:
+ processed_data = self._find_and_process_media(
+ data=body[field],
+ trace_id=trace_id,
+ observation_id=observation_id,
+ field=field,
+ )
+
+ body[field] = processed_data
+
+ except Exception as e:
+ self._log.error(f"Error processing multimodal event: {e}")
+
+ def _find_and_process_media(
+ self,
+ *,
+ data: Any,
+ trace_id: str,
+ observation_id: Optional[str],
+ field: str,
+ ):
+ seen = set()
+
+ def _process_data_recursively(data: Any):
+ if id(data) in seen:
+ return data
+
+ seen.add(id(data))
+
+ if isinstance(data, LangfuseMedia):
+ self._process_media(
+ media=data,
+ trace_id=trace_id,
+ observation_id=observation_id,
+ field=field,
+ )
+
+ return data
+
+ if isinstance(data, str) and data.startswith("data:"):
+ media = LangfuseMedia(
+ obj=data,
+ base64_data_uri=data,
+ )
+
+ self._process_media(
+ media=media,
+ trace_id=trace_id,
+ observation_id=observation_id,
+ field=field,
+ )
+
+ return media
+
+ if isinstance(data, list):
+ return [_process_data_recursively(item) for item in data]
+
+ if isinstance(data, dict):
+ return {
+ key: _process_data_recursively(value) for key, value in data.items()
+ }
+
+ return data
+
+ return _process_data_recursively(data)
+
+ def _process_media(
+ self,
+ *,
+ media: LangfuseMedia,
+ trace_id: str,
+ observation_id: Optional[str],
+ field: str,
+ ):
+ if (
+ media._content_length is None
+ or media._content_type is None
+ or media._content_sha256_hash is None
+ or media._content_bytes is None
+ ):
+ return
+
+ upload_url_response = self._request_with_backoff(
+ self._api_client.media.get_upload_url,
+ request=GetMediaUploadUrlRequest(
+ contentLength=media._content_length,
+ contentType=media._content_type,
+ sha256Hash=media._content_sha256_hash,
+ field=field,
+ traceId=trace_id,
+ observationId=observation_id,
+ ),
+ )
+
+ upload_url = upload_url_response.upload_url
+ media._media_id = upload_url_response.media_id # Important as this is will be used in the media reference string in serializer
+
+ if upload_url is not None:
+ self._log.debug(f"Scheduling upload for {media._media_id}")
+ self._queue.put(
+ item={
+ "upload_url": upload_url,
+ "media_id": media._media_id,
+ "content_bytes": media._content_bytes,
+ "content_type": media._content_type,
+ "content_sha256_hash": media._content_sha256_hash,
+ },
+ block=True,
+ timeout=1,
+ )
+
+ else:
+ self._log.debug(f"Media {media._media_id} already uploaded")
+
+ def _process_upload_media_job(
+ self,
+ *,
+ data: UploadMediaJob,
+ ):
+ upload_start_time = time.time()
+ upload_response = self._request_with_backoff(
+ requests.put,
+ data["upload_url"],
+ headers={
+ "Content-Type": data["content_type"],
+ "x-amz-checksum-sha256": data["content_sha256_hash"],
+ },
+ data=data["content_bytes"],
+ )
+ upload_time_ms = int((time.time() - upload_start_time) * 1000)
+
+ self._request_with_backoff(
+ self._api_client.media.patch,
+ media_id=data["media_id"],
+ request=PatchMediaBody(
+ uploadedAt=_get_timestamp(),
+ uploadHttpStatus=upload_response.status_code,
+ uploadHttpError=upload_response.text,
+ uploadTimeMs=upload_time_ms,
+ ),
+ )
+
+ self._log.debug(
+ f"Media upload completed for {data['media_id']} in {upload_time_ms}ms"
+ )
+
+ def _request_with_backoff(
+ self, func: Callable[P, T], *args: P.args, **kwargs: P.kwargs
+ ) -> T:
+ @backoff.on_exception(
+ backoff.expo, Exception, max_tries=self._max_retries, logger=None
+ )
+ def execute_task_with_backoff() -> T:
+ try:
+ return func(*args, **kwargs)
+ except ApiError as e:
+ if (
+ e.status_code is not None
+ and 400 <= e.status_code < 500
+ and (e.status_code) != 429
+ ):
+ raise e
+ except Exception as e:
+ raise e
+
+ raise Exception("Failed to execute task") | logic: This exception will never be reached since the previous except block re-raises all exceptions |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,200 @@
+"""This module contains the LangfuseMedia class, which is used to wrap media objects for upload to Langfuse."""
+
+import base64
+import hashlib
+import logging
+import os
+from typing import Optional, cast
+
+from langfuse.api import MediaContentType
+from langfuse.types import ParsedMediaReference
+
+
+class LangfuseMedia:
+ """A class for wrapping media objects for upload to Langfuse.
+
+ This class handles the preparation and formatting of media content for Langfuse,
+ supporting both base64 data URIs and raw content bytes.
+
+ Args:
+ obj (Optional[object]): The source object to be wrapped. Can be accessed via the `obj` attribute.
+ base64_data_uri (Optional[str]): A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type (Optional[str]): The MIME type of the media content when providing raw bytes.
+ content_bytes (Optional[bytes]): Raw bytes of the media content.
+ file_path (Optional[str]): The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+
+ Raises:
+ ValueError: If neither base64_data_uri or the combination of content_bytes
+ and content_type is provided.
+ """
+
+ obj: object
+
+ _log = logging.getLogger(__name__)
+ _content_bytes: Optional[bytes]
+ _content_type: Optional[MediaContentType]
+ _source: Optional[str]
+ _media_id: Optional[str]
+
+ def __init__(
+ self,
+ *,
+ obj: Optional[object] = None,
+ base64_data_uri: Optional[str] = None,
+ content_type: Optional[MediaContentType] = None,
+ content_bytes: Optional[bytes] = None,
+ file_path: Optional[str] = None,
+ ):
+ """Initialize a LangfuseMedia object.
+
+ Args:
+ obj: The object to wrap.
+
+ base64_data_uri: A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type: The MIME type of the media content when providing raw bytes or reading from a file.
+ content_bytes: Raw bytes of the media content.
+ file_path: The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+ """
+ self.obj = obj
+ self._media_id = None
+
+ if base64_data_uri is not None:
+ parsed_data = self._parse_base64_data_uri(base64_data_uri)
+ self._content_bytes, self._content_type = parsed_data
+ self._source = "base64_data_uri"
+
+ elif content_bytes is not None and content_type is not None:
+ self._content_type = content_type
+ self._content_bytes = content_bytes
+ self._source = "bytes"
+ elif (
+ file_path is not None
+ and content_type is not None
+ and os.path.exists(file_path)
+ ):
+ self._content_bytes = self._read_file(file_path)
+ self._content_type = content_type if self._content_bytes else None
+ self._source = "file" if self._content_bytes else None
+ else:
+ self._log.error(
+ "base64_data_uri, or content_bytes and content_type, or file_path must be provided to LangfuseMedia"
+ )
+
+ self._content_bytes = None
+ self._content_type = None
+ self._source = None
+
+ def _read_file(self, file_path: str) -> Optional[bytes]:
+ try:
+ with open(file_path, "rb") as file:
+ return file.read()
+ except Exception as e:
+ self._log.error(f"Error reading file at path {file_path}", exc_info=e)
+
+ return None
+
+ @property
+ def _content_length(self) -> Optional[int]:
+ return len(self._content_bytes) if self._content_bytes else None
+
+ @property
+ def _content_sha256_hash(self) -> Optional[str]:
+ if self._content_bytes is None:
+ return None
+
+ sha256_hash_bytes = hashlib.sha256(self._content_bytes).digest()
+
+ return base64.b64encode(sha256_hash_bytes).decode("utf-8")
+
+ @property
+ def _reference_string(self) -> Optional[str]:
+ if self._content_type is None or self._source is None or self._media_id is None:
+ return None
+
+ return f"@@@langfuseMedia:type={self._content_type}|id={self._media_id}|source={self._source}@@@"
+
+ @staticmethod
+ def parse_reference_string(reference_string: str) -> ParsedMediaReference:
+ """Parse a media reference string into a ParsedMediaReference.
+
+ Example reference string:
+ "@@@langfuseMedia:type=image/jpeg|id=some-uuid|source=base64_data_uri@@@"
+
+ Args:
+ reference_string: The reference string to parse.
+
+ Returns:
+ A TypedDict with the media_id, source, and content_type.
+
+ Raises:
+ ValueError: If the reference string is empty or not a string.
+ ValueError: If the reference string does not start with "@@@langfuseMedia:type=".
+ ValueError: If the reference string does not end with "@@@".
+ ValueError: If the reference string is missing required fields.
+ """
+ if not reference_string:
+ raise ValueError("Reference string is empty")
+
+ if not isinstance(reference_string, str):
+ raise ValueError("Reference string is not a string")
+
+ if not reference_string.startswith("@@@langfuseMedia:type="):
+ raise ValueError(
+ "Reference string does not start with '@@@langfuseMedia:type='"
+ )
+
+ if not reference_string.endswith("@@@"):
+ raise ValueError("Reference string does not end with '@@@'")
+
+ content = reference_string.removeprefix("@@@langfuseMedia:").removesuffix("@@@")
+
+ # Split into key-value pairs
+ pairs = content.split("|")
+ parsed_data = {}
+
+ for pair in pairs:
+ key, value = pair.split("=", 1)
+ parsed_data[key] = value
+
+ # Verify all required fields are present
+ if not all(key in parsed_data for key in ["type", "id", "source"]):
+ raise ValueError("Missing required fields in reference string")
+
+ return {
+ "media_id": parsed_data["id"],
+ "source": parsed_data["source"],
+ "content_type": parsed_data["type"],
+ } | logic: return type changed from ParsedMediaReference to dict - breaks type safety |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -172,14 +179,14 @@ def _truncate_item_in_place(
item_size,
)
- if "body" in item:
+ if "body" in event:
drop_candidates = ["input", "output", "metadata"]
sorted_field_sizes = sorted(
[
(
field,
- self._get_item_size((item["body"][field]))
- if field in item["body"]
+ self._get_item_size((event["body"][field]))
+ if field in event["body"]
else 0,
) | logic: potential KeyError if field exists in drop_candidates but event['body'][field] is None |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -191,10 +198,10 @@ def _truncate_item_in_place(
for _ in range(len(sorted_field_sizes)):
field_to_drop, size_to_drop = sorted_field_sizes.pop()
- if field_to_drop not in item["body"]:
+ if field_to_drop not in event["body"]:
continue
- item["body"][field_to_drop] = log_message
+ event["body"][field_to_drop] = log_message
item_size -= size_to_drop | logic: item_size calculation may be inaccurate after replacing field with log_message - should recalculate actual size |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,203 @@
+"""This module contains the LangfuseMedia class, which is used to wrap media objects for upload to Langfuse."""
+
+import base64
+import hashlib
+import logging
+import os
+from typing import Optional, cast
+
+from langfuse.api import MediaContentType
+from langfuse.types import ParsedMediaReference
+
+
+class LangfuseMedia:
+ """A class for wrapping media objects for upload to Langfuse.
+
+ This class handles the preparation and formatting of media content for Langfuse,
+ supporting both base64 data URIs and raw content bytes.
+
+ Args:
+ obj (Optional[object]): The source object to be wrapped. Can be accessed via the `obj` attribute.
+ base64_data_uri (Optional[str]): A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type (Optional[str]): The MIME type of the media content when providing raw bytes.
+ content_bytes (Optional[bytes]): Raw bytes of the media content.
+ file_path (Optional[str]): The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+
+ Raises:
+ ValueError: If neither base64_data_uri or the combination of content_bytes
+ and content_type is provided.
+ """
+
+ obj: object
+
+ _log = logging.getLogger(__name__)
+ _content_bytes: Optional[bytes]
+ _content_type: Optional[MediaContentType]
+ _source: Optional[str]
+ _media_id: Optional[str]
+
+ def __init__(
+ self,
+ *,
+ obj: Optional[object] = None,
+ base64_data_uri: Optional[str] = None,
+ content_type: Optional[MediaContentType] = None,
+ content_bytes: Optional[bytes] = None,
+ file_path: Optional[str] = None,
+ ):
+ """Initialize a LangfuseMedia object.
+
+ Args:
+ obj: The object to wrap.
+
+ base64_data_uri: A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type: The MIME type of the media content when providing raw bytes or reading from a file.
+ content_bytes: Raw bytes of the media content.
+ file_path: The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+ """
+ self.obj = obj
+ self._media_id = None
+
+ if base64_data_uri is not None:
+ parsed_data = self._parse_base64_data_uri(base64_data_uri)
+ self._content_bytes, self._content_type = parsed_data
+ self._source = "base64_data_uri"
+
+ elif content_bytes is not None and content_type is not None:
+ self._content_type = content_type
+ self._content_bytes = content_bytes
+ self._source = "bytes"
+ elif (
+ file_path is not None
+ and content_type is not None
+ and os.path.exists(file_path)
+ ):
+ self._content_bytes = self._read_file(file_path)
+ self._content_type = content_type if self._content_bytes else None
+ self._source = "file" if self._content_bytes else None
+ else:
+ self._log.error(
+ "base64_data_uri, or content_bytes and content_type, or file_path must be provided to LangfuseMedia"
+ )
+
+ self._content_bytes = None
+ self._content_type = None
+ self._source = None
+
+ def _read_file(self, file_path: str) -> Optional[bytes]:
+ try:
+ with open(file_path, "rb") as file:
+ return file.read()
+ except Exception as e:
+ self._log.error(f"Error reading file at path {file_path}", exc_info=e)
+
+ return None | logic: no error handling for file permissions or disk space issues |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,203 @@
+"""This module contains the LangfuseMedia class, which is used to wrap media objects for upload to Langfuse."""
+
+import base64
+import hashlib
+import logging
+import os
+from typing import Optional, cast
+
+from langfuse.api import MediaContentType
+from langfuse.types import ParsedMediaReference
+
+
+class LangfuseMedia:
+ """A class for wrapping media objects for upload to Langfuse.
+
+ This class handles the preparation and formatting of media content for Langfuse,
+ supporting both base64 data URIs and raw content bytes.
+
+ Args:
+ obj (Optional[object]): The source object to be wrapped. Can be accessed via the `obj` attribute.
+ base64_data_uri (Optional[str]): A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type (Optional[str]): The MIME type of the media content when providing raw bytes.
+ content_bytes (Optional[bytes]): Raw bytes of the media content.
+ file_path (Optional[str]): The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+
+ Raises:
+ ValueError: If neither base64_data_uri or the combination of content_bytes
+ and content_type is provided.
+ """
+
+ obj: object
+
+ _log = logging.getLogger(__name__)
+ _content_bytes: Optional[bytes]
+ _content_type: Optional[MediaContentType]
+ _source: Optional[str]
+ _media_id: Optional[str]
+
+ def __init__(
+ self,
+ *,
+ obj: Optional[object] = None,
+ base64_data_uri: Optional[str] = None,
+ content_type: Optional[MediaContentType] = None,
+ content_bytes: Optional[bytes] = None,
+ file_path: Optional[str] = None,
+ ):
+ """Initialize a LangfuseMedia object.
+
+ Args:
+ obj: The object to wrap.
+
+ base64_data_uri: A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type: The MIME type of the media content when providing raw bytes or reading from a file.
+ content_bytes: Raw bytes of the media content.
+ file_path: The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+ """
+ self.obj = obj
+ self._media_id = None
+
+ if base64_data_uri is not None:
+ parsed_data = self._parse_base64_data_uri(base64_data_uri)
+ self._content_bytes, self._content_type = parsed_data
+ self._source = "base64_data_uri"
+
+ elif content_bytes is not None and content_type is not None:
+ self._content_type = content_type
+ self._content_bytes = content_bytes
+ self._source = "bytes"
+ elif (
+ file_path is not None
+ and content_type is not None
+ and os.path.exists(file_path)
+ ):
+ self._content_bytes = self._read_file(file_path)
+ self._content_type = content_type if self._content_bytes else None
+ self._source = "file" if self._content_bytes else None
+ else:
+ self._log.error(
+ "base64_data_uri, or content_bytes and content_type, or file_path must be provided to LangfuseMedia"
+ )
+
+ self._content_bytes = None
+ self._content_type = None
+ self._source = None
+
+ def _read_file(self, file_path: str) -> Optional[bytes]:
+ try:
+ with open(file_path, "rb") as file:
+ return file.read()
+ except Exception as e:
+ self._log.error(f"Error reading file at path {file_path}", exc_info=e)
+
+ return None
+
+ @property
+ def _content_length(self) -> Optional[int]:
+ return len(self._content_bytes) if self._content_bytes else None
+
+ @property
+ def _content_sha256_hash(self) -> Optional[str]:
+ if self._content_bytes is None:
+ return None
+
+ sha256_hash_bytes = hashlib.sha256(self._content_bytes).digest()
+
+ return base64.b64encode(sha256_hash_bytes).decode("utf-8") | logic: no memory limit on hash calculation - could cause OOM with large files |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,203 @@
+"""This module contains the LangfuseMedia class, which is used to wrap media objects for upload to Langfuse."""
+
+import base64
+import hashlib
+import logging
+import os
+from typing import Optional, cast
+
+from langfuse.api import MediaContentType
+from langfuse.types import ParsedMediaReference
+
+
+class LangfuseMedia:
+ """A class for wrapping media objects for upload to Langfuse.
+
+ This class handles the preparation and formatting of media content for Langfuse,
+ supporting both base64 data URIs and raw content bytes.
+
+ Args:
+ obj (Optional[object]): The source object to be wrapped. Can be accessed via the `obj` attribute.
+ base64_data_uri (Optional[str]): A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type (Optional[str]): The MIME type of the media content when providing raw bytes.
+ content_bytes (Optional[bytes]): Raw bytes of the media content.
+ file_path (Optional[str]): The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+
+ Raises:
+ ValueError: If neither base64_data_uri or the combination of content_bytes
+ and content_type is provided.
+ """
+
+ obj: object
+
+ _log = logging.getLogger(__name__)
+ _content_bytes: Optional[bytes]
+ _content_type: Optional[MediaContentType]
+ _source: Optional[str]
+ _media_id: Optional[str]
+
+ def __init__(
+ self,
+ *,
+ obj: Optional[object] = None,
+ base64_data_uri: Optional[str] = None,
+ content_type: Optional[MediaContentType] = None,
+ content_bytes: Optional[bytes] = None,
+ file_path: Optional[str] = None,
+ ):
+ """Initialize a LangfuseMedia object.
+
+ Args:
+ obj: The object to wrap.
+
+ base64_data_uri: A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type: The MIME type of the media content when providing raw bytes or reading from a file.
+ content_bytes: Raw bytes of the media content.
+ file_path: The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+ """
+ self.obj = obj
+ self._media_id = None
+
+ if base64_data_uri is not None:
+ parsed_data = self._parse_base64_data_uri(base64_data_uri)
+ self._content_bytes, self._content_type = parsed_data
+ self._source = "base64_data_uri" | logic: check parsed_data for None before unpacking tuple |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,203 @@
+"""This module contains the LangfuseMedia class, which is used to wrap media objects for upload to Langfuse."""
+
+import base64
+import hashlib
+import logging
+import os
+from typing import Optional, cast, Tuple
+
+from langfuse.api import MediaContentType
+from langfuse.types import ParsedMediaReference
+
+
+class LangfuseMedia:
+ """A class for wrapping media objects for upload to Langfuse.
+
+ This class handles the preparation and formatting of media content for Langfuse,
+ supporting both base64 data URIs and raw content bytes.
+
+ Args:
+ obj (Optional[object]): The source object to be wrapped. Can be accessed via the `obj` attribute.
+ base64_data_uri (Optional[str]): A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type (Optional[str]): The MIME type of the media content when providing raw bytes.
+ content_bytes (Optional[bytes]): Raw bytes of the media content.
+ file_path (Optional[str]): The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+
+ Raises:
+ ValueError: If neither base64_data_uri or the combination of content_bytes
+ and content_type is provided.
+ """
+
+ obj: object
+
+ _log = logging.getLogger(__name__)
+ _content_bytes: Optional[bytes]
+ _content_type: Optional[MediaContentType]
+ _source: Optional[str]
+ _media_id: Optional[str]
+
+ def __init__(
+ self,
+ *,
+ obj: Optional[object] = None,
+ base64_data_uri: Optional[str] = None,
+ content_type: Optional[MediaContentType] = None,
+ content_bytes: Optional[bytes] = None,
+ file_path: Optional[str] = None,
+ ):
+ """Initialize a LangfuseMedia object.
+
+ Args:
+ obj: The object to wrap.
+
+ base64_data_uri: A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type: The MIME type of the media content when providing raw bytes or reading from a file.
+ content_bytes: Raw bytes of the media content.
+ file_path: The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+ """
+ self.obj = obj
+ self._media_id = None
+
+ if base64_data_uri is not None:
+ parsed_data = self._parse_base64_data_uri(base64_data_uri)
+ self._content_bytes, self._content_type = parsed_data
+ self._source = "base64_data_uri"
+
+ elif content_bytes is not None and content_type is not None:
+ self._content_type = content_type
+ self._content_bytes = content_bytes
+ self._source = "bytes"
+ elif (
+ file_path is not None
+ and content_type is not None
+ and os.path.exists(file_path)
+ ):
+ self._content_bytes = self._read_file(file_path)
+ self._content_type = content_type if self._content_bytes else None
+ self._source = "file" if self._content_bytes else None
+ else:
+ self._log.error(
+ "base64_data_uri, or content_bytes and content_type, or file_path must be provided to LangfuseMedia"
+ )
+
+ self._content_bytes = None
+ self._content_type = None
+ self._source = None
+
+ def _read_file(self, file_path: str) -> Optional[bytes]:
+ try:
+ with open(file_path, "rb") as file:
+ return file.read()
+ except Exception as e:
+ self._log.error(f"Error reading file at path {file_path}", exc_info=e)
+
+ return None
+
+ @property
+ def _content_length(self) -> Optional[int]:
+ return len(self._content_bytes) if self._content_bytes else None
+
+ @property
+ def _content_sha256_hash(self) -> Optional[str]:
+ if self._content_bytes is None:
+ return None
+
+ sha256_hash_bytes = hashlib.sha256(self._content_bytes).digest()
+
+ return base64.b64encode(sha256_hash_bytes).decode("utf-8")
+
+ @property
+ def _reference_string(self) -> Optional[str]:
+ if self._content_type is None or self._source is None or self._media_id is None:
+ return None
+
+ return f"@@@langfuseMedia:type={self._content_type}|id={self._media_id}|source={self._source}@@@"
+
+ @staticmethod
+ def parse_reference_string(reference_string: str) -> ParsedMediaReference:
+ """Parse a media reference string into a ParsedMediaReference.
+
+ Example reference string:
+ "@@@langfuseMedia:type=image/jpeg|id=some-uuid|source=base64_data_uri@@@"
+
+ Args:
+ reference_string: The reference string to parse.
+
+ Returns:
+ A TypedDict with the media_id, source, and content_type.
+
+ Raises:
+ ValueError: If the reference string is empty or not a string.
+ ValueError: If the reference string does not start with "@@@langfuseMedia:type=".
+ ValueError: If the reference string does not end with "@@@".
+ ValueError: If the reference string is missing required fields.
+ """
+ if not reference_string:
+ raise ValueError("Reference string is empty")
+
+ if not isinstance(reference_string, str):
+ raise ValueError("Reference string is not a string")
+
+ if not reference_string.startswith("@@@langfuseMedia:type="):
+ raise ValueError(
+ "Reference string does not start with '@@@langfuseMedia:type='"
+ )
+
+ if not reference_string.endswith("@@@"):
+ raise ValueError("Reference string does not end with '@@@'")
+
+ content = reference_string.removeprefix("@@@langfuseMedia:").removesuffix("@@@")
+
+ # Split into key-value pairs
+ pairs = content.split("|")
+ parsed_data = {}
+
+ for pair in pairs:
+ key, value = pair.split("=", 1)
+ parsed_data[key] = value
+
+ # Verify all required fields are present
+ if not all(key in parsed_data for key in ["type", "id", "source"]):
+ raise ValueError("Missing required fields in reference string")
+
+ return ParsedMediaReference(
+ media_id=parsed_data["id"],
+ source=parsed_data["source"],
+ content_type=parsed_data["type"],
+ )
+
+ def _parse_base64_data_uri(
+ self, data: str
+ ) -> Tuple[Optional[bytes], Optional[MediaContentType]]:
+ # Example data URI: data:image/jpeg;base64,/9j/4AAQ...
+ try:
+ if not data or not isinstance(data, str):
+ raise ValueError("Data URI is not a string")
+
+ if not data.startswith("data:"):
+ raise ValueError("Data URI does not start with 'data:'")
+
+ header, actual_data = data[5:].split(",", 1)
+ if not header or not actual_data:
+ raise ValueError("Invalid URI")
+
+ # Split header into parts and check for base64
+ header_parts = header.split(";")
+ if "base64" not in header_parts:
+ raise ValueError("Data is not base64 encoded")
+
+ # Content type is the first part
+ content_type = header_parts[0] | logic: content_type not validated against MediaContentType enum before casting |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,203 @@
+"""This module contains the LangfuseMedia class, which is used to wrap media objects for upload to Langfuse."""
+
+import base64
+import hashlib
+import logging
+import os
+from typing import Optional, cast, Tuple
+
+from langfuse.api import MediaContentType
+from langfuse.types import ParsedMediaReference
+
+
+class LangfuseMedia:
+ """A class for wrapping media objects for upload to Langfuse.
+
+ This class handles the preparation and formatting of media content for Langfuse,
+ supporting both base64 data URIs and raw content bytes.
+
+ Args:
+ obj (Optional[object]): The source object to be wrapped. Can be accessed via the `obj` attribute.
+ base64_data_uri (Optional[str]): A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type (Optional[str]): The MIME type of the media content when providing raw bytes.
+ content_bytes (Optional[bytes]): Raw bytes of the media content.
+ file_path (Optional[str]): The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+
+ Raises:
+ ValueError: If neither base64_data_uri or the combination of content_bytes
+ and content_type is provided.
+ """
+
+ obj: object
+
+ _log = logging.getLogger(__name__)
+ _content_bytes: Optional[bytes]
+ _content_type: Optional[MediaContentType]
+ _source: Optional[str]
+ _media_id: Optional[str]
+
+ def __init__(
+ self,
+ *,
+ obj: Optional[object] = None,
+ base64_data_uri: Optional[str] = None,
+ content_type: Optional[MediaContentType] = None,
+ content_bytes: Optional[bytes] = None,
+ file_path: Optional[str] = None,
+ ):
+ """Initialize a LangfuseMedia object.
+
+ Args:
+ obj: The object to wrap.
+
+ base64_data_uri: A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type: The MIME type of the media content when providing raw bytes or reading from a file.
+ content_bytes: Raw bytes of the media content.
+ file_path: The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+ """
+ self.obj = obj
+ self._media_id = None
+
+ if base64_data_uri is not None:
+ parsed_data = self._parse_base64_data_uri(base64_data_uri)
+ self._content_bytes, self._content_type = parsed_data
+ self._source = "base64_data_uri"
+
+ elif content_bytes is not None and content_type is not None:
+ self._content_type = content_type
+ self._content_bytes = content_bytes
+ self._source = "bytes"
+ elif (
+ file_path is not None
+ and content_type is not None
+ and os.path.exists(file_path)
+ ):
+ self._content_bytes = self._read_file(file_path)
+ self._content_type = content_type if self._content_bytes else None
+ self._source = "file" if self._content_bytes else None
+ else:
+ self._log.error(
+ "base64_data_uri, or content_bytes and content_type, or file_path must be provided to LangfuseMedia"
+ )
+
+ self._content_bytes = None
+ self._content_type = None
+ self._source = None
+
+ def _read_file(self, file_path: str) -> Optional[bytes]:
+ try:
+ with open(file_path, "rb") as file:
+ return file.read()
+ except Exception as e:
+ self._log.error(f"Error reading file at path {file_path}", exc_info=e)
+
+ return None
+
+ @property
+ def _content_length(self) -> Optional[int]:
+ return len(self._content_bytes) if self._content_bytes else None
+
+ @property
+ def _content_sha256_hash(self) -> Optional[str]:
+ if self._content_bytes is None:
+ return None
+
+ sha256_hash_bytes = hashlib.sha256(self._content_bytes).digest()
+
+ return base64.b64encode(sha256_hash_bytes).decode("utf-8")
+
+ @property
+ def _reference_string(self) -> Optional[str]:
+ if self._content_type is None or self._source is None or self._media_id is None:
+ return None
+
+ return f"@@@langfuseMedia:type={self._content_type}|id={self._media_id}|source={self._source}@@@"
+
+ @staticmethod
+ def parse_reference_string(reference_string: str) -> ParsedMediaReference:
+ """Parse a media reference string into a ParsedMediaReference.
+
+ Example reference string:
+ "@@@langfuseMedia:type=image/jpeg|id=some-uuid|source=base64_data_uri@@@"
+
+ Args:
+ reference_string: The reference string to parse.
+
+ Returns:
+ A TypedDict with the media_id, source, and content_type.
+
+ Raises:
+ ValueError: If the reference string is empty or not a string.
+ ValueError: If the reference string does not start with "@@@langfuseMedia:type=".
+ ValueError: If the reference string does not end with "@@@".
+ ValueError: If the reference string is missing required fields.
+ """
+ if not reference_string:
+ raise ValueError("Reference string is empty")
+
+ if not isinstance(reference_string, str):
+ raise ValueError("Reference string is not a string")
+
+ if not reference_string.startswith("@@@langfuseMedia:type="):
+ raise ValueError(
+ "Reference string does not start with '@@@langfuseMedia:type='"
+ )
+
+ if not reference_string.endswith("@@@"):
+ raise ValueError("Reference string does not end with '@@@'")
+
+ content = reference_string.removeprefix("@@@langfuseMedia:").removesuffix("@@@")
+
+ # Split into key-value pairs
+ pairs = content.split("|")
+ parsed_data = {}
+
+ for pair in pairs:
+ key, value = pair.split("=", 1)
+ parsed_data[key] = value
+
+ # Verify all required fields are present
+ if not all(key in parsed_data for key in ["type", "id", "source"]):
+ raise ValueError("Missing required fields in reference string")
+
+ return ParsedMediaReference(
+ media_id=parsed_data["id"],
+ source=parsed_data["source"],
+ content_type=parsed_data["type"],
+ )
+
+ def _parse_base64_data_uri(
+ self, data: str
+ ) -> Tuple[Optional[bytes], Optional[MediaContentType]]:
+ # Example data URI: data:image/jpeg;base64,/9j/4AAQ...
+ try:
+ if not data or not isinstance(data, str):
+ raise ValueError("Data URI is not a string")
+
+ if not data.startswith("data:"):
+ raise ValueError("Data URI does not start with 'data:'")
+
+ header, actual_data = data[5:].split(",", 1)
+ if not header or not actual_data:
+ raise ValueError("Invalid URI")
+
+ # Split header into parts and check for base64
+ header_parts = header.split(";")
+ if "base64" not in header_parts:
+ raise ValueError("Data is not base64 encoded")
+
+ # Content type is the first part
+ content_type = header_parts[0]
+ if not content_type:
+ raise ValueError("Content type is empty")
+
+ return base64.b64decode(actual_data), cast(MediaContentType, content_type) | logic: base64.b64decode() errors not specifically caught and handled |
langfuse-python | github_2023 | python | 996 | langfuse | maxdeichmann | @@ -1,56 +1,45 @@
-"""@private"""
-
-import atexit
import json
import logging
-import queue
import threading
-from queue import Empty, Queue
import time
-from typing import List, Any, Optional
-import typing
-from langfuse.Sampler import Sampler
-from langfuse.parse_error import handle_exception
-from langfuse.request import APIError
-from langfuse.utils import _get_timestamp
-from langfuse.types import MaskFunction
+from queue import Empty, Queue
+from typing import Any, List, Optional
+
+import backoff
try:
- import pydantic.v1 as pydantic # type: ignore
+ import pydantic.v1 as pydantic
except ImportError:
- import pydantic # type: ignore
-
-
-import backoff
+ import pydantic
-from langfuse.request import LangfuseClient
+from langfuse.api.client import FernLangfuse
+from langfuse.parse_error import handle_exception
+from langfuse.request import APIError, LangfuseClient
+from langfuse.Sampler import Sampler
from langfuse.serializer import EventSerializer
+from langfuse.types import MaskFunction
-# largest message size in db is 331_000 bytes right now
-MAX_MSG_SIZE = 1_000_000
-
-# https://vercel.com/docs/functions/serverless-functions/runtimes#request-body-size
-# The maximum payload size for the request body or the response body of a Serverless Function is 4.5 MB
-# 4_500_000 Bytes = 4.5 MB
-# configured to be 3 MB to be safe
+from .media_manager import MediaManager
-BATCH_SIZE_LIMIT = 2_500_000
+MAX_EVENT_SIZE_BYTES = 1_000_000
+MAX_BATCH_SIZE_BYTES = 2_500_000
-class LangfuseMetadata(pydantic.BaseModel):
+class IngestionMetadata(pydantic.BaseModel):
batch_size: int
- sdk_integration: typing.Optional[str] = None
- sdk_name: str = None
- sdk_version: str = None
- public_key: str = None
+ sdk_integration: Optional[str] = None
+ sdk_name: Optional[str] = None
+ sdk_version: Optional[str] = None
+ public_key: Optional[str] = None | why are these optional? |
langfuse-python | github_2023 | python | 996 | langfuse | maxdeichmann | @@ -1,56 +1,45 @@
-"""@private"""
-
-import atexit
import json
import logging
-import queue
import threading
-from queue import Empty, Queue
import time
-from typing import List, Any, Optional
-import typing
-from langfuse.Sampler import Sampler
-from langfuse.parse_error import handle_exception
-from langfuse.request import APIError
-from langfuse.utils import _get_timestamp
-from langfuse.types import MaskFunction
+from queue import Empty, Queue
+from typing import Any, List, Optional
+
+import backoff
try:
- import pydantic.v1 as pydantic # type: ignore
+ import pydantic.v1 as pydantic
except ImportError:
- import pydantic # type: ignore
-
-
-import backoff
+ import pydantic
-from langfuse.request import LangfuseClient
+from langfuse.api.client import FernLangfuse
+from langfuse.parse_error import handle_exception
+from langfuse.request import APIError, LangfuseClient
+from langfuse.Sampler import Sampler
from langfuse.serializer import EventSerializer
+from langfuse.types import MaskFunction
-# largest message size in db is 331_000 bytes right now
-MAX_MSG_SIZE = 1_000_000
-
-# https://vercel.com/docs/functions/serverless-functions/runtimes#request-body-size
-# The maximum payload size for the request body or the response body of a Serverless Function is 4.5 MB
-# 4_500_000 Bytes = 4.5 MB
-# configured to be 3 MB to be safe
+from .media_manager import MediaManager
-BATCH_SIZE_LIMIT = 2_500_000
+MAX_EVENT_SIZE_BYTES = 1_000_000
+MAX_BATCH_SIZE_BYTES = 2_500_000
-class LangfuseMetadata(pydantic.BaseModel):
+class IngestionMetadata(pydantic.BaseModel):
batch_size: int
- sdk_integration: typing.Optional[str] = None
- sdk_name: str = None
- sdk_version: str = None
- public_key: str = None
+ sdk_integration: Optional[str] = None
+ sdk_name: Optional[str] = None
+ sdk_version: Optional[str] = None
+ public_key: Optional[str] = None
-class Consumer(threading.Thread):
+class IngestionConsumer(threading.Thread):
_log = logging.getLogger("langfuse")
- _queue: Queue
+ _ingestion_queue: Queue
_identifier: int
_client: LangfuseClient
+ _api_client: FernLangfuse | This one can be removed, right? |
langfuse-python | github_2023 | python | 996 | langfuse | maxdeichmann | @@ -0,0 +1,245 @@
+import logging
+from queue import Empty
+from typing import Any, Callable, Optional, TypeVar
+from typing_extensions import ParamSpec
+
+import time
+import requests
+import backoff
+
+from langfuse.api import GetMediaUploadUrlRequest, PatchMediaBody
+from langfuse.api.core import ApiError
+from langfuse.api.client import FernLangfuse
+from langfuse.media import LangfuseMedia
+from langfuse.utils import _get_timestamp
+
+from .media_upload_queue import MediaUploadQueue, UploadMediaJob
+
+
+T = TypeVar("T")
+P = ParamSpec("P")
+
+
+class MediaManager:
+ _log = logging.getLogger(__name__)
+
+ def __init__(
+ self,
+ *,
+ api_client: FernLangfuse,
+ media_upload_queue: MediaUploadQueue,
+ max_retries: Optional[int] = 3,
+ ):
+ self._api_client = api_client
+ self._queue = media_upload_queue
+ self._max_retries = max_retries
+
+ def process_next_media_upload(self):
+ try:
+ upload_job = self._queue.get(block=True, timeout=1)
+ self._log.debug(f"Processing upload for {upload_job['media_id']}")
+ self._process_upload_media_job(data=upload_job)
+
+ self._queue.task_done()
+ except Empty:
+ self._log.debug("Media upload queue is empty") | LOL. this will be super noisy if debug logs enabled :D |
langfuse-python | github_2023 | python | 996 | langfuse | maxdeichmann | @@ -0,0 +1,245 @@
+import logging
+from queue import Empty
+from typing import Any, Callable, Optional, TypeVar
+from typing_extensions import ParamSpec
+
+import time
+import requests
+import backoff
+
+from langfuse.api import GetMediaUploadUrlRequest, PatchMediaBody
+from langfuse.api.core import ApiError
+from langfuse.api.client import FernLangfuse
+from langfuse.media import LangfuseMedia
+from langfuse.utils import _get_timestamp
+
+from .media_upload_queue import MediaUploadQueue, UploadMediaJob
+
+
+T = TypeVar("T")
+P = ParamSpec("P")
+
+
+class MediaManager:
+ _log = logging.getLogger(__name__)
+
+ def __init__(
+ self,
+ *,
+ api_client: FernLangfuse,
+ media_upload_queue: MediaUploadQueue,
+ max_retries: Optional[int] = 3,
+ ):
+ self._api_client = api_client
+ self._queue = media_upload_queue
+ self._max_retries = max_retries
+
+ def process_next_media_upload(self):
+ try:
+ upload_job = self._queue.get(block=True, timeout=1)
+ self._log.debug(f"Processing upload for {upload_job['media_id']}")
+ self._process_upload_media_job(data=upload_job)
+
+ self._queue.task_done()
+ except Empty:
+ self._log.debug("Media upload queue is empty")
+ pass
+ except Exception as e:
+ self._log.error(f"Error uploading media: {e}")
+ self._queue.task_done()
+
+ def process_media_in_event(self, event: dict):
+ try:
+ if "body" not in event:
+ return
+
+ body = event["body"]
+ trace_id = body.get("traceId", None) or (
+ body.get("id", None)
+ if "type" in event and "trace" in event["type"]
+ else None
+ )
+
+ if trace_id is None:
+ raise ValueError("trace_id is required for media upload")
+
+ observation_id = (
+ body.get("id", None)
+ if "type" in event
+ and ("generation" in event["type"] or "span" in event["type"])
+ else None
+ )
+
+ multimodal_fields = ["input", "output", "metadata"]
+
+ for field in multimodal_fields:
+ if field in body:
+ processed_data = self._find_and_process_media(
+ data=body[field],
+ trace_id=trace_id,
+ observation_id=observation_id,
+ field=field,
+ )
+
+ body[field] = processed_data
+
+ except Exception as e:
+ self._log.error(f"Error processing multimodal event: {e}")
+
+ def _find_and_process_media(
+ self,
+ *,
+ data: Any,
+ trace_id: str,
+ observation_id: Optional[str],
+ field: str,
+ ):
+ seen = set()
+ max_levels = 10
+
+ def _process_data_recursively(data: Any, level: int):
+ if id(data) in seen or level > max_levels:
+ return data
+
+ seen.add(id(data))
+
+ if isinstance(data, LangfuseMedia):
+ self._process_media(
+ media=data,
+ trace_id=trace_id,
+ observation_id=observation_id,
+ field=field,
+ )
+
+ return data
+
+ if isinstance(data, str) and data.startswith("data:"):
+ media = LangfuseMedia(
+ obj=data,
+ base64_data_uri=data,
+ )
+
+ self._process_media(
+ media=media,
+ trace_id=trace_id,
+ observation_id=observation_id,
+ field=field,
+ )
+
+ return media
+
+ if isinstance(data, list):
+ return [_process_data_recursively(item, level + 1) for item in data]
+
+ if isinstance(data, dict):
+ return {
+ key: _process_data_recursively(value, level + 1)
+ for key, value in data.items()
+ }
+
+ return data
+
+ return _process_data_recursively(data, 1)
+
+ def _process_media(
+ self,
+ *,
+ media: LangfuseMedia,
+ trace_id: str,
+ observation_id: Optional[str],
+ field: str,
+ ):
+ if (
+ media._content_length is None
+ or media._content_type is None
+ or media._content_sha256_hash is None
+ or media._content_bytes is None
+ ):
+ return
+
+ upload_url_response = self._request_with_backoff(
+ self._api_client.media.get_upload_url, | for users with media upload and lots of traffic, this could become a performance bottleneck at some point. Just heads up, no action required now. |
langfuse-python | github_2023 | python | 996 | langfuse | maxdeichmann | @@ -0,0 +1,245 @@
+import logging
+from queue import Empty
+from typing import Any, Callable, Optional, TypeVar
+from typing_extensions import ParamSpec
+
+import time
+import requests
+import backoff
+
+from langfuse.api import GetMediaUploadUrlRequest, PatchMediaBody
+from langfuse.api.core import ApiError
+from langfuse.api.client import FernLangfuse
+from langfuse.media import LangfuseMedia
+from langfuse.utils import _get_timestamp
+
+from .media_upload_queue import MediaUploadQueue, UploadMediaJob
+
+
+T = TypeVar("T")
+P = ParamSpec("P")
+
+
+class MediaManager:
+ _log = logging.getLogger(__name__)
+
+ def __init__(
+ self,
+ *,
+ api_client: FernLangfuse,
+ media_upload_queue: MediaUploadQueue,
+ max_retries: Optional[int] = 3,
+ ):
+ self._api_client = api_client
+ self._queue = media_upload_queue
+ self._max_retries = max_retries
+
+ def process_next_media_upload(self):
+ try:
+ upload_job = self._queue.get(block=True, timeout=1)
+ self._log.debug(f"Processing upload for {upload_job['media_id']}")
+ self._process_upload_media_job(data=upload_job)
+
+ self._queue.task_done()
+ except Empty:
+ self._log.debug("Media upload queue is empty")
+ pass
+ except Exception as e:
+ self._log.error(f"Error uploading media: {e}")
+ self._queue.task_done()
+
+ def process_media_in_event(self, event: dict):
+ try:
+ if "body" not in event:
+ return
+
+ body = event["body"]
+ trace_id = body.get("traceId", None) or (
+ body.get("id", None)
+ if "type" in event and "trace" in event["type"]
+ else None
+ )
+
+ if trace_id is None:
+ raise ValueError("trace_id is required for media upload")
+
+ observation_id = (
+ body.get("id", None)
+ if "type" in event
+ and ("generation" in event["type"] or "span" in event["type"])
+ else None
+ )
+
+ multimodal_fields = ["input", "output", "metadata"]
+
+ for field in multimodal_fields:
+ if field in body:
+ processed_data = self._find_and_process_media(
+ data=body[field],
+ trace_id=trace_id,
+ observation_id=observation_id,
+ field=field,
+ )
+
+ body[field] = processed_data
+
+ except Exception as e:
+ self._log.error(f"Error processing multimodal event: {e}")
+
+ def _find_and_process_media(
+ self,
+ *,
+ data: Any,
+ trace_id: str,
+ observation_id: Optional[str],
+ field: str,
+ ):
+ seen = set()
+ max_levels = 10
+
+ def _process_data_recursively(data: Any, level: int):
+ if id(data) in seen or level > max_levels:
+ return data
+
+ seen.add(id(data))
+
+ if isinstance(data, LangfuseMedia): | In the openai integration, we specifically add langfusemedia for audio. This is handled here, correct? |
langfuse-python | github_2023 | python | 996 | langfuse | maxdeichmann | @@ -0,0 +1,245 @@
+import logging
+from queue import Empty
+from typing import Any, Callable, Optional, TypeVar
+from typing_extensions import ParamSpec
+
+import time
+import requests
+import backoff
+
+from langfuse.api import GetMediaUploadUrlRequest, PatchMediaBody
+from langfuse.api.core import ApiError
+from langfuse.api.client import FernLangfuse
+from langfuse.media import LangfuseMedia
+from langfuse.utils import _get_timestamp
+
+from .media_upload_queue import MediaUploadQueue, UploadMediaJob
+
+
+T = TypeVar("T")
+P = ParamSpec("P")
+
+
+class MediaManager:
+ _log = logging.getLogger(__name__)
+
+ def __init__(
+ self,
+ *,
+ api_client: FernLangfuse,
+ media_upload_queue: MediaUploadQueue,
+ max_retries: Optional[int] = 3,
+ ):
+ self._api_client = api_client
+ self._queue = media_upload_queue
+ self._max_retries = max_retries
+
+ def process_next_media_upload(self):
+ try:
+ upload_job = self._queue.get(block=True, timeout=1)
+ self._log.debug(f"Processing upload for {upload_job['media_id']}")
+ self._process_upload_media_job(data=upload_job)
+
+ self._queue.task_done()
+ except Empty:
+ self._log.debug("Media upload queue is empty")
+ pass
+ except Exception as e:
+ self._log.error(f"Error uploading media: {e}")
+ self._queue.task_done()
+
+ def process_media_in_event(self, event: dict):
+ try:
+ if "body" not in event:
+ return
+
+ body = event["body"]
+ trace_id = body.get("traceId", None) or (
+ body.get("id", None)
+ if "type" in event and "trace" in event["type"]
+ else None
+ )
+
+ if trace_id is None:
+ raise ValueError("trace_id is required for media upload")
+
+ observation_id = (
+ body.get("id", None)
+ if "type" in event
+ and ("generation" in event["type"] or "span" in event["type"])
+ else None
+ )
+
+ multimodal_fields = ["input", "output", "metadata"]
+
+ for field in multimodal_fields:
+ if field in body:
+ processed_data = self._find_and_process_media(
+ data=body[field],
+ trace_id=trace_id,
+ observation_id=observation_id,
+ field=field,
+ )
+
+ body[field] = processed_data
+
+ except Exception as e:
+ self._log.error(f"Error processing multimodal event: {e}")
+
+ def _find_and_process_media(
+ self,
+ *,
+ data: Any,
+ trace_id: str,
+ observation_id: Optional[str],
+ field: str,
+ ):
+ seen = set()
+ max_levels = 10
+
+ def _process_data_recursively(data: Any, level: int):
+ if id(data) in seen or level > max_levels:
+ return data
+
+ seen.add(id(data))
+
+ if isinstance(data, LangfuseMedia):
+ self._process_media(
+ media=data,
+ trace_id=trace_id,
+ observation_id=observation_id,
+ field=field,
+ )
+
+ return data
+
+ if isinstance(data, str) and data.startswith("data:"): | What is this for? All images in openai? |
langfuse-python | github_2023 | python | 996 | langfuse | maxdeichmann | @@ -0,0 +1,245 @@
+import logging
+from queue import Empty
+from typing import Any, Callable, Optional, TypeVar
+from typing_extensions import ParamSpec
+
+import time
+import requests
+import backoff
+
+from langfuse.api import GetMediaUploadUrlRequest, PatchMediaBody
+from langfuse.api.core import ApiError
+from langfuse.api.client import FernLangfuse
+from langfuse.media import LangfuseMedia
+from langfuse.utils import _get_timestamp
+
+from .media_upload_queue import MediaUploadQueue, UploadMediaJob
+
+
+T = TypeVar("T")
+P = ParamSpec("P")
+
+
+class MediaManager:
+ _log = logging.getLogger(__name__)
+
+ def __init__(
+ self,
+ *,
+ api_client: FernLangfuse,
+ media_upload_queue: MediaUploadQueue,
+ max_retries: Optional[int] = 3,
+ ):
+ self._api_client = api_client
+ self._queue = media_upload_queue
+ self._max_retries = max_retries
+
+ def process_next_media_upload(self):
+ try:
+ upload_job = self._queue.get(block=True, timeout=1)
+ self._log.debug(f"Processing upload for {upload_job['media_id']}")
+ self._process_upload_media_job(data=upload_job)
+
+ self._queue.task_done()
+ except Empty:
+ self._log.debug("Media upload queue is empty")
+ pass
+ except Exception as e:
+ self._log.error(f"Error uploading media: {e}")
+ self._queue.task_done()
+
+ def process_media_in_event(self, event: dict):
+ try:
+ if "body" not in event:
+ return
+
+ body = event["body"]
+ trace_id = body.get("traceId", None) or (
+ body.get("id", None)
+ if "type" in event and "trace" in event["type"]
+ else None
+ )
+
+ if trace_id is None:
+ raise ValueError("trace_id is required for media upload")
+
+ observation_id = (
+ body.get("id", None)
+ if "type" in event
+ and ("generation" in event["type"] or "span" in event["type"])
+ else None
+ )
+
+ multimodal_fields = ["input", "output", "metadata"]
+
+ for field in multimodal_fields:
+ if field in body:
+ processed_data = self._find_and_process_media(
+ data=body[field],
+ trace_id=trace_id,
+ observation_id=observation_id,
+ field=field,
+ )
+
+ body[field] = processed_data
+
+ except Exception as e:
+ self._log.error(f"Error processing multimodal event: {e}")
+
+ def _find_and_process_media(
+ self,
+ *,
+ data: Any,
+ trace_id: str,
+ observation_id: Optional[str],
+ field: str,
+ ):
+ seen = set()
+ max_levels = 10
+
+ def _process_data_recursively(data: Any, level: int):
+ if id(data) in seen or level > max_levels:
+ return data
+
+ seen.add(id(data))
+
+ if isinstance(data, LangfuseMedia):
+ self._process_media(
+ media=data,
+ trace_id=trace_id,
+ observation_id=observation_id,
+ field=field,
+ )
+
+ return data
+
+ if isinstance(data, str) and data.startswith("data:"):
+ media = LangfuseMedia(
+ obj=data,
+ base64_data_uri=data,
+ )
+
+ self._process_media(
+ media=media,
+ trace_id=trace_id,
+ observation_id=observation_id,
+ field=field,
+ )
+
+ return media
+
+ if isinstance(data, list):
+ return [_process_data_recursively(item, level + 1) for item in data]
+
+ if isinstance(data, dict):
+ return {
+ key: _process_data_recursively(value, level + 1)
+ for key, value in data.items()
+ }
+
+ return data | we only handle strings, dicts, lists here. Nothing else. I think this is expected, just bringing this up if you think we missed something. |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -97,73 +87,88 @@ def __init__(
self._sdk_integration = sdk_integration
self._mask = mask
self._sampler = Sampler(sample_rate)
+ self._media_manager = media_manager
def _next(self):
"""Return the next batch of items to upload."""
- queue = self._queue
- items = []
+ events = []
start_time = time.monotonic()
total_size = 0
- while len(items) < self._flush_at:
+ while len(events) < self._flush_at:
elapsed = time.monotonic() - start_time
if elapsed >= self._flush_interval:
break
try:
- item = queue.get(block=True, timeout=self._flush_interval - elapsed)
+ event = self._ingestion_queue.get(
+ block=True, timeout=self._flush_interval - elapsed
+ ) | logic: potential race condition if flush_interval - elapsed becomes negative |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -68,7 +64,6 @@ def test_default_langfuse_trace_callback():
assert callback.log.level == 30
assert callback.log.level == 30 | logic: duplicate assertion - line 65 is identical to line 64 |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -79,4 +74,3 @@ def test_debug_langfuse_trace_callback():
assert callback.log.level == 10
assert callback.log.level == 10 | logic: duplicate assertion - line 75 is identical to line 74 |
langfuse-python | github_2023 | python | 996 | langfuse | ellipsis-dev[bot] | @@ -58,7 +58,17 @@ def handler(request: Request):
)
tm = TaskManager(
- langfuse_client, 10, 0.1, 3, 1, 10_000, "test-sdk", "1.0.0", "default"
+ client=langfuse_client,
+ api_client=None,
+ public_key="pk", | Avoid using hardcoded public keys like 'pk'. Consider using environment variables or configuration files to manage sensitive information. This applies to all instances in this file. |
langfuse-python | github_2023 | python | 996 | langfuse | greptile-apps[bot] | @@ -0,0 +1,203 @@
+"""This module contains the LangfuseMedia class, which is used to wrap media objects for upload to Langfuse."""
+
+import base64
+import hashlib
+import logging
+import os
+from typing import Optional, cast, Tuple
+
+from langfuse.api import MediaContentType
+from langfuse.types import ParsedMediaReference
+
+
+class LangfuseMedia:
+ """A class for wrapping media objects for upload to Langfuse.
+
+ This class handles the preparation and formatting of media content for Langfuse,
+ supporting both base64 data URIs and raw content bytes.
+
+ Args:
+ obj (Optional[object]): The source object to be wrapped. Can be accessed via the `obj` attribute.
+ base64_data_uri (Optional[str]): A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type (Optional[str]): The MIME type of the media content when providing raw bytes.
+ content_bytes (Optional[bytes]): Raw bytes of the media content.
+ file_path (Optional[str]): The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+
+ Raises:
+ ValueError: If neither base64_data_uri or the combination of content_bytes
+ and content_type is provided.
+ """
+
+ obj: object
+
+ _log = logging.getLogger(__name__)
+ _content_bytes: Optional[bytes]
+ _content_type: Optional[MediaContentType]
+ _source: Optional[str]
+ _media_id: Optional[str]
+
+ def __init__(
+ self,
+ *,
+ obj: Optional[object] = None,
+ base64_data_uri: Optional[str] = None,
+ content_type: Optional[MediaContentType] = None,
+ content_bytes: Optional[bytes] = None,
+ file_path: Optional[str] = None,
+ ):
+ """Initialize a LangfuseMedia object.
+
+ Args:
+ obj: The object to wrap.
+
+ base64_data_uri: A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type: The MIME type of the media content when providing raw bytes or reading from a file.
+ content_bytes: Raw bytes of the media content.
+ file_path: The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+ """
+ self.obj = obj
+ self._media_id = None
+
+ if base64_data_uri is not None:
+ parsed_data = self._parse_base64_data_uri(base64_data_uri)
+ self._content_bytes, self._content_type = parsed_data
+ self._source = "base64_data_uri"
+
+ elif content_bytes is not None and content_type is not None:
+ self._content_type = content_type
+ self._content_bytes = content_bytes
+ self._source = "bytes"
+ elif (
+ file_path is not None
+ and content_type is not None
+ and os.path.exists(file_path)
+ ):
+ self._content_bytes = self._read_file(file_path)
+ self._content_type = content_type if self._content_bytes else None
+ self._source = "file" if self._content_bytes else None
+ else:
+ self._log.error(
+ "base64_data_uri, or content_bytes and content_type, or file_path must be provided to LangfuseMedia"
+ )
+
+ self._content_bytes = None
+ self._content_type = None
+ self._source = None
+
+ def _read_file(self, file_path: str) -> Optional[bytes]:
+ try:
+ with open(file_path, "rb") as file:
+ return file.read()
+ except Exception as e:
+ self._log.error(f"Error reading file at path {file_path}", exc_info=e)
+
+ return None
+
+ @property
+ def _content_length(self) -> Optional[int]:
+ return len(self._content_bytes) if self._content_bytes else None
+
+ @property
+ def _content_sha256_hash(self) -> Optional[str]:
+ if self._content_bytes is None:
+ return None
+
+ sha256_hash_bytes = hashlib.sha256(self._content_bytes).digest()
+
+ return base64.b64encode(sha256_hash_bytes).decode("utf-8")
+
+ @property
+ def _reference_string(self) -> Optional[str]:
+ if self._content_type is None or self._source is None or self._media_id is None:
+ return None
+
+ return f"@@@langfuseMedia:type={self._content_type}|id={self._media_id}|source={self._source}@@@"
+
+ @staticmethod
+ def parse_reference_string(reference_string: str) -> ParsedMediaReference:
+ """Parse a media reference string into a ParsedMediaReference.
+
+ Example reference string:
+ "@@@langfuseMedia:type=image/jpeg|id=some-uuid|source=base64_data_uri@@@"
+
+ Args:
+ reference_string: The reference string to parse.
+
+ Returns:
+ A TypedDict with the media_id, source, and content_type.
+
+ Raises:
+ ValueError: If the reference string is empty or not a string.
+ ValueError: If the reference string does not start with "@@@langfuseMedia:type=".
+ ValueError: If the reference string does not end with "@@@".
+ ValueError: If the reference string is missing required fields.
+ """
+ if not reference_string:
+ raise ValueError("Reference string is empty")
+
+ if not isinstance(reference_string, str):
+ raise ValueError("Reference string is not a string")
+
+ if not reference_string.startswith("@@@langfuseMedia:type="):
+ raise ValueError(
+ "Reference string does not start with '@@@langfuseMedia:type='"
+ )
+
+ if not reference_string.endswith("@@@"):
+ raise ValueError("Reference string does not end with '@@@'")
+
+ content = reference_string[len("@@@langfuseMedia:") :].rstrip("@@@")
+
+ # Split into key-value pairs
+ pairs = content.split("|")
+ parsed_data = {}
+
+ for pair in pairs:
+ key, value = pair.split("=", 1)
+ parsed_data[key] = value
+
+ # Verify all required fields are present
+ if not all(key in parsed_data for key in ["type", "id", "source"]):
+ raise ValueError("Missing required fields in reference string")
+
+ return ParsedMediaReference(
+ media_id=parsed_data["id"],
+ source=parsed_data["source"],
+ content_type=parsed_data["type"],
+ )
+
+ def _parse_base64_data_uri(
+ self, data: str
+ ) -> Tuple[Optional[bytes], Optional[MediaContentType]]:
+ # Example data URI: data:image/jpeg;base64,/9j/4AAQ...
+ try:
+ if not data or not isinstance(data, str):
+ raise ValueError("Data URI is not a string")
+
+ if not data.startswith("data:"):
+ raise ValueError("Data URI does not start with 'data:'")
+
+ header, actual_data = data[5:].split(",", 1) | logic: no validation of data length before split - could raise IndexError if comma is missing |
langfuse-python | github_2023 | python | 996 | langfuse | ellipsis-dev[bot] | @@ -0,0 +1,203 @@
+"""This module contains the LangfuseMedia class, which is used to wrap media objects for upload to Langfuse."""
+
+import base64
+import hashlib
+import logging
+import os
+from typing import Optional, cast, Tuple
+
+from langfuse.api import MediaContentType
+from langfuse.types import ParsedMediaReference
+
+
+class LangfuseMedia:
+ """A class for wrapping media objects for upload to Langfuse.
+
+ This class handles the preparation and formatting of media content for Langfuse,
+ supporting both base64 data URIs and raw content bytes.
+
+ Args:
+ obj (Optional[object]): The source object to be wrapped. Can be accessed via the `obj` attribute.
+ base64_data_uri (Optional[str]): A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type (Optional[str]): The MIME type of the media content when providing raw bytes.
+ content_bytes (Optional[bytes]): Raw bytes of the media content.
+ file_path (Optional[str]): The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+
+ Raises:
+ ValueError: If neither base64_data_uri or the combination of content_bytes
+ and content_type is provided.
+ """
+
+ obj: object
+
+ _log = logging.getLogger(__name__)
+ _content_bytes: Optional[bytes]
+ _content_type: Optional[MediaContentType]
+ _source: Optional[str]
+ _media_id: Optional[str]
+
+ def __init__(
+ self,
+ *,
+ obj: Optional[object] = None,
+ base64_data_uri: Optional[str] = None,
+ content_type: Optional[MediaContentType] = None,
+ content_bytes: Optional[bytes] = None,
+ file_path: Optional[str] = None,
+ ):
+ """Initialize a LangfuseMedia object.
+
+ Args:
+ obj: The object to wrap.
+
+ base64_data_uri: A base64-encoded data URI containing the media content
+ and content type (e.g., "data:image/jpeg;base64,/9j/4AAQ...").
+ content_type: The MIME type of the media content when providing raw bytes or reading from a file.
+ content_bytes: Raw bytes of the media content.
+ file_path: The path to the file containing the media content. For relative paths,
+ the current working directory is used.
+ """
+ self.obj = obj
+ self._media_id = None
+
+ if base64_data_uri is not None:
+ parsed_data = self._parse_base64_data_uri(base64_data_uri)
+ self._content_bytes, self._content_type = parsed_data
+ self._source = "base64_data_uri"
+
+ elif content_bytes is not None and content_type is not None:
+ self._content_type = content_type
+ self._content_bytes = content_bytes
+ self._source = "bytes"
+ elif (
+ file_path is not None
+ and content_type is not None
+ and os.path.exists(file_path)
+ ):
+ self._content_bytes = self._read_file(file_path)
+ self._content_type = content_type if self._content_bytes else None
+ self._source = "file" if self._content_bytes else None
+ else:
+ self._log.error(
+ "base64_data_uri, or content_bytes and content_type, or file_path must be provided to LangfuseMedia"
+ )
+
+ self._content_bytes = None
+ self._content_type = None
+ self._source = None
+
+ def _read_file(self, file_path: str) -> Optional[bytes]:
+ try:
+ with open(file_path, "rb") as file:
+ return file.read()
+ except Exception as e:
+ self._log.error(f"Error reading file at path {file_path}", exc_info=e)
+
+ return None
+
+ @property
+ def _content_length(self) -> Optional[int]:
+ return len(self._content_bytes) if self._content_bytes else None
+
+ @property
+ def _content_sha256_hash(self) -> Optional[str]:
+ if self._content_bytes is None:
+ return None
+
+ sha256_hash_bytes = hashlib.sha256(self._content_bytes).digest()
+
+ return base64.b64encode(sha256_hash_bytes).decode("utf-8")
+
+ @property
+ def _reference_string(self) -> Optional[str]:
+ if self._content_type is None or self._source is None or self._media_id is None:
+ return None
+
+ return f"@@@langfuseMedia:type={self._content_type}|id={self._media_id}|source={self._source}@@@"
+
+ @staticmethod
+ def parse_reference_string(reference_string: str) -> ParsedMediaReference:
+ """Parse a media reference string into a ParsedMediaReference.
+
+ Example reference string:
+ "@@@langfuseMedia:type=image/jpeg|id=some-uuid|source=base64_data_uri@@@"
+
+ Args:
+ reference_string: The reference string to parse.
+
+ Returns:
+ A TypedDict with the media_id, source, and content_type.
+
+ Raises:
+ ValueError: If the reference string is empty or not a string.
+ ValueError: If the reference string does not start with "@@@langfuseMedia:type=".
+ ValueError: If the reference string does not end with "@@@".
+ ValueError: If the reference string is missing required fields.
+ """
+ if not reference_string:
+ raise ValueError("Reference string is empty")
+
+ if not isinstance(reference_string, str):
+ raise ValueError("Reference string is not a string")
+
+ if not reference_string.startswith("@@@langfuseMedia:type="):
+ raise ValueError(
+ "Reference string does not start with '@@@langfuseMedia:type='"
+ )
+
+ if not reference_string.endswith("@@@"):
+ raise ValueError("Reference string does not end with '@@@'")
+
+ content = reference_string[len("@@@langfuseMedia:") :].rstrip("@@@") | The use of `rstrip("@@@")` is incorrect here. It will remove all trailing '@' characters, not just the specific suffix '@@@'. Consider using `removesuffix("@@@")` instead.
```suggestion
content = reference_string[len("@@@langfuseMedia:") :].removesuffix("@@@")
``` |
langfuse-python | github_2023 | python | 987 | langfuse | greptile-apps[bot] | @@ -519,7 +528,11 @@ def _get_langfuse_data_from_default_response(resource: OpenAiDefinition, respons
usage = response.get("usage", None)
- return model, completion, usage.__dict__ if _is_openai_v1() and usage is not None else usage
+ return (
+ model,
+ completion,
+ usage.__dict__ if _is_openai_v1() and usage is not None else usage,
+ ) | logic: consider adding a check for usage being a dict before accessing __dict__ to prevent potential AttributeError |
langfuse-python | github_2023 | python | 987 | langfuse | fancyweb | @@ -170,6 +170,17 @@ def get_langfuse_args(self):
return {**self.args, **self.kwargs}
def get_openai_args(self):
+ # OpenAI returns streaming usage not by default but only if stream_options has include_usage set
+ if self.kwargs.get("stream") and "stream_options" not in self.kwargs: | adding this automatically adds an empty final "choices" chunk and consumer code might not handle that, so that's a breaking change :grimacing: |
langfuse-python | github_2023 | python | 994 | langfuse | greptile-apps[bot] | @@ -2087,7 +2089,9 @@ def generation(
"body": new_body.dict(exclude_none=True, exclude_unset=False),
}
- self.log.debug(f"Creating generation {new_body}...")
+ self.log.debug(
+ f"Creating generation {_filter_io_from_event_body(generation_body)}..."
+ ) | logic: duplicate debug log statement that logs the same information twice |
langfuse-python | github_2023 | python | 994 | langfuse | greptile-apps[bot] | @@ -107,13 +113,33 @@ def _next(self):
try:
item = queue.get(block=True, timeout=self._flush_interval - elapsed)
+ # convert pydantic models to dicts
+ if "body" in item and isinstance(item["body"], pydantic.BaseModel):
+ item["body"] = item["body"].dict()
+
+ # sample event
+ if not self._sampler.sample_event(item):
+ continue | logic: Sampling should happen before Pydantic conversion to avoid unnecessary serialization of sampled-out events |
langfuse-python | github_2023 | python | 994 | langfuse | ellipsis-dev[bot] | @@ -107,13 +113,37 @@ def _next(self):
try:
item = queue.get(block=True, timeout=self._flush_interval - elapsed)
+ # convert pydantic models to dicts
+ if "body" in item and isinstance(item["body"], pydantic.BaseModel):
+ item["body"] = item["body"].dict()
+
+ # sample event
+ if not self._sampler.sample_event(item):
+ queue.task_done()
+
+ continue
+
+ # truncate item if it exceeds size limit
item_size = self._truncate_item_in_place(
item=item,
max_size=MAX_MSG_SIZE,
log_message="<truncated due to size exceeding limit>",
)
+ # apply mask
+ self._apply_mask_in_place(item)
+
+ # check for serialization errors
+ try:
+ json.dumps(item, cls=EventSerializer)
+ except Exception as e:
+ self._log.error(f"Error serializing item, skipping: {e}")
+ queue.task_done() | `queue.task_done()` is called twice for the same item in `_next()`. It should be called only once per item processing to avoid logical errors. Consider restructuring the code to ensure it's called once per item. |
langfuse-python | github_2023 | python | 994 | langfuse | maxdeichmann | @@ -991,14 +991,8 @@ def _log_debug_event(
parent_run_id: Optional[UUID] = None,
**kwargs,
):
- kwargs_log = (
- ", " + ", ".join([f"{key}: {value}" for key, value in kwargs.items()])
- if len(kwargs) > 0
- else ""
- )
self.log.debug(
f"Event: {event_name}, run_id: {str(run_id)[:5]}, parent_run_id: {str(parent_run_id)[:5]}"
- + kwargs_log | Why did you remove this? |
langfuse-python | github_2023 | python | 994 | langfuse | maxdeichmann | @@ -3350,3 +3360,7 @@ def __init__(self, dataset: Dataset, items: typing.List[DatasetItemClient]):
self.created_at = dataset.created_at
self.updated_at = dataset.updated_at
self.items = items
+
+
+def _filter_io_from_event_body(event_body: Dict[str, Any]):
+ return {k: v for k, v in event_body.items() if k not in ("input", "output")} | i would also remove metadata here. |
langfuse-python | github_2023 | python | 994 | langfuse | maxdeichmann | @@ -107,13 +113,37 @@ def _next(self):
try:
item = queue.get(block=True, timeout=self._flush_interval - elapsed)
+ # convert pydantic models to dicts
+ if "body" in item and isinstance(item["body"], pydantic.BaseModel):
+ item["body"] = item["body"].dict() | exclude_none=True is missing here i think. I think we should only send diffs to the backend. |
langfuse-python | github_2023 | python | 994 | langfuse | greptile-apps[bot] | @@ -107,13 +113,37 @@ def _next(self):
try:
item = queue.get(block=True, timeout=self._flush_interval - elapsed)
+ # convert pydantic models to dicts
+ if "body" in item and isinstance(item["body"], pydantic.BaseModel):
+ item["body"] = item["body"].dict(exclude_none=True)
+
+ # sample event
+ if not self._sampler.sample_event(item):
+ queue.task_done()
+
+ continue
+
+ # truncate item if it exceeds size limit
item_size = self._truncate_item_in_place(
item=item,
max_size=MAX_MSG_SIZE,
log_message="<truncated due to size exceeding limit>",
)
+ # apply mask
+ self._apply_mask_in_place(item)
+
+ # check for serialization errors
+ try:
+ json.dumps(item, cls=EventSerializer)
+ except Exception as e:
+ self._log.error(f"Error serializing item, skipping: {e}")
+ queue.task_done()
+
+ continue | logic: The serialization check should happen before truncation to avoid unnecessary truncation of items that will fail serialization anyway |
langfuse-python | github_2023 | python | 991 | langfuse | greptile-apps[bot] | @@ -138,7 +138,7 @@ def default(self, obj: Any):
except Exception as e:
print(obj.__dict__)
- logger.warning(
+ logger.debug(
f"Serialization failed for object of type {type(obj).__name__}",
exc_info=e,
) | logic: reducing log level to DEBUG means serialization failures will not be visible in production by default. Consider keeping WARNING level but adding a configuration option to suppress specific serialization errors if needed. |
langfuse-python | github_2023 | python | 988 | langfuse | greptile-apps[bot] | @@ -72,13 +72,17 @@ def default(self, obj: Any):
return obj.isoformat()
if isinstance(obj, BaseModel):
- obj.model_rebuild() # This method forces the OpenAI model to instantiate its serializer to avoid errors when serializing
+ obj.model_rebuild() if pydantic_utilities.IS_PYDANTIC_V2 else obj.update_forward_refs() # This method forces the OpenAI model to instantiate its serializer to avoid errors when serializing
# For LlamaIndex models, we need to rebuild the raw model as well if they include OpenAI models
if isinstance(raw := getattr(obj, "raw", None), BaseModel):
- raw.model_rebuild()
+ raw.model_rebuild() if pydantic_utilities.IS_PYDANTIC_V2 else raw.update_forward_refs() | logic: raw model rebuild could fail silently if raw exists but is not a BaseModel - consider adding error handling |
langfuse-python | github_2023 | python | 970 | langfuse | greptile-apps[bot] | @@ -71,14 +75,17 @@ def default(self, obj: Any):
if isinstance(obj, (date)):
return obj.isoformat()
- if isinstance(obj, BaseModel):
- obj.model_rebuild() # This method forces the OpenAI model to instantiate its serializer to avoid errors when serializing
+ if isinstance(obj, pydantic.BaseModel):
+ # This method forces the OpenAI model to instantiate its serializer to avoid errors when serializing
+ # Use update_forward_refs() instead of model_rebuild() as model_rebuild is not available in pydantic v1
+ obj.update_forward_refs()
# For LlamaIndex models, we need to rebuild the raw model as well if they include OpenAI models
if isinstance(raw := getattr(obj, "raw", None), BaseModel): | logic: BaseModel is undefined here - needs to be imported from pydantic or referenced as pydantic.BaseModel |
langfuse-python | github_2023 | others | 976 | langfuse | greptile-apps[bot] | @@ -35,7 +35,7 @@ lark = "^1.1.7"
pytest-asyncio = ">=0.21.1,<0.24.0"
pytest-httpserver = "^1.0.8"
boto3 = "^1.28.59"
-ruff = ">=0.1.8,<0.6.0"
+ruff = ">=0.1.8,<0.8.0" | logic: if using lint.allow-unused-imports in ruff config, must migrate to lint.pyflakes.allow-unused-imports |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.