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 / ...
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 fit...
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.Cal...
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 AnnotationQueueObjectTyp...
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 AnnotationQueueOb...
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_opt...
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...
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", No...
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(out...
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 = cho...
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: ...
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] + + ...
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] + + ...
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] + + ...
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) + ...
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.environme...
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 wil...
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 alphanumer...
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) + ...
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(E...
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 si...
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 `L...
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", {}) +...
```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 "...
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", + ( + ...
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", + ( + ...
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)) ...
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...
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 impo...
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_Res...
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 ( + ...
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 ...
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_wit...
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 = creat...
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 = creat...
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 = crea...
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 ....
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=["p...
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 w...
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( ...
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( ...
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}" resp...
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}" resp...
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 scor...
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.Opt...
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"...
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): + pr...
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 + ) ...
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 = "...
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 + ) ...
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 i...
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 i...
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[...
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 + ...
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 + ...
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 + ...
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 t...
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 (variabl...
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_FR...
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( + ...
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...
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...
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...
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(a...
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(a...
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 + + Rais...
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("stor...
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 ...
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...
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...
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 ...
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() + ...
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 ...
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() + ...
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=...
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( ...
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'