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,154
langfuse
greptile-apps[bot]
@@ -176,6 +177,9 @@ def _truncate_item_in_place( "Item exceeds size limit (size: %s), dropping input / output / metadata of item until it fits.", item_size, ) + raise RuntimeError( + f"Item exceeds size limit (size: {item_size}), dropping input / output / metadata of item until it fits." + ) if "body" in event:
logic: All code after the RuntimeError is unreachable, including the truncation logic. This changes the behavior from truncating large items to simply rejecting them ```suggestion self._log.warning( "Item exceeds size limit (size: %s), dropping input / output / metadata of item until it fits.", item_size, ) if "body" in event: ```
langfuse-python
github_2023
python
1,152
langfuse
greptile-apps[bot]
@@ -0,0 +1,21 @@ +# This file was auto-generated by Fern from our API Definition. + +import enum +import typing + +T_Result = typing.TypeVar("T_Result") + + +class AnnotationQueueObjectType(str, enum.Enum): + TRACE = "TRACE" + OBSERVATION = "OBSERVATION" + + def visit( + self, + trace: typing.Callable[[], T_Result], + observation: typing.Callable[[], T_Result], + ) -> T_Result: + if self is AnnotationQueueObjectType.TRACE: + return trace() + if self is AnnotationQueueObjectType.OBSERVATION: + return observation()
logic: visit method lacks exhaustive pattern matching - no default/else case to handle potential future enum values ```suggestion def visit( self, trace: typing.Callable[[], T_Result], observation: typing.Callable[[], T_Result], ) -> T_Result: if self is AnnotationQueueObjectType.TRACE: return trace() if self is AnnotationQueueObjectType.OBSERVATION: return observation() raise ValueError(f"Unhandled enum value: {self}") ```
langfuse-python
github_2023
python
1,152
langfuse
greptile-apps[bot]
@@ -0,0 +1,51 @@ +# 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 .annotation_queue_object_type import AnnotationQueueObjectType +from .annotation_queue_status import AnnotationQueueStatus + + +class CreateAnnotationQueueItemRequest(pydantic_v1.BaseModel): + object_id: str = pydantic_v1.Field(alias="objectId") + object_type: AnnotationQueueObjectType = pydantic_v1.Field(alias="objectType") + status: typing.Optional[AnnotationQueueStatus] = pydantic_v1.Field(default=None) + """ + Defaults to PENDING for new queue items + """
logic: Docstring states status defaults to PENDING but field default is None. This could cause inconsistency in behavior.
langfuse-python
github_2023
python
1,141
langfuse
greptile-apps[bot]
@@ -313,6 +309,79 @@ def get_run( raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) + def delete_run( + self, + dataset_name: str, + run_name: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> DeleteDatasetRunResponse: + """ + Delete a dataset run and all its run items. This action is irreversible. + + Parameters + ---------- + dataset_name : str + + run_name : str + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + DeleteDatasetRunResponse + + Examples + -------- + from langfuse.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.datasets.delete_run( + dataset_name="datasetName", + run_name="runName", + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"api/public/datasets/{jsonable_encoder(dataset_name)}/runs/{jsonable_encoder(run_name)}",
logic: API endpoint path inconsistency - using 'api/public/datasets' here but 'api/public/v2/datasets' in other methods
langfuse-python
github_2023
python
1,141
langfuse
ellipsis-dev[bot]
@@ -350,7 +366,11 @@ def _get_langfuse_data_from_kwargs( if resource.type == "completion": prompt = kwargs.get("prompt", None) - elif resource.type == "chat": + + elif resource.object == "Responses": + prompt = kwargs.get("input", None) + + elif resource.type == "chat" or resource.object == "Responses":
The branch in `_get_langfuse_data_from_kwargs` handling `resource.object == 'Responses'` followed by `elif resource.type == "chat" or resource.object == "Responses"` seems redundant. Consider revisiting the condition ordering to clarify intent. ```suggestion elif resource.type == "chat": ```
langfuse-python
github_2023
python
1,141
langfuse
greptile-apps[bot]
@@ -350,6 +366,10 @@ def _get_langfuse_data_from_kwargs( if resource.type == "completion": prompt = kwargs.get("prompt", None) + + elif resource.object == "Responses": + prompt = kwargs.get("input", None) + elif resource.type == "chat": prompt = _extract_chat_prompt(kwargs)
logic: Potential logical error in condition - `resource.object == 'Responses'` is checked twice, once in the elif and once in the final condition
langfuse-python
github_2023
python
1,141
langfuse
greptile-apps[bot]
@@ -478,6 +507,33 @@ def _parse_usage(usage=None): return usage_dict +def _extract_streamed_response_api_response(chunks): + completion, model, usage = None, None, None + metadata = {} + + for raw_chunk in chunks: + chunk = raw_chunk.__dict__ + if raw_response := chunk.get("response", None): + usage = chunk.get("usage", None) + response = raw_response.__dict__ + model = response.get("model") + + for key, val in response.items(): + if key not in ["created_at", "model", "output", "usage", "text"]: + metadata[key] = val + + if key == "output": + output = val + + if len(output) > 1: + completion = output + + elif len(output) == 1: + completion = output[0]
logic: No validation of output array length before accessing. Could cause runtime error if output is empty ```suggestion if key == "output": output = val if not isinstance(output, list): completion = output elif len(output) > 1: completion = output elif len(output) == 1: completion = output[0] ```
langfuse-python
github_2023
python
1,141
langfuse
greptile-apps[bot]
@@ -597,12 +654,23 @@ def _get_langfuse_data_from_default_response(resource: OpenAiDefinition, respons model = response.get("model", None) or None completion = None + if resource.type == "completion": choices = response.get("choices", []) if len(choices) > 0: choice = choices[-1] completion = choice.text if _is_openai_v1() else choice.get("text", None) + + elif resource.object == "Responses": + output = response.get("output", {}) + + if len(output) > 1: + completion = output + + elif len(output) == 1: + completion = output[0]
logic: Similar to streaming response, missing validation of output array length before accessing. Should handle empty output case ```suggestion if not isinstance(output, list): completion = output elif len(output) > 1: completion = output elif len(output) == 1: completion = output[0] ```
langfuse-python
github_2023
python
1,141
langfuse
greptile-apps[bot]
@@ -1612,3 +1612,234 @@ def test_audio_input_and_output(): "@@@langfuseMedia:type=audio/wav|id=" in generation.data[0].output["audio"]["data"] ) + + +def test_response_api_text_input(): + client = openai.OpenAI() + generation_name = "test_response_api_text_input" + create_uuid()[:8] + + client.responses.create( + name=generation_name, + model="gpt-4o", + input="Tell me a three sentence bedtime story about a unicorn.", + ) + + openai.flush_langfuse() + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert ( + generation.data[0].input + == "Tell me a three sentence bedtime story about a unicorn." + ) + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + + +def test_response_api_image_input(): + client = openai.OpenAI() + generation_name = "test_response_api_image_input" + create_uuid()[:8] + + client.responses.create( + name=generation_name, + model="gpt-4o", + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": "what is in this image?"}, + { + "type": "input_image", + "image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", + }, + ], + } + ], + ) + + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generation.data[0].input[0]["content"][0]["text"] == "what is in this image?" + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + + +def test_response_api_web_search(): + client = openai.OpenAI() + generation_name = "test_response_api_web_search" + create_uuid()[:8] + + client.responses.create( + name=generation_name, + model="gpt-4o", + tools=[{"type": "web_search_preview"}], + input="What was a positive news story from today?", + ) + + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generationData.input == "What was a positive news story from today?" + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + assert generationData.metadata is not None + + +def test_response_api_streaming(): + client = openai.OpenAI() + generation_name = "test_response_api_streaming" + create_uuid()[:8] + + response = client.responses.create( + name=generation_name, + model="gpt-4o", + instructions="You are a helpful assistant.", + input="Hello!", + stream=True, + ) + + for _ in response: + continue + + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generation.data[0].input == "Hello!" + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + assert generationData.metadata is not None + assert generationData.metadata["instructions"] == "You are a helpful assistant." + + +def test_response_api_functions(): + client = openai.OpenAI() + generation_name = "test_response_api_functions" + create_uuid()[:8] + + tools = [ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location", "unit"], + }, + } + ] + + client.responses.create( + name=generation_name, + model="gpt-4o", + tools=tools, + input="What is the weather like in Boston today?", + tool_choice="auto", + ) + + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generation.data[0].input == "Hello!"
logic: Incorrect assertion - test is checking for 'Hello!' but the actual input was 'What is the weather like in Boston today?' ```suggestion assert generation.data[0].input == "What is the weather like in Boston today?" ```
langfuse-python
github_2023
python
1,141
langfuse
greptile-apps[bot]
@@ -1612,3 +1612,234 @@ def test_audio_input_and_output(): "@@@langfuseMedia:type=audio/wav|id=" in generation.data[0].output["audio"]["data"] ) + + +def test_response_api_text_input(): + client = openai.OpenAI() + generation_name = "test_response_api_text_input" + create_uuid()[:8] + + client.responses.create( + name=generation_name, + model="gpt-4o", + input="Tell me a three sentence bedtime story about a unicorn.", + ) + + openai.flush_langfuse() + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert ( + generation.data[0].input + == "Tell me a three sentence bedtime story about a unicorn." + ) + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + + +def test_response_api_image_input(): + client = openai.OpenAI() + generation_name = "test_response_api_image_input" + create_uuid()[:8] + + client.responses.create( + name=generation_name, + model="gpt-4o", + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": "what is in this image?"}, + { + "type": "input_image", + "image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", + }, + ], + } + ], + ) + + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generation.data[0].input[0]["content"][0]["text"] == "what is in this image?" + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + + +def test_response_api_web_search(): + client = openai.OpenAI() + generation_name = "test_response_api_web_search" + create_uuid()[:8] + + client.responses.create( + name=generation_name, + model="gpt-4o", + tools=[{"type": "web_search_preview"}], + input="What was a positive news story from today?", + ) + + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generationData.input == "What was a positive news story from today?" + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + assert generationData.metadata is not None + + +def test_response_api_streaming(): + client = openai.OpenAI() + generation_name = "test_response_api_streaming" + create_uuid()[:8] + + response = client.responses.create( + name=generation_name, + model="gpt-4o", + instructions="You are a helpful assistant.", + input="Hello!", + stream=True, + ) + + for _ in response: + continue + + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generation.data[0].input == "Hello!" + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + assert generationData.metadata is not None + assert generationData.metadata["instructions"] == "You are a helpful assistant." + + +def test_response_api_functions(): + client = openai.OpenAI() + generation_name = "test_response_api_functions" + create_uuid()[:8] + + tools = [ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location", "unit"], + }, + } + ] + + client.responses.create( + name=generation_name, + model="gpt-4o", + tools=tools, + input="What is the weather like in Boston today?", + tool_choice="auto", + ) + + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generation.data[0].input == "Hello!" + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + assert generationData.metadata is not None + + +def test_response_api_reasoning(): + client = openai.OpenAI() + generation_name = "test_response_api_reasoning" + create_uuid()[:8] + + client.responses.create( + name=generation_name, + model="o3-mini", + input="How much wood would a woodchuck chuck?", + reasoning={"effort": "high"}, + ) + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generation.data[0].input == "Hello!"
logic: Incorrect assertion - test is checking for 'Hello!' but the actual input was 'How much wood would a woodchuck chuck?' ```suggestion assert generation.data[0].input == "How much wood would a woodchuck chuck?" ```
langfuse-python
github_2023
python
1,141
langfuse
greptile-apps[bot]
@@ -1612,3 +1612,234 @@ def test_audio_input_and_output(): "@@@langfuseMedia:type=audio/wav|id=" in generation.data[0].output["audio"]["data"] ) + + +def test_response_api_text_input(): + client = openai.OpenAI() + generation_name = "test_response_api_text_input" + create_uuid()[:8] + + client.responses.create( + name=generation_name, + model="gpt-4o", + input="Tell me a three sentence bedtime story about a unicorn.", + ) + + openai.flush_langfuse() + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert ( + generation.data[0].input + == "Tell me a three sentence bedtime story about a unicorn." + ) + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + + +def test_response_api_image_input(): + client = openai.OpenAI() + generation_name = "test_response_api_image_input" + create_uuid()[:8] + + client.responses.create( + name=generation_name, + model="gpt-4o", + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": "what is in this image?"}, + { + "type": "input_image", + "image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", + }, + ], + } + ], + ) + + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generation.data[0].input[0]["content"][0]["text"] == "what is in this image?" + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + + +def test_response_api_web_search(): + client = openai.OpenAI() + generation_name = "test_response_api_web_search" + create_uuid()[:8] + + client.responses.create( + name=generation_name, + model="gpt-4o", + tools=[{"type": "web_search_preview"}], + input="What was a positive news story from today?", + ) + + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generationData.input == "What was a positive news story from today?" + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + assert generationData.metadata is not None + + +def test_response_api_streaming(): + client = openai.OpenAI() + generation_name = "test_response_api_streaming" + create_uuid()[:8] + + response = client.responses.create( + name=generation_name, + model="gpt-4o", + instructions="You are a helpful assistant.", + input="Hello!", + stream=True, + ) + + for _ in response: + continue + + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generation.data[0].input == "Hello!" + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + assert generationData.metadata is not None + assert generationData.metadata["instructions"] == "You are a helpful assistant." + + +def test_response_api_functions(): + client = openai.OpenAI() + generation_name = "test_response_api_functions" + create_uuid()[:8] + + tools = [ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location", "unit"], + }, + } + ] + + client.responses.create( + name=generation_name, + model="gpt-4o", + tools=tools, + input="What is the weather like in Boston today?", + tool_choice="auto", + ) + + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generation.data[0].input == "Hello!" + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model + assert generationData.start_time is not None + assert generationData.end_time is not None + assert generationData.start_time < generationData.end_time + assert generationData.usage.input is not None + assert generationData.usage.output is not None + assert generationData.usage.total is not None + assert generationData.output is not None + assert generationData.metadata is not None + + +def test_response_api_reasoning(): + client = openai.OpenAI() + generation_name = "test_response_api_reasoning" + create_uuid()[:8] + + client.responses.create( + name=generation_name, + model="o3-mini", + input="How much wood would a woodchuck chuck?", + reasoning={"effort": "high"}, + ) + openai.flush_langfuse() + + generation = get_api().observations.get_many( + name=generation_name, type="GENERATION" + ) + + assert len(generation.data) != 0 + generationData = generation.data[0] + assert generationData.name == generation_name + assert generation.data[0].input == "Hello!" + assert generationData.type == "GENERATION" + assert "gpt-4o" in generationData.model
logic: Incorrect model assertion - test is checking for 'gpt-4o' but the model specified was 'o3-mini' ```suggestion assert "o3-mini" in generationData.model ```
langfuse-python
github_2023
python
1,122
langfuse
greptile-apps[bot]
@@ -2135,6 +2164,16 @@ def __init__( self.state_type = state_type self.task_manager = task_manager + self.environment = environment or os.environ.get("LANGFUSE_TRACING_ENVIRONMENT") + + if self.environment and not bool( + re.match(ENVIRONMENT_PATTERN, self.environment) + ): + self.log.warning( + f'Invalid environment specified "{environment}" that does not match validation pattern ("{ENVIRONMENT_PATTERN}"). Setting will be ignored.' + ) + self.environment = None
logic: There's an inconsistency in error handling between the main `Langfuse` class and `StatefulClient`. The main class logs an error for invalid environments but still keeps the value, while `StatefulClient` logs a warning and sets the environment to None. These should be consistent.
langfuse-python
github_2023
python
1,122
langfuse
ellipsis-dev[bot]
@@ -287,6 +292,15 @@ def __init__( else os.environ.get("LANGFUSE_HOST", "https://cloud.langfuse.com") ) + self.environment = environment or os.environ.get("LANGFUSE_TRACING_ENVIRONMENT") + + if self.environment and not bool( + re.match(ENVIRONMENT_PATTERN, self.environment) + ): + self.log.error( + f'Invalid environment specified "{environment}" that does not match validation pattern ("{ENVIRONMENT_PATTERN}"). Events will be rejected by Langfuse servers.' + )
If an invalid environment is specified, consider resetting self.environment to None after logging the error to prevent subsequent events from carrying an invalid value. ```suggestion self.environment = None ```
langfuse-python
github_2023
python
1,122
langfuse
ellipsis-dev[bot]
@@ -1076,7 +1077,7 @@ def configure( httpx_client: Pass your own httpx client for more customizability of requests. enabled: Enables or disables the Langfuse client. Defaults to True. If disabled, no observability data will be sent to Langfuse. If data is requested while disabled, an error will be raised. mask (Callable): Function that masks sensitive information from input and output in log messages. - + environment (optional): The tracing environment. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'. Can bet set via `LANGFUSE_TRACING_ENVIRONMENT` environment variable.
Typographical error: In the environment parameter description, change 'Can bet set via `LANGFUSE_TRACING_ENVIRONMENT` environment variable.' to 'Can be set via `LANGFUSE_TRACING_ENVIRONMENT` environment variable.' ```suggestion environment (optional): The tracing environment. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'. Can be set via `LANGFUSE_TRACING_ENVIRONMENT` environment variable. ```
langfuse-python
github_2023
python
1,126
langfuse
greptile-apps[bot]
@@ -2135,6 +2172,15 @@ def __init__( self.state_type = state_type self.task_manager = task_manager + self.environment = environment or os.environ.get("LANGFUSE_TRACING_ENVIRONMENT") + + if self.environment and not bool( + re.match(ENVIRONMENT_PATTERN, self.environment) + ): + self.log.warning( + f'Invalid environment specified "{environment}" that does not match validation pattern ("{ENVIRONMENT_PATTERN}"). Setting will be ignored.' + )
logic: The warning message references `environment` directly, but should reference `self.environment` to show the actual value that failed validation. ```suggestion self.environment = environment or os.environ.get("LANGFUSE_TRACING_ENVIRONMENT") if self.environment and not bool( re.match(ENVIRONMENT_PATTERN, self.environment) ): self.log.warning( f'Invalid environment specified "{self.environment}" that does not match validation pattern ("{ENVIRONMENT_PATTERN}"). Setting will be ignored.' ) ```
langfuse-python
github_2023
python
1,126
langfuse
ellipsis-dev[bot]
@@ -63,6 +63,7 @@ class LlamaIndexInstrumentor: enabled (Optional[bool]): Enable/disable the instrumentor sample_rate (Optional[float]): Sample rate for logging (0.0 to 1.0) mask (langfuse.types.MaskFunction): Masking function for 'input' and 'output' fields in events. Function must take a single keyword argument `data` and return a serializable, masked version of the data. + environment (optional): The tracing environment. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'. Can bet set via `LANGFUSE_TRACING_ENVIRONMENT` environment variable.
Typo in the documentation for the 'environment' argument: 'Can bet set via ...' should be corrected to 'Can be set via ...'. ```suggestion environment (optional): The tracing environment. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'. Can be set via `LANGFUSE_TRACING_ENVIRONMENT` environment variable. ```
langfuse-python
github_2023
python
1,115
langfuse
hassiebp
@@ -172,7 +172,7 @@ def get_openai_args(self): # If OpenAI model distillation is enabled, we need to add the metadata to the kwargs # https://platform.openai.com/docs/guides/distillation if self.kwargs.get("store", False): - self.kwargs["metadata"] = self.args.get("metadata", {}) + self.kwargs["metadata"] = {} if self.args.get("metadata") is None else self.args["metadata"]
```suggestion self.kwargs["metadata"] = {} if self.args.get("metadata", None) is None else self.args["metadata"] ```
langfuse-python
github_2023
python
1,121
langfuse
greptile-apps[bot]
@@ -1096,12 +1096,18 @@ def _parse_usage_model(usage: typing.Union[pydantic.BaseModel, dict]): for key, value in input_token_details.items(): usage_model[f"input_{key}"] = value + if "input" in usage_model: + usage_model["input"] -= value
logic: This subtraction could result in negative values if input_token_details sum exceeds the total input tokens. Consider adding a check to prevent negative values. ```suggestion if "input" in usage_model: usage_model["input"] = max(0, usage_model["input"] - value) ```
langfuse-python
github_2023
python
1,121
langfuse
greptile-apps[bot]
@@ -1096,12 +1096,18 @@ def _parse_usage_model(usage: typing.Union[pydantic.BaseModel, dict]): for key, value in input_token_details.items(): usage_model[f"input_{key}"] = value + if "input" in usage_model: + usage_model["input"] -= value + if "output_token_details" in usage_model: output_token_details = usage_model.pop("output_token_details", {}) for key, value in output_token_details.items(): usage_model[f"output_{key}"] = value + if "output" in usage_model: + usage_model["output"] -= value
logic: This subtraction could result in negative values if output_token_details sum exceeds the total output tokens. Consider adding a check to prevent negative values. ```suggestion if "output" in usage_model: usage_model["output"] = max(0, usage_model["output"] - value) ```
langfuse-python
github_2023
python
1,121
langfuse
greptile-apps[bot]
@@ -2318,3 +2318,49 @@ def call_model(state: MessagesState): assert observation.level == "DEFAULT" assert hidden_count > 0 + + +def test_cached_token_usage(): + prompt = ChatPromptTemplate.from_messages( + [ + ( + "system", + ( + "This is a test prompt to reproduce the issue. " + "The prompt needs 1024 tokens to enable cache." * 100 + ), + ), + ("user", "Reply to this message {test_param}."), + ] + ) + chat = ChatOpenAI(model="gpt-4o-mini") + chain = prompt | chat + handler = CallbackHandler() + config = {"callbacks": [handler]} if handler else {} + + chain.invoke({"test_param": "in a funny way"}, config) + + # invoke again to force cached token usage + chain.invoke({"test_param": "in a funny way"}, config) + + handler.flush() + + trace = get_api().trace.get(handler.get_trace_id()) + + generation = next((o for o in trace.observations if o.type == "GENERATION"))
logic: check that generation exists before accessing properties - next() could raise StopIteration
langfuse-python
github_2023
python
1,121
langfuse
ellipsis-dev[bot]
@@ -2318,3 +2318,49 @@ def call_model(state: MessagesState): assert observation.level == "DEFAULT" assert hidden_count > 0 + + +def test_cached_token_usage(): + prompt = ChatPromptTemplate.from_messages( + [ + ( + "system", + ( + "This is a test prompt to reproduce the issue. " + "The prompt needs 1024 tokens to enable cache." * 100 + ), + ), + ("user", "Reply to this message {test_param}."), + ] + ) + chat = ChatOpenAI(model="gpt-4o-mini") + chain = prompt | chat + handler = CallbackHandler() + config = {"callbacks": [handler]} if handler else {}
The conditional 'if handler else {}' is unnecessary since handler is always defined; consider simplifying the config assignment. ```suggestion config = {"callbacks": [handler]} ```
langfuse-python
github_2023
python
1,107
langfuse
ellipsis-dev[bot]
@@ -54,6 +55,9 @@ def default(self, obj: Any): if np is not None and isinstance(obj, np.generic): return obj.item() + if isinstance(obj, float) and math.isnan(obj):
Consider also handling Infinity (math.isinf) alongside NaN if consistent nulling of non-finite floats is desired. ```suggestion if isinstance(obj, float) and (math.isnan(obj) or math.isinf(obj)): ```
langfuse-python
github_2023
python
1,103
langfuse
greptile-apps[bot]
@@ -21,8 +21,8 @@ from .media_manager import MediaManager -MAX_EVENT_SIZE_BYTES = 1_000_000 -MAX_BATCH_SIZE_BYTES = 2_500_000 +MAX_EVENT_SIZE_BYTES = int(os.environ.get("LANGFUSE_MAX_EVENT_SIZE_BYTES", 1_000_000)) +MAX_BATCH_SIZE_BYTES = int(os.environ.get("LANGFUSE_MAX_BATCH_SIZE_BYTES", 2_500_000))
logic: No error handling for invalid integer values in environment variables. Could crash on startup if LANGFUSE_MAX_EVENT_SIZE_BYTES or LANGFUSE_MAX_BATCH_SIZE_BYTES contain non-integer values. ```suggestion def safe_int_env(key: str, default: int) -> int: try: return int(os.environ.get(key, default)) except ValueError: logging.warning(f"Invalid integer value for {key}, using default {default}") return default MAX_EVENT_SIZE_BYTES = safe_int_env("LANGFUSE_MAX_EVENT_SIZE_BYTES", 1_000_000) MAX_BATCH_SIZE_BYTES = safe_int_env("LANGFUSE_MAX_BATCH_SIZE_BYTES", 2_500_000) ```
langfuse-python
github_2023
python
1,102
langfuse
greptile-apps[bot]
@@ -299,9 +299,19 @@ def __init__( httpx_client=self.httpx_client, timeout=timeout, ) + async_public_api_client = AsyncFernLangfuse( + base_url=self.base_url, + username=public_key, + password=secret_key, + x_langfuse_sdk_name="python", + x_langfuse_sdk_version=version, + x_langfuse_public_key=public_key, + timeout=timeout, + )
logic: The async client is instantiated without an httpx_client, while the sync client uses the shared httpx_client. This could lead to connection pooling issues since the async client will create its own connection pool.
langfuse-python
github_2023
python
901
langfuse
greptile-apps[bot]
@@ -1,52 +1,39 @@ # 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 pydantic_v1 +from ....core.pydantic_utilities import UniversalBaseModel from .dataset_status import DatasetStatus +import typing +import pydantic +import datetime as dt +from ....core.pydantic_utilities import IS_PYDANTIC_V2 -class DatasetItem(pydantic_v1.BaseModel): +class DatasetItem(UniversalBaseModel): id: str status: DatasetStatus - input: typing.Optional[typing.Any] = None - expected_output: typing.Optional[typing.Any] = pydantic_v1.Field( + input: typing.Optional[typing.Optional[typing.Any]] = None + expected_output: typing.Optional[typing.Optional[typing.Any]] = pydantic.Field( alias="expectedOutput", default=None ) - metadata: typing.Optional[typing.Any] = None - source_trace_id: typing.Optional[str] = pydantic_v1.Field( + metadata: typing.Optional[typing.Optional[typing.Any]] = None
logic: Double Optional wrapping for 'input', 'expected_output', and 'metadata' fields. This might be unintentional and could lead to unexpected behavior.
langfuse-python
github_2023
python
901
langfuse
greptile-apps[bot]
@@ -1,21 +1,5 @@ # This file was auto-generated by Fern from our API Definition. -import enum import typing -T_Result = typing.TypeVar("T_Result") - - -class DatasetStatus(str, enum.Enum): - ACTIVE = "ACTIVE" - ARCHIVED = "ARCHIVED" - - def visit( - self, - active: typing.Callable[[], T_Result], - archived: typing.Callable[[], T_Result], - ) -> T_Result: - if self is DatasetStatus.ACTIVE: - return active() - if self is DatasetStatus.ARCHIVED: - return archived() +DatasetStatus = typing.Union[typing.Literal["ACTIVE", "ARCHIVED"], typing.Any]
logic: Removal of visit method may break existing code that relies on it.
langfuse-python
github_2023
python
1,100
langfuse
greptile-apps[bot]
@@ -283,8 +283,15 @@ def execute_task_with_backoff() -> T: and (e.status_code) != 429 ): raise e - except Exception as e: - raise e + except requests.exceptions.RequestException as e: + if ( + e.response + and hasattr(e.response, "status_code") + and (e.response.status_code >= 500 or e.response.status_code == 429) + ): + raise
logic: this condition should check for e.response being None first to avoid potential AttributeError ```suggestion if ( e.response is not None and hasattr(e.response, "status_code") and (e.response.status_code >= 500 or e.response.status_code == 429) ): raise ```
langfuse-python
github_2023
python
1,100
langfuse
ellipsis-dev[bot]
@@ -283,8 +283,15 @@ def execute_task_with_backoff() -> T: and (e.status_code) != 429 ): raise e - except Exception as e: - raise e + except requests.exceptions.RequestException as e:
Use a giveup callback with backoff.on_exception to skip retries for non-transient errors. Currently, re‑raising e in the RequestException block (for non‑500/429 responses) still triggers retries.
langfuse-python
github_2023
python
1,100
langfuse
ellipsis-dev[bot]
@@ -270,22 +270,29 @@ def _process_upload_media_job( 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 ( + def _should_give_up(e: Exception) -> bool:
Consider adding a short docstring for _should_give_up explaining the retry conditions.
langfuse-python
github_2023
python
827
langfuse
marcklingen
@@ -451,6 +451,162 @@ def delete( raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) + def list(
where is this coming from? is this auto-generated?
langfuse-python
github_2023
python
827
langfuse
marcklingen
@@ -1465,3 +1467,69 @@ def test_fetch_sessions(): response = langfuse.fetch_sessions(limit=1, page=2) assert len(response.data) == 1 assert response.data[0].id in [session1, session2, session3] + + +def test_fetch_scores(): + langfuse = Langfuse() + + # Create a trace with a score + name = create_uuid() + trace = langfuse + trace = langfuse.trace(name=name) + trace.score(name="harmfulness", value=0.5) + trace.score(name="quality", value=1) + trace.score(name="relevance", value=0.8) + langfuse.flush() + + # Fetch scores + response = langfuse.fetch_scores() + + # Assert the structure of the response + assert isinstance(response, FetchScoresResponse) + assert hasattr(response, "data") + assert hasattr(response, "meta") + assert isinstance(response.data, list) + assert response.data[2].name == "harmfulness" + assert response.data[2].value == 0.5 + assert response.data[1].name == "quality" + assert response.data[1].value == 1 + assert response.data[0].name == "relevance" + assert response.data[0].value == 0.8 + + # fetch only one + response = langfuse.fetch_scores(limit=1, page=2) + assert len(response.data) == 1 + + +def test_fetch_prompts():
please add multiple versions and labels to make sure it works with multiple prompt versions as well
langfuse-python
github_2023
python
827
langfuse
marcklingen
@@ -1465,3 +1467,69 @@ def test_fetch_sessions(): response = langfuse.fetch_sessions(limit=1, page=2) assert len(response.data) == 1 assert response.data[0].id in [session1, session2, session3] + + +def test_fetch_scores(): + langfuse = Langfuse() + + # Create a trace with a score + name = create_uuid() + trace = langfuse + trace = langfuse.trace(name=name) + trace.score(name="harmfulness", value=0.5) + trace.score(name="quality", value=1) + trace.score(name="relevance", value=0.8) + langfuse.flush() + + # Fetch scores + response = langfuse.fetch_scores() + + # Assert the structure of the response + assert isinstance(response, FetchScoresResponse) + assert hasattr(response, "data") + assert hasattr(response, "meta") + assert isinstance(response.data, list) + assert response.data[2].name == "harmfulness" + assert response.data[2].value == 0.5 + assert response.data[1].name == "quality" + assert response.data[1].value == 1 + assert response.data[0].name == "relevance" + assert response.data[0].value == 0.8 + + # fetch only one + response = langfuse.fetch_scores(limit=1, page=2) + assert len(response.data) == 1 + + +def test_fetch_prompts(): + langfuse = Langfuse() + + # Create a prompt + langfuse.create_prompt( + name="event-planner", + prompt="Plan an event titled {{Event Name}}. The event will be about: {{Event Description}}. " + "The event will be held in {{Location}} on {{Date}}. " + "Consider the following factors: audience, budget, venue, catering options, and entertainment. " + "Provide a detailed plan including potential vendors and logistics.", + config={ + "model": "gpt-3.5-turbo-1106", + "temperature": 0, + }, + labels=["production"], + ) + langfuse.flush() + + # Fetch prompts + response = langfuse.fetch_prompts() + + # Assert the structure of the response + assert isinstance(response, FetchPromptsResponse) + assert hasattr(response, "data") + assert hasattr(response, "meta") + assert isinstance(response.data, list) + assert response.data[0].name == "event-planner" + assert ( + response.data[0].prompt
why do we have the prompt here included? the api does not include the prompt in the response: https://api.reference.langfuse.com/#get-/api/public/v2/prompts
langfuse-python
github_2023
python
827
langfuse
greptile-apps[bot]
@@ -1465,3 +1468,186 @@ def test_fetch_sessions(): response = langfuse.fetch_sessions(limit=1, page=2) assert len(response.data) == 1 assert response.data[0].id in [session1, session2, session3] + + +def test_fetch_scores(): + langfuse = Langfuse() + + # Create a trace with a score + name = create_uuid() + trace = langfuse + trace = langfuse.trace(name=name) + trace.score(name="harmfulness", value=0.5) + trace.score(name="quality", value=1) + trace.score(name="relevance", value=0.8) + langfuse.flush() + + # Fetch scores + response = langfuse.fetch_scores() + + # Assert the structure of the response + assert isinstance(response, FetchScoresResponse) + assert hasattr(response, "data") + assert hasattr(response, "meta") + assert isinstance(response.data, list) + assert response.data[2].name == "harmfulness" + assert response.data[2].value == 0.5 + assert response.data[1].name == "quality" + assert response.data[1].value == 1 + assert response.data[0].name == "relevance" + assert response.data[0].value == 0.8 + + # fetch only one + response = langfuse.fetch_scores(limit=1, page=2) + assert len(response.data) == 1 + +def test_fetch_score_by_id(): + langfuse = Langfuse( public_key="pk-lf-1234567890",
logic: Sensitive information like public and secret keys should not be hardcoded. Consider using environment variables.
langfuse-python
github_2023
python
1,082
langfuse
greptile-apps[bot]
@@ -0,0 +1,28 @@ +from langfuse.client import Langfuse +from tests.utils import create_uuid + + +def test_update_prompt(): + langfuse = Langfuse()
logic: Langfuse() instantiated without configuration parameters - should include test configuration
langfuse-python
github_2023
python
1,082
langfuse
hassiebp
@@ -1357,6 +1357,31 @@ def create_prompt( handle_fern_exception(e) raise e + def update_prompt( + self, + prompt_name: str,
We should pass all args as keyword args to have an extendable interface
langfuse-python
github_2023
python
1,082
langfuse
greptile-apps[bot]
@@ -0,0 +1,197 @@ +# 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 ..prompts.types.prompt import Prompt + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class PromptVersionClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def update( + self, + prompt_name: str, + version: int, + *, + new_labels: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, + ) -> Prompt: + """ + Update labels for a specific prompt version + + Parameters + ---------- + prompt_name : str + The name of the prompt + + version : int + Version of the prompt to update + + new_labels : typing.Sequence[str] + New labels for the prompt version. Labels are unique across versions. The "latest" label is reserved and managed by Langfuse. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + Prompt + + Examples + -------- + from langfuse.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.prompt_version.update( + prompt_name="string", + version=1, + new_labels=["string"], + ) + """ + _response = self._client_wrapper.httpx_client.request( + f"api/public/v2/prompts/{jsonable_encoder(prompt_name)}/version/{jsonable_encoder(version)}",
logic: API endpoint path should start with a leading slash to ensure proper URL construction
langfuse-python
github_2023
python
1,082
langfuse
greptile-apps[bot]
@@ -0,0 +1,35 @@ +from langfuse.client import Langfuse +from tests.utils import create_uuid + + +def test_update_prompt(): + langfuse = Langfuse() + prompt_name = create_uuid() + + # Create initial prompt + langfuse.create_prompt( + name=prompt_name, + prompt="test prompt", + labels=["production"], + ) + + # Update prompt labels + updated_prompt = langfuse.update_prompt( + name=prompt_name, + version=1, + new_labels=["john", "doe"], + ) + + # Fetch prompt after update (should be invalidated) + fetched_prompt = langfuse.get_prompt(prompt_name) + + # Verify the fetched prompt matches the updated values + assert fetched_prompt.name == prompt_name + assert fetched_prompt.version == 1 + print(f"Fetched prompt labels: {fetched_prompt.labels}") + print(f"Updated prompt labels: {updated_prompt.labels}") + + # production was set by the first call, latest is managed and set by Langfuse + expected_labels = sorted(["latest", "doe", "production", "john"]) + assert sorted(fetched_prompt.labels) == expected_labels + assert sorted(updated_prompt.labels) == expected_labels
logic: Test assumes 'production' label persists after update - verify this is intended behavior
langfuse-python
github_2023
others
1,077
langfuse
greptile-apps[bot]
@@ -54,6 +54,7 @@ langchain-cohere = "^0.3.3" langchain-huggingface = "^0.1.2" langchain-community = ">=0.2.14,<0.4" +langgraph = "^0.2.62"
logic: langgraph appears to be misplaced - should be properly indented under [tool.poetry.group.dev.dependencies] if intended as dev dependency
langfuse-python
github_2023
python
1,077
langfuse
greptile-apps[bot]
@@ -2223,3 +2227,92 @@ def test_multimodal(): "@@@langfuseMedia:type=image/jpeg|id=" in trace.observations[0].input[0]["content"][1]["image_url"]["url"] ) + + +def test_langgraph(): + # Define the tools for the agent to use + @tool + def search(query: str): + """Call to surf the web.""" + # This is a placeholder, but don't tell the LLM that... + if "sf" in query.lower() or "san francisco" in query.lower(): + return "It's 60 degrees and foggy." + return "It's 90 degrees and sunny." + + tools = [search] + tool_node = ToolNode(tools) + model = ChatOpenAI(model="gpt-4o-mini").bind_tools(tools)
logic: model='gpt-4o-mini' appears to be a typo - this is not a valid OpenAI model name
langfuse-python
github_2023
python
1,077
langfuse
ellipsis-dev[bot]
@@ -260,6 +262,7 @@ def on_chain_start( "metadata": self.__join_tags_and_metadata(tags, metadata), "input": inputs, "version": self.version, + "level": "DEBUG" if LANGSMITH_TAG_HIDDEN in tags else None,
Consider checking if `tags` is not `None` before checking for `LANGSMITH_TAG_HIDDEN` to avoid potential `TypeError`. This applies to similar checks on lines 587 and 626.
langfuse-python
github_2023
python
1,077
langfuse
greptile-apps[bot]
@@ -619,6 +623,7 @@ def on_retriever_start( "metadata": self.__join_tags_and_metadata(tags, metadata), "input": query, "version": self.version, + "level": "DEBUG" if tags and LANGSMITH_TAG_HIDDEN in tags else None,
logic: Inconsistent level setting between parent and child spans. The level is not set for child spans in the else block starting at line 633.
langfuse-python
github_2023
python
1,063
langfuse
greptile-apps[bot]
@@ -19,16 +22,44 @@ from langfuse.api.client import FernLangfuse +logger = logging.getLogger(__name__) + def create_uuid(): return str(uuid4()) +class HTTPClientWithRetries(httpx.Client): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + @backoff.on_exception( + backoff.expo, + httpx.HTTPError, + max_time=3, + max_tries=4,
logic: max_time=3 with max_tries=4 could lead to some retries being skipped if exponential backoff exceeds the max time. Consider increasing max_time or reducing max_tries.
langfuse-python
github_2023
python
1,063
langfuse
greptile-apps[bot]
@@ -19,16 +22,44 @@ from langfuse.api.client import FernLangfuse +logger = logging.getLogger(__name__) + def create_uuid(): return str(uuid4()) +class HTTPClientWithRetries(httpx.Client): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + @backoff.on_exception( + backoff.expo, + httpx.HTTPError, + max_time=3, + max_tries=4, + giveup=lambda e: isinstance(e, httpx.HTTPStatusError) + and e.response.status_code >= 500, + on_backoff=lambda details: logger.warning(
logic: giveup condition will retry on non-500 errors but give up on 500+ errors, which is typically the opposite of what you want (500s are usually retryable, 4xx are not)
langfuse-python
github_2023
python
1,063
langfuse
greptile-apps[bot]
@@ -11,23 +12,27 @@ def __init__(self, username=None, password=None, base_url=None): self.BASE_URL = base_url if base_url else os.environ["LANGFUSE_HOST"] def get_observation(self, observation_id): + sleep(1) url = f"{self.BASE_URL}/api/public/observations/{observation_id}" response = httpx.get(url, auth=self.auth) return response.json()
logic: no error handling for failed requests - should catch httpx.HTTPError and handle appropriately
langfuse-python
github_2023
python
1,063
langfuse
greptile-apps[bot]
@@ -11,23 +12,27 @@ def __init__(self, username=None, password=None, base_url=None): self.BASE_URL = base_url if base_url else os.environ["LANGFUSE_HOST"] def get_observation(self, observation_id): + sleep(1) url = f"{self.BASE_URL}/api/public/observations/{observation_id}" response = httpx.get(url, auth=self.auth)
logic: missing timeout parameter on request - could hang indefinitely
langfuse-python
github_2023
python
1,063
langfuse
greptile-apps[bot]
@@ -45,7 +46,7 @@ async def update_generation(i, langfuse: Langfuse): for i in range(100): observation = api.observations.get_many(name=str(i)).data[0] assert observation.name == str(i) - assert observation.metadata == {"count": str(i)} + assert observation.metadata == {"count": i}
logic: metadata value is now an integer instead of string, which could break existing code expecting string values
langfuse-python
github_2023
python
1,063
langfuse
greptile-apps[bot]
@@ -208,7 +209,7 @@ def test_create_categorical_score(): assert trace["scores"][0]["id"] == score_id assert trace["scores"][0]["dataType"] == "CATEGORICAL" - assert trace["scores"][0]["value"] is None + assert trace["scores"][0]["value"] == 0 assert trace["scores"][0]["stringValue"] == "high score"
logic: categorical score value changed from None to 0, which could affect code that checks for null values
langfuse-python
github_2023
others
1,063
langfuse
greptile-apps[bot]
@@ -149,7 +155,7 @@ jobs: - name: Run the automated tests run: | python --version - poetry run pytest -s -v --log-cli-level=INFO + poetry run pytest -n auto -s -v --log-cli-level=INFO
logic: Running tests in parallel (-n auto) may cause issues with shared resources like the database. Consider adding test markers to prevent parallel execution of database-dependent tests.
langfuse-python
github_2023
python
1,063
langfuse
greptile-apps[bot]
@@ -1331,7 +1296,7 @@ def test_fetch_traces(): fetched_trace = response.data[0] assert fetched_trace.name == name assert fetched_trace.session_id == "session-1" - assert fetched_trace.input == {"key": "value"} + assert fetched_trace.input == '{"key":"value"}'
logic: input is now serialized as a JSON string in the API response, which could break code expecting a dictionary
langfuse-python
github_2023
python
1,063
langfuse
greptile-apps[bot]
@@ -1035,7 +1036,8 @@ async def level_1_function(*args, **kwargs): assert generation.usage.input is not None assert generation.usage.output is not None assert generation.usage.total is not None - assert "2" in generation.output + print(generation) + assert generation.output == 2
logic: Generation output assertion should handle both string and integer responses since OpenAI may return either format. Consider using a more flexible assertion.
langfuse-python
github_2023
python
1,073
langfuse
greptile-apps[bot]
@@ -31,7 +31,7 @@ class Model(pydantic_v1.BaseModel): Apply only to generations which are newer than this ISO date. """ - unit: ModelUsageUnit = pydantic_v1.Field() + unit: typing.Optional[ModelUsageUnit] = pydantic_v1.Field(default=None) """ Unit used by this model. """
logic: Making unit optional could cause issues if any code relies on unit being present for cost calculations. Consider adding validation to ensure unit is present when input_price, output_price, or total_price are set.
langfuse-python
github_2023
others
1,071
langfuse
greptile-apps[bot]
@@ -116,7 +116,7 @@ The SDK defaults to a 60 second timeout. You can configure this with a timeout o ```python -from langfuse.api.client import FernLangfuse +from langfuse.client import FernLangfuse client = FernLangfuse(..., { timeout=20.0 }, )
logic: invalid dictionary syntax in example - should be timeout=20.0 as a kwarg, not in a dict
langfuse-python
github_2023
python
1,071
langfuse
greptile-apps[bot]
@@ -26,7 +26,7 @@ class CreateModelRequest(pydantic_v1.BaseModel): Apply only to generations which are newer than this ISO date. """ - unit: ModelUsageUnit = pydantic_v1.Field() + unit: typing.Optional[ModelUsageUnit] = pydantic_v1.Field(default=None) """ Unit used by this model. """
logic: Making `unit` optional without validation logic could lead to issues if the unit is required for certain model types or pricing calculations
langfuse-python
github_2023
python
1,068
langfuse
greptile-apps[bot]
@@ -24,14 +24,14 @@ class Model(pydantic_v1.BaseModel): Regex pattern which matches this model definition to generation.model. Useful in case of fine-tuned models. If you want to exact match, use `(?i)^modelname$` """ - start_date: typing.Optional[dt.date] = pydantic_v1.Field( + start_date: typing.Optional[dt.datetime] = pydantic_v1.Field( alias="startDate", default=None ) """ Apply only to generations which are newer than this ISO date. """ - unit: ModelUsageUnit = pydantic_v1.Field() + unit: typing.Optional[ModelUsageUnit] = pydantic_v1.Field(default=None) """ Unit used by this model. """
logic: Making unit optional may affect cost calculations if code assumes unit is always present. Ensure all consumers handle None case.
langfuse-python
github_2023
python
1,021
langfuse
greptile-apps[bot]
@@ -1,35 +1,133 @@ # This file was auto-generated by Fern from our API Definition. +import enum import typing -MediaContentType = typing.Literal[ - "image/png", - "image/jpeg", - "image/jpg", - "image/webp", - "image/gif", - "image/svg+xml", - "image/tiff", - "image/bmp", - "audio/mpeg", - "audio/mp3", - "audio/wav", - "audio/ogg", - "audio/oga", - "audio/aac", - "audio/mp4", - "audio/flac", - "video/mp4", - "video/webm", - "text/plain", - "text/html", - "text/css", - "text/csv", - "application/pdf", - "application/msword", - "application/vnd.ms-excel", - "application/zip", - "application/json", - "application/xml", - "application/octet-stream", -] +T_Result = typing.TypeVar("T_Result") + + +class MediaContentType(str, enum.Enum): + """ + The MIME type of the media record + """ + + IMAGE_PNG = "image/png" + IMAGE_JPEG = "image/jpeg" + IMAGE_JPG = "image/jpg" + IMAGE_WEBP = "image/webp" + IMAGE_GIF = "image/gif" + IMAGE_SVG_XML = "image/svg+xml" + IMAGE_TIFF = "image/tiff" + IMAGE_BMP = "image/bmp" + AUDIO_MPEG = "audio/mpeg" + AUDIO_MP_3 = "audio/mp3" + AUDIO_WAV = "audio/wav" + AUDIO_OGG = "audio/ogg" + AUDIO_OGA = "audio/oga" + AUDIO_AAC = "audio/aac" + AUDIO_MP_4 = "audio/mp4" + AUDIO_FLAC = "audio/flac" + VIDEO_MP_4 = "video/mp4" + VIDEO_WEBM = "video/webm" + TEXT_PLAIN = "text/plain" + TEXT_HTML = "text/html" + TEXT_CSS = "text/css" + TEXT_CSV = "text/csv" + APPLICATION_PDF = "application/pdf" + APPLICATION_MSWORD = "application/msword" + APPLICATION_MS_EXCEL = "application/vnd.ms-excel" + APPLICATION_ZIP = "application/zip" + APPLICATION_JSON = "application/json" + APPLICATION_XML = "application/xml" + APPLICATION_OCTET_STREAM = "application/octet-stream" + + def visit(
logic: visit() method lacks exhaustive check or default case. Consider adding a default handler or raising NotImplementedError for unhandled cases to prevent silent failures if new enum values are added.
langfuse-python
github_2023
python
1,021
langfuse
greptile-apps[bot]
@@ -0,0 +1,46 @@ +# 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 OpenAiUsageSchema(pydantic_v1.BaseModel): + prompt_tokens: int + completion_tokens: int + total_tokens: int
logic: total_tokens should validate that it equals prompt_tokens + completion_tokens
langfuse-python
github_2023
python
1,021
langfuse
greptile-apps[bot]
@@ -119,12 +118,12 @@ def update_generation_from_end_event( } self._get_generation_client(event.span_id).update( - usage=usage, end_time=_get_timestamp() + usage=usage, usage_details=usage, end_time=_get_timestamp() )
logic: passing same 'usage' value to both usage and usage_details fields may cause issues with backward compatibility since usage field is deprecated
langfuse-python
github_2023
python
1,046
langfuse
greptile-apps[bot]
@@ -54,6 +54,74 @@ class ChatMessageDict(TypedDict): content: str +class ChatMessageVariables(TypedDict): + role: str + variables: List[str] + + +class TemplateParser: + OPENING = "{{" + CLOSING = "}}" + + @staticmethod + def _parse_next_variable( + content: str, start_idx: int + ) -> Optional[Tuple[str, int, int]]: + """Returns (variable_name, start_pos, end_pos) or None if no variable found""" + var_start = content.find(TemplateParser.OPENING, start_idx) + if var_start == -1: + return None + + var_end = content.find(TemplateParser.CLOSING, var_start) + if var_end == -1: + return None + + variable_name = content[ + var_start + len(TemplateParser.OPENING) : var_end + ].strip() + return (variable_name, var_start, var_end + len(TemplateParser.CLOSING)) + + @staticmethod + def find_variable_names(content: str) -> List[str]: + names = [] + curr_idx = 0 + + while curr_idx < len(content): + result = TemplateParser._parse_next_variable(content, curr_idx) + if not result: + break + names.append(result[0]) + curr_idx = result[2] + + return names + + @staticmethod + def compile_template(content: str, data: Dict[str, Any] = {}) -> str:
logic: mutable default argument {} could cause issues with shared state between calls
langfuse-python
github_2023
python
1,046
langfuse
greptile-apps[bot]
@@ -29,103 +26,77 @@ def test_no_replacements(): template = "This is a test." expected = "This is a test." - assert BasePromptClient._compile_template_string(template) == expected + assert TemplateParser.compile_template(template) == expected def test_content_as_variable_name(): template = "This is a {{content}}." expected = "This is a dog." - assert ( - BasePromptClient._compile_template_string(template, {"content": "dog"}) - == expected - ) + assert TemplateParser.compile_template(template, {"content": "dog"}) == expected def test_unmatched_opening_tag(): template = "Hello, {{name! Your balance is $100." expected = "Hello, {{name! Your balance is $100." - assert ( - BasePromptClient._compile_template_string(template, {"name": "John"}) - == expected - ) + assert TemplateParser.compile_template(template, {"name": "John"}) == expected
logic: test case doesn't verify that other variables in the template still get replaced when there's an unmatched opening tag
langfuse-python
github_2023
python
1,046
langfuse
greptile-apps[bot]
@@ -54,6 +54,74 @@ class ChatMessageDict(TypedDict): content: str +class ChatMessageVariables(TypedDict): + role: str + variables: List[str] + + +class TemplateParser: + OPENING = "{{" + CLOSING = "}}" + + @staticmethod + def _parse_next_variable( + content: str, start_idx: int + ) -> Optional[Tuple[str, int, int]]: + """Returns (variable_name, start_pos, end_pos) or None if no variable found""" + var_start = content.find(TemplateParser.OPENING, start_idx) + if var_start == -1: + return None + + var_end = content.find(TemplateParser.CLOSING, var_start) + if var_end == -1: + return None + + variable_name = content[ + var_start + len(TemplateParser.OPENING) : var_end + ].strip()
logic: no validation of variable_name - empty/whitespace variables could cause issues
langfuse-python
github_2023
python
1,046
langfuse
greptile-apps[bot]
@@ -994,3 +994,106 @@ def test_do_not_link_observation_if_fallback(): assert len(trace.observations) == 1 assert trace.observations[0].prompt_id is None
logic: Missing assertion for observation type - should verify that the observation is a generation
langfuse-python
github_2023
python
1,046
langfuse
greptile-apps[bot]
@@ -85,55 +156,19 @@ def get_langchain_prompt(self): def _get_langchain_prompt_string(content: str): return re.sub(r"{{\s*(\w+)\s*}}", r"{\g<1>}", content)
logic: regex pattern \w+ only matches word chars - may need to support other valid variable name chars
langfuse-python
github_2023
python
1,033
langfuse
greptile-apps[bot]
@@ -150,23 +150,35 @@ def on_llm_new_token( self.updated_completion_start_time_memo.add(run_id) def get_langchain_run_name(self, serialized: Dict[str, Any], **kwargs: Any) -> str: - """Retrieves the 'run_name' for an entity based on Langchain convention, prioritizing the 'name' - key in 'kwargs' or falling back to the 'name' or 'id' in 'serialized'. Defaults to "<unknown>" - if none are available. + """Retrieve the name of a serialized LangChain runnable. + + The prioritization for the determination of the run name is as follows: + - The value assigned to the "name" key in `kwargs`. + - The value assigned to the "name" key in `serialized`. + - The last entry of the value assigned to the "id" key in `serialized`. + - "<unknown>". Args: - serialized (Dict[str, Any]): A dictionary containing the entity's serialized data. + serialized (Dict[str, Any]): A dictionary containing the runnable's serialized data. **kwargs (Any): Additional keyword arguments, potentially including the 'name' override. Returns: - str: The determined Langchain run name for the entity. + str: The determined name of the Langchain runnable. """ - # Check if 'name' is in kwargs and not None, otherwise use default fallback logic if "name" in kwargs and kwargs["name"] is not None: return kwargs["name"] - # Fallback to serialized 'name', 'id', or "<unknown>" - return serialized.get("name", serialized.get("id", ["<unknown>"])[-1]) + try: + return serialized["name"] + except (KeyError, TypeError): + pass + + try: + return serialized["id"][-1] + except (KeyError, TypeError):
logic: The code assumes serialized['id'] is a list. Add a type check to handle cases where 'id' exists but isn't a list
langfuse-python
github_2023
python
1,033
langfuse
hassiebp
@@ -150,23 +150,35 @@ def on_llm_new_token( self.updated_completion_start_time_memo.add(run_id) def get_langchain_run_name(self, serialized: Dict[str, Any], **kwargs: Any) -> str: - """Retrieves the 'run_name' for an entity based on Langchain convention, prioritizing the 'name' - key in 'kwargs' or falling back to the 'name' or 'id' in 'serialized'. Defaults to "<unknown>" - if none are available. + """Retrieve the name of a serialized LangChain runnable. + + The prioritization for the determination of the run name is as follows: + - The value assigned to the "name" key in `kwargs`. + - The value assigned to the "name" key in `serialized`. + - The last entry of the value assigned to the "id" key in `serialized`. + - "<unknown>". Args: - serialized (Dict[str, Any]): A dictionary containing the entity's serialized data. + serialized (Dict[str, Any]): A dictionary containing the runnable's serialized data. **kwargs (Any): Additional keyword arguments, potentially including the 'name' override. Returns: - str: The determined Langchain run name for the entity. + str: The determined name of the Langchain runnable. """ - # Check if 'name' is in kwargs and not None, otherwise use default fallback logic if "name" in kwargs and kwargs["name"] is not None: return kwargs["name"] - # Fallback to serialized 'name', 'id', or "<unknown>" - return serialized.get("name", serialized.get("id", ["<unknown>"])[-1])
What do you think about simply ```python return serialized.get("name", serialized.get("id", ["<unknown>"])[-1]) if serialized is not None and isinstance(serialized, dict) else <unknown> ```
langfuse-python
github_2023
python
1,033
langfuse
greptile-apps[bot]
@@ -123,21 +128,27 @@ def _extract_model_with_regex(pattern: str, text: str): def _extract_model_by_path_for_id( id: str, - serialized: dict, + serialized: Optional[Dict[str, Any]], kwargs: dict, keys: List[str], - select_from: str = Literal["serialized", "kwargs"], + select_from: Literal["serialized", "kwargs"], ): + if serialized is None and select_from == "serialized": + return None + if serialized.get("id")[-1] == id:
logic: Potential NullPointerException here - need to check if serialized.get('id') returns None before accessing [-1]
langfuse-python
github_2023
python
1,013
langfuse
greptile-apps[bot]
@@ -85,6 +90,28 @@ def get_langchain_prompt(self): def _get_langchain_prompt_string(content: str): return re.sub(r"{{\s*(\w+)\s*}}", r"{\g<1>}", content) + @staticmethod + def _find_variable_names(content: str) -> List[str]: + opening = "{{" + closing = "}}" + curr_idx = 0 + names = [] + + while curr_idx < len(content): + var_start = content.find(opening, curr_idx) + if var_start == -1: + break + + var_end = content.find(closing, var_start) + if var_end == -1: + break + + variable_name = content[var_start + len(opening) : var_end].strip() + names.append(variable_name) + curr_idx = var_end + len(closing) + + return names + @staticmethod def _compile_template_string(content: str, data: Dict[str, Any] = {}) -> str:
logic: mutable default argument {} could cause issues if modified - use None as default and initialize empty dict in method body
langfuse-python
github_2023
python
1,013
langfuse
greptile-apps[bot]
@@ -85,6 +90,28 @@ def get_langchain_prompt(self): def _get_langchain_prompt_string(content: str): return re.sub(r"{{\s*(\w+)\s*}}", r"{\g<1>}", content) + @staticmethod + def _find_variable_names(content: str) -> List[str]: + opening = "{{" + closing = "}}" + curr_idx = 0 + names = [] + + while curr_idx < len(content): + var_start = content.find(opening, curr_idx) + if var_start == -1: + break + + var_end = content.find(closing, var_start) + if var_end == -1: + break + + variable_name = content[var_start + len(opening) : var_end].strip() + names.append(variable_name)
logic: variable name extraction should validate that the name only contains valid characters (currently accepts any characters between braces)
langfuse-python
github_2023
python
1,013
langfuse
greptile-apps[bot]
@@ -85,6 +90,28 @@ def get_langchain_prompt(self): def _get_langchain_prompt_string(content: str): return re.sub(r"{{\s*(\w+)\s*}}", r"{\g<1>}", content) + @staticmethod + def _find_variable_names(content: str) -> List[str]: + opening = "{{" + closing = "}}" + curr_idx = 0 + names = [] + + while curr_idx < len(content): + var_start = content.find(opening, curr_idx) + if var_start == -1: + break + + var_end = content.find(closing, var_start) + if var_end == -1: + break
logic: missing closing brace could cause infinite loop - should throw a meaningful error instead of silently breaking
langfuse-python
github_2023
python
1,013
langfuse
greptile-apps[bot]
@@ -994,3 +994,106 @@ def test_do_not_link_observation_if_fallback(): assert len(trace.observations) == 1 assert trace.observations[0].prompt_id is None
logic: Incorrect assertion - should be 'assert trace.observations[0].prompt_id is None' since this is testing fallback behavior
langfuse-python
github_2023
python
1,013
langfuse
hassiebp
@@ -184,6 +219,21 @@ def compile(self, **kwargs) -> List[ChatMessageDict]: for chat_message in self.prompt ] + def variable_names(self) -> List[ChatMessageVariables]:
I think the utility of getting a list of variable names of a prompt it to verify before rendering the template whether all vars have been passed. From that lens, I don't understand why having a list of `ChatMessageVariables` has utility for chat prompts rather than a simple list of strings with the variable names. Is there a use case for you here @rhighs ?
langfuse-python
github_2023
python
1,013
langfuse
hassiebp
@@ -85,6 +90,28 @@ def get_langchain_prompt(self): def _get_langchain_prompt_string(content: str): return re.sub(r"{{\s*(\w+)\s*}}", r"{\g<1>}", content) + @staticmethod + def _find_variable_names(content: str) -> List[str]:
Please refactor reused logic into a shared utility. Suggestion by claude (please adapt accordingly) ```python class TemplateParser: OPENING = "{{" CLOSING = "}}" @staticmethod def _parse_next_variable(content: str, start_idx: int) -> Optional[Tuple[str, int, int]]: """Returns (variable_name, start_pos, end_pos) or None if no variable found""" var_start = content.find(TemplateParser.OPENING, start_idx) if var_start == -1: return None var_end = content.find(TemplateParser.CLOSING, var_start) if var_end == -1: return None variable_name = content[var_start + len(TemplateParser.OPENING):var_end].strip() return (variable_name, var_start, var_end + len(TemplateParser.CLOSING)) @staticmethod def find_variable_names(content: str) -> List[str]: names = [] curr_idx = 0 while curr_idx < len(content): result = TemplateParser._parse_next_variable(content, curr_idx) if not result: break names.append(result[0]) curr_idx = result[2] return names @staticmethod def compile_template(content: str, data: Dict[str, Any] = {}) -> str: result_list = [] curr_idx = 0 while curr_idx < len(content): result = TemplateParser._parse_next_variable(content, curr_idx) if not result: result_list.append(content[curr_idx:]) break variable_name, var_start, var_end = result result_list.append(content[curr_idx:var_start]) if variable_name in data: result_list.append(str(data[variable_name]) if data[variable_name] is not None else "") else: result_list.append(content[var_start:var_end]) curr_idx = var_end return "".join(result_list) ```
langfuse-python
github_2023
others
1,039
langfuse
greptile-apps[bot]
@@ -90,7 +90,7 @@ jobs: rm -rf .env echo "::group::Run server" - TELEMETRY_ENABLED=false LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT=http://localhost:9090 LANGFUSE_SDK_CI_SYNC_PROCESSING_ENABLED=true LANGFUSE_READ_FROM_POSTGRES_ONLY=true LANGFUSE_READ_FROM_CLICKHOUSE_ONLY=false LANGFUSE_RETURN_FROM_CLICKHOUSE=false docker compose up -d + TELEMETRY_ENABLED=false LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT=http://localhost:9090 LANGFUSE_SDK_CI_SYNC_PROCESSING_ENABLED=true LANGFUSE_READ_FROM_POSTGRES_ONLY=true LANGFUSE_READ_FROM_CLICKHOUSE_ONLY=false LANGFUSE_RETURN_FROM_CLICKHOUSE=false docker compose up -d
logic: PR description mentions changing endpoint to http://0.0.0.0:9090 but it's still set to http://localhost:9090. This may cause Docker networking issues.
langfuse-python
github_2023
python
1,037
langfuse
greptile-apps[bot]
@@ -275,8 +276,10 @@ def traverse(obj: Any, depth: int) -> Any: ) media_data = langfuse_client.fetch_media( parsed_media_reference["media_id"] + ).data + media_content = requests.get( + media_data.url, timeout=content_fetch_timeout_seconds )
logic: timeout only applies to the GET request, but not to the fetch_media call which could also hang. Consider wrapping both operations in a timeout
langfuse-python
github_2023
python
1,036
langfuse
greptile-apps[bot]
@@ -201,3 +205,116 @@ def _parse_base64_data_uri( self._log.error("Error parsing base64 data URI", exc_info=e) return None, None + + @staticmethod + def resolve_media_references( + *, + obj: T, + langfuse_client: Any, + resolve_with: Literal["base64_data_uri"], + max_depth: int = 10, + ) -> T: + """Replace media reference strings in an object with base64 data URIs. + + This method recursively traverses an object (up to max_depth) looking for media reference strings + in the format "@@@langfuseMedia:...@@@". When found, it (synchronously) fetches the actual media content using + the provided Langfuse client and replaces the reference string with a base64 data URI. + + If fetching media content fails for a reference string, a warning is logged and the reference + string is left unchanged. + + Args: + obj: The object to process. Can be a primitive value, array, or nested object. + If the object has a __dict__ attribute, a dict will be returned instead of the original object type. + langfuse_client: Langfuse client instance used to fetch media content. + resolve_with: The representation of the media content to replace the media reference string with. + Currently only "base64_data_uri" is supported. + max_depth: Optional. Default is 10. The maximum depth to traverse the object. + + Returns: + A deep copy of the input object with all media references replaced with base64 data URIs where possible. + If the input object has a __dict__ attribute, a dict will be returned instead of the original object type. + + Example: + obj = { + "image": "@@@langfuseMedia:type=image/jpeg|id=123|source=bytes@@@", + "nested": { + "pdf": "@@@langfuseMedia:type=application/pdf|id=456|source=bytes@@@" + } + } + + result = await LangfuseMedia.resolve_media_references(obj, langfuse_client) + + # Result: + # { + # "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg...", + # "nested": { + # "pdf": "data:application/pdf;base64,JVBERi0xLjcK..." + # } + # } + """ + + def traverse(obj: Any, depth: int) -> Any: + if depth > max_depth: + return obj + + # Handle string with potential media references + if isinstance(obj, str): + regex = r"@@@langfuseMedia:.+?@@@" + reference_string_matches = re.findall(regex, obj) + if len(reference_string_matches) == 0: + return obj + + result = obj + reference_string_to_media_content = {} + + for reference_string in reference_string_matches: + try: + parsed_media_reference = LangfuseMedia.parse_reference_string( + reference_string + ) + media_data = langfuse_client.fetch_media( + parsed_media_reference["media_id"] + ) + media_content = requests.get(media_data.url)
logic: Direct requests.get() call could hang indefinitely. Should add timeout parameter
langfuse-python
github_2023
python
1,036
langfuse
greptile-apps[bot]
@@ -201,3 +205,116 @@ def _parse_base64_data_uri( self._log.error("Error parsing base64 data URI", exc_info=e) return None, None + + @staticmethod + def resolve_media_references( + *, + obj: T, + langfuse_client: Any, + resolve_with: Literal["base64_data_uri"], + max_depth: int = 10, + ) -> T: + """Replace media reference strings in an object with base64 data URIs. + + This method recursively traverses an object (up to max_depth) looking for media reference strings + in the format "@@@langfuseMedia:...@@@". When found, it (synchronously) fetches the actual media content using + the provided Langfuse client and replaces the reference string with a base64 data URI. + + If fetching media content fails for a reference string, a warning is logged and the reference + string is left unchanged. + + Args: + obj: The object to process. Can be a primitive value, array, or nested object. + If the object has a __dict__ attribute, a dict will be returned instead of the original object type. + langfuse_client: Langfuse client instance used to fetch media content. + resolve_with: The representation of the media content to replace the media reference string with. + Currently only "base64_data_uri" is supported. + max_depth: Optional. Default is 10. The maximum depth to traverse the object. + + Returns: + A deep copy of the input object with all media references replaced with base64 data URIs where possible. + If the input object has a __dict__ attribute, a dict will be returned instead of the original object type. + + Example: + obj = { + "image": "@@@langfuseMedia:type=image/jpeg|id=123|source=bytes@@@", + "nested": { + "pdf": "@@@langfuseMedia:type=application/pdf|id=456|source=bytes@@@" + } + } + + result = await LangfuseMedia.resolve_media_references(obj, langfuse_client) + + # Result: + # { + # "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg...", + # "nested": { + # "pdf": "data:application/pdf;base64,JVBERi0xLjcK..." + # } + # } + """ + + def traverse(obj: Any, depth: int) -> Any: + if depth > max_depth: + return obj + + # Handle string with potential media references + if isinstance(obj, str): + regex = r"@@@langfuseMedia:.+?@@@"
logic: Regex pattern .+? is greedy and could match more than intended. Use [^@]+ instead
langfuse-python
github_2023
python
1,036
langfuse
greptile-apps[bot]
@@ -201,3 +205,116 @@ def _parse_base64_data_uri( self._log.error("Error parsing base64 data URI", exc_info=e) return None, None + + @staticmethod + def resolve_media_references( + *, + obj: T, + langfuse_client: Any, + resolve_with: Literal["base64_data_uri"], + max_depth: int = 10, + ) -> T: + """Replace media reference strings in an object with base64 data URIs. + + This method recursively traverses an object (up to max_depth) looking for media reference strings + in the format "@@@langfuseMedia:...@@@". When found, it (synchronously) fetches the actual media content using + the provided Langfuse client and replaces the reference string with a base64 data URI. + + If fetching media content fails for a reference string, a warning is logged and the reference + string is left unchanged. + + Args: + obj: The object to process. Can be a primitive value, array, or nested object. + If the object has a __dict__ attribute, a dict will be returned instead of the original object type. + langfuse_client: Langfuse client instance used to fetch media content. + resolve_with: The representation of the media content to replace the media reference string with. + Currently only "base64_data_uri" is supported. + max_depth: Optional. Default is 10. The maximum depth to traverse the object. + + Returns: + A deep copy of the input object with all media references replaced with base64 data URIs where possible. + If the input object has a __dict__ attribute, a dict will be returned instead of the original object type. + + Example: + obj = { + "image": "@@@langfuseMedia:type=image/jpeg|id=123|source=bytes@@@", + "nested": { + "pdf": "@@@langfuseMedia:type=application/pdf|id=456|source=bytes@@@" + } + } + + result = await LangfuseMedia.resolve_media_references(obj, langfuse_client) + + # Result: + # { + # "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg...", + # "nested": { + # "pdf": "data:application/pdf;base64,JVBERi0xLjcK..." + # } + # } + """ + + def traverse(obj: Any, depth: int) -> Any: + if depth > max_depth: + return obj + + # Handle string with potential media references + if isinstance(obj, str): + regex = r"@@@langfuseMedia:.+?@@@" + reference_string_matches = re.findall(regex, obj) + if len(reference_string_matches) == 0: + return obj + + result = obj + reference_string_to_media_content = {} + + for reference_string in reference_string_matches: + try: + parsed_media_reference = LangfuseMedia.parse_reference_string( + reference_string + ) + media_data = langfuse_client.fetch_media( + parsed_media_reference["media_id"] + ) + media_content = requests.get(media_data.url) + if not media_content.ok: + raise Exception("Failed to fetch media content") + + base64_media_content = base64.b64encode( + media_content.content + ).decode() + base64_data_uri = f"data:{media_data.content_type};base64,{base64_media_content}" + + reference_string_to_media_content[reference_string] = ( + base64_data_uri + ) + except Exception as e: + logging.warning(
logic: Using root logging instead of class logger self._log
langfuse-python
github_2023
python
1,036
langfuse
greptile-apps[bot]
@@ -104,3 +108,63 @@ def test_nonexistent_file(): assert media._source is None assert media._content_bytes is None assert media._content_type is None + + +def test_replace_media_reference_string_in_object(tmp_path): + # Create test audio file + audio_file = "static/joke_prompt.wav" + with open(audio_file, "rb") as f: + mock_audio_bytes = f.read()
logic: test depends on external file 'static/joke_prompt.wav' which may not exist in all environments - should use a small mock file or fixture instead
langfuse-python
github_2023
python
1,036
langfuse
greptile-apps[bot]
@@ -104,3 +108,63 @@ def test_nonexistent_file(): assert media._source is None assert media._content_bytes is None assert media._content_type is None + + +def test_replace_media_reference_string_in_object(tmp_path): + # Create test audio file + audio_file = "static/joke_prompt.wav" + with open(audio_file, "rb") as f: + mock_audio_bytes = f.read() + + # Create Langfuse client and trace with media + langfuse = Langfuse()
logic: Langfuse client initialized without credentials - test may fail in CI/CD. Should mock or provide test credentials
langfuse-python
github_2023
python
1,036
langfuse
ellipsis-dev[bot]
@@ -885,6 +885,20 @@ def fetch_observation( handle_fern_exception(e) raise e + def fetch_media(self, id: str): + """Get media content by ID. + + Args: + id: The identifier of the media content to fetch. + + Returns: + Media object + + Raises: + Exception: If the media content could not be found or if an error occurred during the request. + """ + return self.client.media.get(id)
Consider adding exception handling for the `self.client.media.get(id)` call to handle potential errors gracefully.
langfuse-python
github_2023
python
1,031
langfuse
greptile-apps[bot]
@@ -170,6 +170,11 @@ def get_langfuse_args(self): return {**self.args, **self.kwargs} def get_openai_args(self): + # If OpenAI model distillation is enabled, we need to add the metadata to the kwargs + # https://platform.openai.com/docs/guides/distillation + if self.kwargs.get("store", False): + self.kwargs["metadata"] = self.args.get("metadata", {})
logic: potential overwrite of existing metadata in kwargs - should merge with existing metadata instead of replacing
langfuse-python
github_2023
python
1,024
langfuse
greptile-apps[bot]
@@ -1536,3 +1536,17 @@ def faulty_mask_func(data): fetched_trace = api_wrapper.get_trace(trace.id) assert fetched_trace["input"] == "<fully masked due to failed mask function>" assert fetched_trace["output"] == "<fully masked due to failed mask function>" + + +def test_generate_trace_id(): + langfuse = Langfuse(debug=False) + trace_id = create_uuid() + + trace = langfuse.trace(id=trace_id, name="test_trace") + langfuse.flush() + + trace_url = langfuse.get_trace_url() + assert ( + trace_url + == f"https://localhost:3000/7a88fb47-b4e2-43b8-a06c-a5ce950dc53a/traces/{trace_id}" + )
logic: The hardcoded localhost URL and project ID make this test brittle and environment-dependent. The test should use the actual base_url from the Langfuse client and fetch the project ID dynamically.
langfuse-python
github_2023
python
1,024
langfuse
greptile-apps[bot]
@@ -330,7 +333,14 @@ def get_trace_id(self) -> str: def get_trace_url(self) -> str: """Get the URL of the current trace to view it in the Langfuse UI.""" - return f"{self.base_url}/trace/{self.trace_id}" + if not self.trace_id: + proj = self.client.projects.get() + if not proj.data or not proj.data[0].id: + return f"{self.base_url}/trace/{self.trace_id}" +
logic: this will return an invalid URL if trace_id is None, since it's used in both the fallback and final URL construction
langfuse-python
github_2023
python
1,024
langfuse
greptile-apps[bot]
@@ -330,7 +333,14 @@ def get_trace_id(self) -> str: def get_trace_url(self) -> str: """Get the URL of the current trace to view it in the Langfuse UI.""" - return f"{self.base_url}/trace/{self.trace_id}" + if not self.trace_id: + proj = self.client.projects.get() + if not proj.data or not proj.data[0].id: + return f"{self.base_url}/trace/{self.trace_id}"
logic: should check if proj.data exists before accessing index 0 to avoid potential IndexError
langfuse-python
github_2023
python
1,024
langfuse
ellipsis-dev[bot]
@@ -1536,3 +1536,17 @@ def faulty_mask_func(data): fetched_trace = api_wrapper.get_trace(trace.id) assert fetched_trace["input"] == "<fully masked due to failed mask function>" assert fetched_trace["output"] == "<fully masked due to failed mask function>" + + +def test_generate_trace_id(): + langfuse = Langfuse(debug=False) + trace_id = create_uuid() + + trace = langfuse.trace(id=trace_id, name="test_trace") + langfuse.flush() + + trace_url = langfuse.get_trace_url() + assert (
Avoid hardcoding the project ID in the expected URL. Instead, use the actual project ID from the `langfuse` instance to construct the expected URL.
langfuse-python
github_2023
python
1,024
langfuse
greptile-apps[bot]
@@ -330,7 +334,14 @@ def get_trace_id(self) -> str: def get_trace_url(self) -> str: """Get the URL of the current trace to view it in the Langfuse UI.""" - return f"{self.base_url}/trace/{self.trace_id}" + if not self.project_id: + proj = self.client.projects.get() + if not proj.data or not proj.data[0].id: + return f"{self.base_url}/trace/{self.trace_id}"
logic: checking project_id instead of trace_id means the project API call will happen even when trace_id is not set, which will result in an invalid URL
langfuse-python
github_2023
python
1,024
langfuse
ellipsis-dev[bot]
@@ -1536,3 +1536,17 @@ def faulty_mask_func(data): fetched_trace = api_wrapper.get_trace(trace.id) assert fetched_trace["input"] == "<fully masked due to failed mask function>" assert fetched_trace["output"] == "<fully masked due to failed mask function>" + + +def test_generate_trace_id(): + langfuse = Langfuse(debug=False) + trace_id = create_uuid() + + trace = langfuse.trace(id=trace_id, name="test_trace") + langfuse.flush() + + trace_url = langfuse.get_trace_url() + assert ( + trace_url + == f"http://localhost:3000/7a88fb47-b4e2-43b8-a06c-a5ce950dc53a/traces/{trace_id}"
Use `langfuse.base_url` instead of hardcoded URL for consistency. ```suggestion trace_url == f"{langfuse.base_url}/7a88fb47-b4e2-43b8-a06c-a5ce950dc53a/traces/{trace_id}" ```
langfuse-python
github_2023
python
1,024
langfuse
hassiebp
@@ -330,7 +334,14 @@ def get_trace_id(self) -> str: def get_trace_url(self) -> str: """Get the URL of the current trace to view it in the Langfuse UI.""" - return f"{self.base_url}/trace/{self.trace_id}" + if not self.project_id: + proj = self.client.projects.get() + if not proj.data or not proj.data[0].id: + return f"{self.base_url}/trace/{self.trace_id}" + + self.project_id = proj.data[0].id
note: Relationship between public-key and project is 1:1 so returning an array of projects from this endpoint is unintuitive 🤔
langfuse-python
github_2023
others
1,022
langfuse
greptile-apps[bot]
@@ -90,7 +90,7 @@ jobs: rm -rf .env echo "::group::Run server" - TELEMETRY_ENABLED=false CLICKHOUSE_CLUSTER_ENABLED=false LANGFUSE_ASYNC_INGESTION_PROCESSING=false LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING=false LANGFUSE_READ_FROM_POSTGRES_ONLY=true LANGFUSE_RETURN_FROM_CLICKHOUSE=false docker compose -f docker-compose.v3preview.yml up -d + TELEMETRY_ENABLED=false LANGFUSE_CI_SYNC_PROCESSING_ENABELD=true LANGFUSE_READ_FROM_POSTGRES_ONLY=true LANGFUSE_RETURN_FROM_CLICKHOUSE=false LANGFUSE_RETURN_FROM_CLICKHOUSE=false docker compose up -d
logic: LANGFUSE_RETURN_FROM_CLICKHOUSE is duplicated in the environment variables
langfuse-python
github_2023
others
1,011
langfuse
greptile-apps[bot]
@@ -17,7 +17,7 @@ Instantiate and use the client with the following: ```python from finto import CreateCommentRequest -from finto.client import FernLangfuse +from langfuse.api.client import FernLangfuse
logic: This import still uses 'finto' while other imports have been updated to 'langfuse'
langfuse-python
github_2023
python
1,011
langfuse
greptile-apps[bot]
@@ -49,7 +49,7 @@ def create( Examples -------- from finto import CreateCommentRequest - from finto.client import FernLangfuse + from langfuse.api.client import FernLangfuse
logic: import path still references 'finto' for CreateCommentRequest but uses 'langfuse.api.client' for FernLangfuse
langfuse-python
github_2023
python
1,011
langfuse
greptile-apps[bot]
@@ -45,7 +48,7 @@ def create( Examples -------- from finto import CreateDatasetItemRequest, DatasetStatus - from finto.client import FernLangfuse + from langfuse.api.client import FernLangfuse
logic: import path still uses 'finto' instead of 'langfuse.api' for CreateDatasetItemRequest and DatasetStatus
langfuse-python
github_2023
python
1,011
langfuse
greptile-apps[bot]
@@ -43,7 +46,7 @@ def create( Examples -------- from finto import CreateDatasetRunItemRequest - from finto.client import FernLangfuse + from langfuse.api.client import FernLangfuse
logic: import path still references 'finto' for CreateDatasetRunItemRequest but uses 'langfuse.api.client' for FernLangfuse - these should be consistent
langfuse-python
github_2023
python
1,011
langfuse
greptile-apps[bot]
@@ -112,7 +130,7 @@ async def create( import asyncio from finto import CreateDatasetRunItemRequest - from finto.client import AsyncFernLangfuse + from langfuse.api.client import AsyncFernLangfuse
logic: same inconsistent import pattern here - should use langfuse.api instead of finto
langfuse-python
github_2023
python
1,011
langfuse
greptile-apps[bot]
@@ -20,22 +22,37 @@ class CreateDatasetRunItemRequest(pydantic_v1.BaseModel): """ dataset_item_id: str = pydantic_v1.Field(alias="datasetItemId") - observation_id: typing.Optional[str] = pydantic_v1.Field(alias="observationId", default=None) + observation_id: typing.Optional[str] = pydantic_v1.Field( + alias="observationId", default=None + ) trace_id: typing.Optional[str] = pydantic_v1.Field(alias="traceId", default=None) """ traceId should always be provided. For compatibility with older SDK versions it can also be inferred from the provided observationId. """
logic: docstring indicates traceId 'should always be provided' but the field is marked as Optional. Consider making this field required if it should always be present
langfuse-python
github_2023
python
1,011
langfuse
greptile-apps[bot]
@@ -165,7 +191,7 @@ def create( Examples -------- from finto import CreateDatasetRequest
logic: import path still references 'finto' instead of 'langfuse.api' for CreateDatasetRequest
langfuse-python
github_2023
python
1,011
langfuse
greptile-apps[bot]
@@ -494,7 +578,7 @@ async def create( import asyncio from finto import CreateDatasetRequest
logic: import path still references 'finto' instead of 'langfuse.api' for CreateDatasetRequest in async example
langfuse-python
github_2023
python
1,011
langfuse
greptile-apps[bot]
@@ -58,7 +58,7 @@ def batch( import datetime from finto import IngestionEvent_TraceCreate, TraceBody - from finto.client import FernLangfuse + from langfuse.api.client import FernLangfuse
logic: The import still references 'finto' package while using 'langfuse.api.client'
langfuse-python
github_2023
python
1,011
langfuse
greptile-apps[bot]
@@ -120,7 +120,7 @@ def patch( import datetime from finto import PatchMediaBody - from finto.client import FernLangfuse + from langfuse.api.client import FernLangfuse
logic: inconsistent import paths - still using 'finto' for PatchMediaBody while main client import was updated to langfuse.api.client
langfuse-python
github_2023
python
1,011
langfuse
greptile-apps[bot]
@@ -198,7 +198,7 @@ def get_upload_url( Examples -------- from finto import GetMediaUploadUrlRequest - from finto.client import FernLangfuse + from langfuse.api.client import FernLangfuse
logic: inconsistent import paths - still using 'finto' for GetMediaUploadUrlRequest while main client import was updated to langfuse.api.client
langfuse-python
github_2023
python
1,011
langfuse
greptile-apps[bot]
@@ -50,7 +50,7 @@ def create( import datetime from finto import CreateModelRequest, ModelUsageUnit - from finto.client import FernLangfuse + from langfuse.api.client import FernLangfuse
logic: import path for CreateModelRequest and ModelUsageUnit still references 'finto' but should be updated to 'langfuse.api'