Skip to content

Commit a655738

Browse files
committed
push
1 parent 0d75384 commit a655738

8 files changed

Lines changed: 55 additions & 41 deletions

File tree

langfuse/_client/attributes.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
import json
1414
from datetime import datetime
15-
from typing import Any, Dict, List, Literal, Optional
15+
from typing import Any, Dict, List, Literal, Optional, Union
1616

1717
from langfuse._utils.serializer import EventSerializer
1818
from langfuse.model import PromptClient
@@ -164,14 +164,14 @@ def _flatten_and_serialize_metadata(
164164
else LangfuseOtelSpanAttributes.TRACE_METADATA
165165
)
166166

167-
metadata_attributes = {}
167+
metadata_attributes: Dict[str, Union[str, int, None]] = {}
168168

169169
if not isinstance(metadata, dict):
170170
metadata_attributes[prefix] = _serialize(metadata)
171171
else:
172172
for key, value in metadata.items():
173173
metadata_attributes[f"{prefix}.{key}"] = (
174-
str(value)
174+
value
175175
if isinstance(value, str) or isinstance(value, int)
176176
else _serialize(value)
177177
)

langfuse/_client/client.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ class Langfuse:
147147

148148
_resources: Optional[LangfuseResourceManager] = None
149149
_mask: Optional[MaskFunction] = None
150+
_otel_tracer: otel_trace_api.Tracer
150151

151152
def __init__(
152153
self,
@@ -167,10 +168,14 @@ def __init__(
167168
mask: Optional[MaskFunction] = None,
168169
blocked_instrumentation_scopes: Optional[List[str]] = None,
169170
additional_headers: Optional[Dict[str, str]] = None,
170-
tracer_provider: Optional[otel_trace_api.TracerProvider] = None,
171+
tracer_provider: Optional[TracerProvider] = None,
171172
):
172-
self._host = host or os.environ.get(LANGFUSE_HOST, "https://cloud.langfuse.com")
173-
self._environment = environment or os.environ.get(LANGFUSE_TRACING_ENVIRONMENT)
173+
self._host = host or cast(
174+
str, os.environ.get(LANGFUSE_HOST, "https://cloud.langfuse.com")
175+
)
176+
self._environment = environment or cast(
177+
str, os.environ.get(LANGFUSE_TRACING_ENVIRONMENT)
178+
)
174179
self._project_id: Optional[str] = None
175180
sample_rate = sample_rate or float(os.environ.get(LANGFUSE_SAMPLE_RATE, 1.0))
176181
if not 0.0 <= sample_rate <= 1.0:
@@ -218,7 +223,7 @@ def __init__(
218223
self._resources = LangfuseResourceManager(
219224
public_key=public_key,
220225
secret_key=secret_key,
221-
host=self._host or "https://cloud.langfuse.com",
226+
host=self._host,
222227
timeout=timeout,
223228
environment=environment,
224229
release=release,
@@ -231,15 +236,14 @@ def __init__(
231236
tracing_enabled=self._tracing_enabled,
232237
blocked_instrumentation_scopes=blocked_instrumentation_scopes,
233238
additional_headers=additional_headers,
234-
tracer_provider=cast(Optional[TracerProvider], tracer_provider),
239+
tracer_provider=tracer_provider,
235240
)
236241
self._mask = self._resources.mask
237242

238-
self._otel_tracer = cast(
239-
Any,
243+
self._otel_tracer = (
240244
self._resources.tracer
241245
if self._tracing_enabled and self._resources.tracer is not None
242-
else otel_trace_api.NoOpTracer(),
246+
else otel_trace_api.NoOpTracer()
243247
)
244248
self.api = self._resources.api
245249
self.async_api = self._resources.async_api
@@ -660,8 +664,8 @@ def _create_span_with_parent_context(
660664
self,
661665
*,
662666
name: str,
663-
parent: Any,
664-
remote_parent_span: Any,
667+
parent: Optional[otel_trace_api.Span] = None,
668+
remote_parent_span: Optional[otel_trace_api.Span] = None,
665669
as_type: Literal["generation", "span"],
666670
end_on_exit: Optional[bool] = None,
667671
input: Optional[Any] = None,

langfuse/_client/datasets.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import datetime as dt
22
import logging
3+
from .span import LangfuseSpan
34
from typing import TYPE_CHECKING, Any, Generator, List, Optional
45

56
from opentelemetry.util._decorator import _agnosticcontextmanager
@@ -91,7 +92,7 @@ def run(
9192
run_name: str,
9293
run_metadata: Optional[Any] = None,
9394
run_description: Optional[str] = None,
94-
) -> Generator[Any, None, None]:
95+
) -> Generator[LangfuseSpan, None, None]:
9596
"""Create a context manager for the dataset item run that links the execution to a Langfuse trace.
9697
9798
This method is a context manager that creates a trace for the dataset run and yields a span

langfuse/_client/observe.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -207,9 +207,11 @@ def _async_observe(
207207
transform_to_string: Optional[Callable[[Iterable], str]] = None,
208208
) -> F:
209209
@wraps(func)
210-
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
211-
trace_id = kwargs.pop("langfuse_trace_id", None)
212-
parent_observation_id = kwargs.pop("langfuse_parent_observation_id", None)
210+
async def async_wrapper(*args: Tuple[Any], **kwargs: Dict[str, Any]) -> Any:
211+
trace_id = cast(str, kwargs.pop("langfuse_trace_id", None))
212+
parent_observation_id = cast(
213+
str, kwargs.pop("langfuse_parent_observation_id", None)
214+
)
213215
trace_context: Optional[TraceContext] = (
214216
{
215217
"trace_id": trace_id,
@@ -228,7 +230,7 @@ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
228230
if capture_input
229231
else None
230232
)
231-
public_key = kwargs.pop("langfuse_public_key", None)
233+
public_key = cast(str, kwargs.pop("langfuse_public_key", None))
232234
langfuse_client = get_client(public_key=public_key)
233235
context_manager: Optional[
234236
Union[

langfuse/_client/span.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1071,7 +1071,7 @@ def update(
10711071
usage_details: Optional[Dict[str, int]] = None,
10721072
cost_details: Optional[Dict[str, float]] = None,
10731073
prompt: Optional[PromptClient] = None,
1074-
**kwargs: Any,
1074+
**kwargs: Dict[str, Any],
10751075
) -> "LangfuseGeneration":
10761076
"""Update this generation span with new information.
10771077

langfuse/_task_manager/media_manager.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -170,18 +170,18 @@ def _process_media(
170170
trace_id: str,
171171
observation_id: Optional[str],
172172
field: str,
173-
) -> str:
173+
) -> None:
174174
if (
175175
media._content_length is None
176176
or media._content_type is None
177177
or media._content_sha256_hash is None
178178
or media._content_bytes is None
179179
):
180-
return ""
180+
return
181181

182182
if media._media_id is None:
183183
self._log.error("Media ID is None. Skipping upload.")
184-
return ""
184+
return
185185

186186
try:
187187
upload_media_job = UploadMediaJob(
@@ -212,9 +212,6 @@ def _process_media(
212212
self._log.error(
213213
f"Media processing error: Failed to process media_id={media._media_id} for trace_id={trace_id}. Error: {str(e)}"
214214
)
215-
return ""
216-
217-
return media._reference_string or ""
218215

219216
def _process_upload_media_job(
220217
self,

langfuse/_utils/parse_error.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def generate_error_message_fern(error: Error) -> str:
6363
else defaultErrorResponse
6464
)
6565

66-
# This line is unreachable but kept for completeness
66+
return defaultErrorResponse # type: ignore
6767

6868

6969
def handle_fern_exception(exception: Error) -> None:

langfuse/model.py

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import re
44
from abc import ABC, abstractmethod
5-
from typing import Any, Dict, List, Literal, Optional, Tuple, TypedDict, Union
5+
from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, TypedDict, Union
66
from langfuse.logger import langfuse_logger
77

88
from langfuse.api.resources.commons.types.dataset import (
@@ -161,7 +161,12 @@ def __init__(self, prompt: Prompt, is_fallback: bool = False):
161161
self.is_fallback = is_fallback
162162

163163
@abstractmethod
164-
def compile(self, **kwargs: Any) -> Union[str, List[Dict[str, Any]]]:
164+
def compile(
165+
self, **kwargs: Union[str, Any]
166+
) -> Union[
167+
str,
168+
Sequence[Union[ChatMessageDict, ChatMessageWithPlaceholdersDict_Placeholder]],
169+
]:
165170
pass
166171

167172
@property
@@ -255,7 +260,7 @@ def __init__(self, prompt: Prompt_Text, is_fallback: bool = False):
255260
super().__init__(prompt, is_fallback)
256261
self.prompt = prompt.prompt
257262

258-
def compile(self, **kwargs: Any) -> str:
263+
def compile(self, **kwargs: Union[str, Any]) -> str:
259264
return TemplateParser.compile_template(self.prompt, kwargs)
260265

261266
@property
@@ -274,7 +279,7 @@ def __eq__(self, other: object) -> bool:
274279

275280
return False
276281

277-
def get_langchain_prompt(self, **kwargs: Any) -> str:
282+
def get_langchain_prompt(self, **kwargs: Union[str, Any]) -> str:
278283
"""Convert Langfuse prompt into string compatible with Langchain PromptTemplate.
279284
280285
This method adapts the mustache-style double curly braces {{variable}} used in Langfuse
@@ -314,12 +319,15 @@ def __init__(self, prompt: Prompt_Chat, is_fallback: bool = False):
314319
self.prompt.append(
315320
ChatMessageWithPlaceholdersDict_Message(
316321
type="message",
317-
role=p.role,
318-
content=p.content,
322+
role=p.role, # type: ignore
323+
content=p.content, # type: ignore
319324
),
320325
)
321326

322-
def compile(self, **kwargs: Any) -> List[Dict[str, Any]]:
327+
def compile(
328+
self,
329+
**kwargs: Union[str, Any],
330+
) -> Sequence[Union[ChatMessageDict, ChatMessageWithPlaceholdersDict_Placeholder]]:
323331
"""Compile the prompt with placeholders and variables.
324332
325333
Args:
@@ -358,9 +366,9 @@ def compile(self, **kwargs: Any) -> List[Dict[str, Any]]:
358366
):
359367
compiled_messages.append(
360368
{
361-
"role": msg["role"],
369+
"role": msg["role"], # type: ignore
362370
"content": TemplateParser.compile_template(
363-
msg["content"],
371+
msg["content"], # type: ignore
364372
kwargs,
365373
),
366374
},
@@ -392,7 +400,7 @@ def compile(self, **kwargs: Any) -> List[Dict[str, Any]]:
392400
unresolved_placeholders_message = f"Placeholders {unresolved_placeholders} have not been resolved. Pass them as keyword arguments to compile()."
393401
langfuse_logger.warning(unresolved_placeholders_message)
394402

395-
return compiled_messages
403+
return compiled_messages # type: ignore
396404

397405
@property
398406
def variables(self) -> List[str]:
@@ -434,7 +442,9 @@ def __eq__(self, other: object) -> bool:
434442

435443
return False
436444

437-
def get_langchain_prompt(self, **kwargs: Any) -> List[Union[Tuple[str, str], Any]]:
445+
def get_langchain_prompt(
446+
self, **kwargs: Union[str, Any]
447+
) -> List[Union[Tuple[str, str], Any]]:
438448
"""Convert Langfuse prompt into string compatible with Langchain ChatPromptTemplate.
439449
440450
It specifically adapts the mustache-style double curly braces {{variable}} used in Langfuse
@@ -455,9 +465,9 @@ def get_langchain_prompt(self, **kwargs: Any) -> List[Union[Tuple[str, str], Any
455465
langchain_messages: List[Union[Tuple[str, str], Any]] = []
456466

457467
for msg in compiled_messages:
458-
if isinstance(msg, dict) and "type" in msg and msg["type"] == "placeholder":
468+
if isinstance(msg, dict) and "type" in msg and msg["type"] == "placeholder": # type: ignore
459469
# unresolved placeholder -> add LC MessagesPlaceholder
460-
placeholder_name = msg["name"]
470+
placeholder_name = msg["name"] # type: ignore
461471
try:
462472
from langchain_core.prompts.chat import MessagesPlaceholder # noqa: PLC0415, I001
463473

@@ -471,8 +481,8 @@ def get_langchain_prompt(self, **kwargs: Any) -> List[Union[Tuple[str, str], Any
471481
if isinstance(msg, dict) and "role" in msg and "content" in msg:
472482
langchain_messages.append(
473483
(
474-
msg["role"],
475-
self._get_langchain_prompt_string(msg["content"]),
484+
msg["role"], # type: ignore
485+
self._get_langchain_prompt_string(msg["content"]), # type: ignore
476486
),
477487
)
478488

0 commit comments

Comments
 (0)