-
Notifications
You must be signed in to change notification settings - Fork 261
Expand file tree
/
Copy pathCallbackHandler.py
More file actions
1377 lines (1166 loc) · 46.4 KB
/
CallbackHandler.py
File metadata and controls
1377 lines (1166 loc) · 46.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from contextvars import Token
from typing import (
Any,
Dict,
List,
Literal,
Optional,
Sequence,
Set,
Type,
Union,
cast,
)
from uuid import UUID
import pydantic
from opentelemetry import context, trace
from opentelemetry.context import _RUNTIME_CONTEXT
from opentelemetry.util._decorator import _AgnosticContextManager
from langfuse import propagate_attributes
from langfuse._client.attributes import LangfuseOtelSpanAttributes
from langfuse._client.client import Langfuse
from langfuse._client.get_client import get_client
from langfuse._client.span import (
LangfuseAgent,
LangfuseChain,
LangfuseGeneration,
LangfuseRetriever,
LangfuseSpan,
LangfuseTool,
)
from langfuse._utils import _get_timestamp
from langfuse.langchain.utils import _extract_model_name
from langfuse.logger import langfuse_logger
from langfuse.types import TraceContext
try:
import langchain
if langchain.__version__.startswith("1"):
# Langchain v1
from langchain_core.agents import AgentAction, AgentFinish
from langchain_core.callbacks import (
BaseCallbackHandler as LangchainBaseCallbackHandler,
)
from langchain_core.documents import Document
from langchain_core.messages import (
AIMessage,
BaseMessage,
ChatMessage,
FunctionMessage,
HumanMessage,
SystemMessage,
ToolMessage,
)
from langchain_core.outputs import ChatGeneration, LLMResult
else:
# Langchain v0
from langchain.callbacks.base import ( # type: ignore
BaseCallbackHandler as LangchainBaseCallbackHandler,
)
from langchain.schema.agent import AgentAction, AgentFinish # type: ignore
from langchain.schema.document import Document # type: ignore
from langchain_core.messages import (
AIMessage,
BaseMessage,
ChatMessage,
FunctionMessage,
HumanMessage,
SystemMessage,
ToolMessage,
)
from langchain_core.outputs import (
ChatGeneration,
LLMResult,
)
except ImportError:
raise ModuleNotFoundError(
"Please install langchain to use the Langfuse langchain integration: 'pip install langchain'"
)
LANGSMITH_TAG_HIDDEN: str = "langsmith:hidden"
CONTROL_FLOW_EXCEPTION_TYPES: Set[Type[BaseException]] = set()
try:
from langgraph.errors import GraphBubbleUp
CONTROL_FLOW_EXCEPTION_TYPES.add(GraphBubbleUp)
except ImportError:
pass
class LangchainCallbackHandler(LangchainBaseCallbackHandler):
def __init__(
self,
*,
public_key: Optional[str] = None,
trace_context: Optional[TraceContext] = None,
) -> None:
"""Initialize the LangchainCallbackHandler.
Args:
public_key: Optional Langfuse public key. If not provided, will use the default client configuration.
trace_context: Optional context for connecting to an existing trace (distributed tracing) or
setting a custom trace id for the root LangChain run. Pass a `TraceContext` dict, e.g.
`{"trace_id": "<trace_id>"}` (and optionally `{"parent_span_id": "<span_id>"}`) to link
the trace to an upstream system.
Example:
Use a custom trace id without context managers:
```python
from langfuse.langchain import CallbackHandler
handler = CallbackHandler(trace_context={"trace_id": "my-trace-id"})
```
"""
self._langfuse_client = get_client(public_key=public_key)
self._runs: Dict[
UUID,
Union[
LangfuseSpan,
LangfuseGeneration,
LangfuseAgent,
LangfuseChain,
LangfuseTool,
LangfuseRetriever,
],
] = {}
self._context_tokens: Dict[UUID, Token] = {}
self._prompt_to_parent_run_map: Dict[UUID, Any] = {}
self._updated_completion_start_time_memo: Set[UUID] = set()
self._propagation_context_manager: Optional[_AgnosticContextManager] = None
self._trace_context = trace_context
self._child_to_parent_run_id_map: Dict[UUID, Optional[UUID]] = {}
self.last_trace_id: Optional[str] = None
def on_llm_new_token(
self,
token: str,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
**kwargs: Any,
) -> Any:
"""Run on new LLM token. Only available when streaming is enabled."""
langfuse_logger.debug(
f"on llm new token: run_id: {run_id} parent_run_id: {parent_run_id}"
)
if (
run_id in self._runs
and isinstance(self._runs[run_id], LangfuseGeneration)
and run_id not in self._updated_completion_start_time_memo
):
current_generation = cast(LangfuseGeneration, self._runs[run_id])
current_generation.update(completion_start_time=_get_timestamp())
self._updated_completion_start_time_memo.add(run_id)
def _get_observation_type_from_serialized(
self, serialized: Optional[Dict[str, Any]], callback_type: str, **kwargs: Any
) -> Union[
Literal["tool"],
Literal["retriever"],
Literal["generation"],
Literal["agent"],
Literal["chain"],
Literal["span"],
]:
"""Determine Langfuse observation type from LangChain component.
Args:
serialized: LangChain's serialized component dict
callback_type: The type of callback (e.g., "chain", "tool", "retriever", "llm")
**kwargs: Additional keyword arguments from the callback
Returns:
The appropriate Langfuse observation type string
"""
# Direct mappings based on callback type
if callback_type == "tool":
return "tool"
elif callback_type == "retriever":
return "retriever"
elif callback_type == "llm":
return "generation"
elif callback_type == "chain":
# Detect if it's an agent by examining class path or name
if serialized and "id" in serialized:
class_path = serialized["id"]
if any("agent" in part.lower() for part in class_path):
return "agent"
# Check name for agent-related keywords
name = self.get_langchain_run_name(serialized, **kwargs)
if "agent" in name.lower():
return "agent"
return "chain"
return "span"
def get_langchain_run_name(
self, serialized: Optional[Dict[str, Any]], **kwargs: Any
) -> str:
"""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 (Optional[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 name of the Langchain runnable.
"""
if "name" in kwargs and kwargs["name"] is not None:
return str(kwargs["name"])
if serialized is None:
return "<unknown>"
try:
return str(serialized["name"])
except (KeyError, TypeError):
pass
try:
return str(serialized["id"][-1])
except (KeyError, TypeError):
pass
return "<unknown>"
def on_retriever_error(
self,
error: BaseException,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
**kwargs: Any,
) -> Any:
"""Run when Retriever errors."""
try:
self._log_debug_event(
"on_retriever_error", run_id, parent_run_id, error=error
)
observation = self._detach_observation(run_id)
if observation is not None:
observation.update(
level="ERROR",
status_message=str(error),
input=kwargs.get("inputs"),
cost_details={"total": 0},
).end()
except Exception as e:
langfuse_logger.exception(e)
def _parse_langfuse_trace_attributes(
self, *, metadata: Optional[Dict[str, Any]], tags: Optional[List[str]]
) -> Dict[str, Any]:
attributes: Dict[str, Any] = {}
if metadata is None and tags is not None:
return {"tags": tags}
if metadata is None:
return attributes
if "langfuse_session_id" in metadata and isinstance(
metadata["langfuse_session_id"], str
):
attributes["session_id"] = metadata["langfuse_session_id"]
if "langfuse_user_id" in metadata and isinstance(
metadata["langfuse_user_id"], str
):
attributes["user_id"] = metadata["langfuse_user_id"]
if tags is not None or (
"langfuse_tags" in metadata and isinstance(metadata["langfuse_tags"], list)
):
langfuse_tags = (
metadata["langfuse_tags"]
if "langfuse_tags" in metadata
and isinstance(metadata["langfuse_tags"], list)
else []
)
merged_tags = list(set(langfuse_tags) | set(tags or []))
attributes["tags"] = [str(tag) for tag in set(merged_tags)]
attributes["metadata"] = _strip_langfuse_keys_from_dict(metadata, False)
return attributes
def on_chain_start(
self,
serialized: Optional[Dict[str, Any]],
inputs: Dict[str, Any],
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Any:
self._child_to_parent_run_id_map[run_id] = parent_run_id
try:
self._log_debug_event(
"on_chain_start", run_id, parent_run_id, inputs=inputs
)
self._register_langfuse_prompt(
run_id=run_id, parent_run_id=parent_run_id, metadata=metadata
)
span_name = self.get_langchain_run_name(serialized, **kwargs)
span_metadata = self.__join_tags_and_metadata(tags, metadata)
span_level = "DEBUG" if tags and LANGSMITH_TAG_HIDDEN in tags else None
observation_type = self._get_observation_type_from_serialized(
serialized, "chain", **kwargs
)
# Handle trace attribute propagation at the root of the chain
if parent_run_id is None:
parsed_trace_attributes = self._parse_langfuse_trace_attributes(
metadata=metadata, tags=tags
)
self._propagation_context_manager = propagate_attributes(
user_id=parsed_trace_attributes.get("user_id", None),
session_id=parsed_trace_attributes.get("session_id", None),
tags=parsed_trace_attributes.get("tags", None),
metadata=parsed_trace_attributes.get("metadata", None),
)
self._propagation_context_manager.__enter__()
obs = self._get_parent_observation(parent_run_id)
if isinstance(obs, Langfuse):
span = obs.start_observation(
trace_context=self._trace_context,
name=span_name,
as_type=observation_type,
metadata=span_metadata,
input=inputs,
level=cast(
Literal["DEBUG", "DEFAULT", "WARNING", "ERROR"] | None,
span_level,
),
)
else:
span = obs.start_observation(
name=span_name,
as_type=observation_type,
metadata=span_metadata,
input=inputs,
level=cast(
Literal["DEBUG", "DEFAULT", "WARNING", "ERROR"] | None,
span_level,
),
)
self._attach_observation(run_id, span)
self.last_trace_id = self._runs[run_id].trace_id
except Exception as e:
langfuse_logger.exception(e)
def _register_langfuse_prompt(
self,
*,
run_id: UUID,
parent_run_id: Optional[UUID],
metadata: Optional[Dict[str, Any]],
) -> None:
"""We need to register any passed Langfuse prompt to the parent_run_id so that we can link following generations with that prompt.
If parent_run_id is None, we are at the root of a trace and should not attempt to register the prompt, as there will be no LLM invocation following it.
Otherwise it would have been traced in with a parent run consisting of the prompt template formatting and the LLM invocation.
"""
if not parent_run_id or not run_id:
return
langfuse_prompt = metadata and metadata.get("langfuse_prompt", None)
if langfuse_prompt:
self._prompt_to_parent_run_map[parent_run_id] = langfuse_prompt
# If we have a registered prompt that has not been linked to a generation yet, we need to allow _children_ of that chain to link to it.
# Otherwise, we only allow generations on the same level of the prompt rendering to be linked, not if they are nested.
elif parent_run_id in self._prompt_to_parent_run_map:
registered_prompt = self._prompt_to_parent_run_map[parent_run_id]
self._prompt_to_parent_run_map[run_id] = registered_prompt
def _deregister_langfuse_prompt(self, run_id: Optional[UUID]) -> None:
if run_id is not None and run_id in self._prompt_to_parent_run_map:
del self._prompt_to_parent_run_map[run_id]
def _get_parent_observation(
self, parent_run_id: Optional[UUID]
) -> Union[
Langfuse,
LangfuseAgent,
LangfuseChain,
LangfuseGeneration,
LangfuseRetriever,
LangfuseSpan,
LangfuseTool,
]:
if parent_run_id and parent_run_id in self._runs:
return self._runs[parent_run_id]
return self._langfuse_client
def _attach_observation(
self,
run_id: UUID,
observation: Union[
LangfuseAgent,
LangfuseChain,
LangfuseGeneration,
LangfuseRetriever,
LangfuseSpan,
LangfuseTool,
],
) -> None:
ctx = trace.set_span_in_context(observation._otel_span)
token = context.attach(ctx)
self._runs[run_id] = observation
self._context_tokens[run_id] = token
def _detach_observation(
self, run_id: UUID
) -> Optional[
Union[
LangfuseAgent,
LangfuseChain,
LangfuseGeneration,
LangfuseRetriever,
LangfuseSpan,
LangfuseTool,
]
]:
token = self._context_tokens.pop(run_id, None)
if token:
try:
# Directly detach from runtime context to avoid error logging
_RUNTIME_CONTEXT.detach(token)
except Exception:
# Context detach can fail in async scenarios - this is expected and safe to ignore
# The span itself was properly ended and tracing data is correctly captured
#
# Examples:
# 1. Token created in one async task/thread, detached in another
# 2. Context already detached by framework or other handlers
# 3. Runtime context state mismatch in concurrent execution
pass
return cast(
Union[
LangfuseAgent,
LangfuseChain,
LangfuseGeneration,
LangfuseRetriever,
LangfuseSpan,
LangfuseTool,
],
self._runs.pop(run_id, None),
)
def on_agent_action(
self,
action: AgentAction,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
**kwargs: Any,
) -> Any:
"""Run on agent action."""
self._child_to_parent_run_id_map[run_id] = parent_run_id
try:
self._log_debug_event(
"on_agent_action", run_id, parent_run_id, action=action
)
agent_run = self._runs.get(run_id, None)
if agent_run is not None:
agent_run._otel_span.set_attribute(
LangfuseOtelSpanAttributes.OBSERVATION_TYPE, "agent"
)
agent_run.update(
output=action,
input=kwargs.get("inputs"),
)
except Exception as e:
langfuse_logger.exception(e)
def on_agent_finish(
self,
finish: AgentFinish,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
**kwargs: Any,
) -> Any:
try:
self._log_debug_event(
"on_agent_finish", run_id, parent_run_id, finish=finish
)
# Langchain is sending same run ID for both agent finish and chain end
# handle cleanup of observation in the chain end callback
agent_run = self._runs.get(run_id, None)
if agent_run is not None:
agent_run._otel_span.set_attribute(
LangfuseOtelSpanAttributes.OBSERVATION_TYPE, "agent"
)
agent_run.update(
output=finish,
input=kwargs.get("inputs"),
)
except Exception as e:
langfuse_logger.exception(e)
def on_chain_end(
self,
outputs: Dict[str, Any],
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
**kwargs: Any,
) -> Any:
try:
self._log_debug_event(
"on_chain_end", run_id, parent_run_id, outputs=outputs
)
span = self._detach_observation(run_id)
if span is not None:
span.update(
output=outputs,
input=kwargs.get("inputs"),
)
if (
parent_run_id is None
and self._propagation_context_manager is not None
):
self._propagation_context_manager.__exit__(None, None, None)
span.end()
self._deregister_langfuse_prompt(run_id)
except Exception as e:
langfuse_logger.exception(e)
finally:
if parent_run_id is None:
self._reset()
def on_chain_error(
self,
error: BaseException,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
**kwargs: Any,
) -> None:
try:
self._log_debug_event("on_chain_error", run_id, parent_run_id, error=error)
if any(isinstance(error, t) for t in CONTROL_FLOW_EXCEPTION_TYPES):
level = None
else:
level = "ERROR"
observation = self._detach_observation(run_id)
if observation is not None:
observation.update(
level=cast(
Optional[Literal["DEBUG", "DEFAULT", "WARNING", "ERROR"]],
level,
),
status_message=str(error) if level else None,
input=kwargs.get("inputs"),
cost_details={"total": 0},
).end()
except Exception as e:
langfuse_logger.exception(e)
def on_chat_model_start(
self,
serialized: Optional[Dict[str, Any]],
messages: List[List[BaseMessage]],
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Any:
self._child_to_parent_run_id_map[run_id] = parent_run_id
try:
self._log_debug_event(
"on_chat_model_start", run_id, parent_run_id, messages=messages
)
self.__on_llm_action(
serialized,
run_id,
cast(
List,
_flatten_comprehension(
[self._create_message_dicts(m) for m in messages]
),
),
parent_run_id,
tags=tags,
metadata=metadata,
**kwargs,
)
except Exception as e:
langfuse_logger.exception(e)
def on_llm_start(
self,
serialized: Optional[Dict[str, Any]],
prompts: List[str],
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Any:
self._child_to_parent_run_id_map[run_id] = parent_run_id
try:
self._log_debug_event(
"on_llm_start", run_id, parent_run_id, prompts=prompts
)
self.__on_llm_action(
serialized,
run_id,
cast(List, prompts[0] if len(prompts) == 1 else prompts),
parent_run_id,
tags=tags,
metadata=metadata,
**kwargs,
)
except Exception as e:
langfuse_logger.exception(e)
def on_tool_start(
self,
serialized: Optional[Dict[str, Any]],
input_str: str,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Any:
self._child_to_parent_run_id_map[run_id] = parent_run_id
try:
self._log_debug_event(
"on_tool_start", run_id, parent_run_id, input_str=input_str
)
meta = self.__join_tags_and_metadata(tags, metadata)
if not meta:
meta = {}
meta.update(
{key: value for key, value in kwargs.items() if value is not None}
)
observation_type = self._get_observation_type_from_serialized(
serialized, "tool", **kwargs
)
span = self._get_parent_observation(parent_run_id).start_observation(
name=self.get_langchain_run_name(serialized, **kwargs),
as_type=observation_type,
input=input_str,
metadata=meta,
level="DEBUG" if tags and LANGSMITH_TAG_HIDDEN in tags else None,
)
self._attach_observation(run_id, span)
except Exception as e:
langfuse_logger.exception(e)
def on_retriever_start(
self,
serialized: Optional[Dict[str, Any]],
query: str,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Any:
self._child_to_parent_run_id_map[run_id] = parent_run_id
try:
self._log_debug_event(
"on_retriever_start", run_id, parent_run_id, query=query
)
span_name = self.get_langchain_run_name(serialized, **kwargs)
span_metadata = self.__join_tags_and_metadata(tags, metadata)
span_level = "DEBUG" if tags and LANGSMITH_TAG_HIDDEN in tags else None
observation_type = self._get_observation_type_from_serialized(
serialized, "retriever", **kwargs
)
span = self._get_parent_observation(parent_run_id).start_observation(
name=span_name,
as_type=observation_type,
metadata=span_metadata,
input=query,
level=cast(
Optional[Literal["DEBUG", "DEFAULT", "WARNING", "ERROR"]],
span_level,
),
)
self._attach_observation(run_id, span)
except Exception as e:
langfuse_logger.exception(e)
def on_retriever_end(
self,
documents: Sequence[Document],
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
**kwargs: Any,
) -> Any:
try:
self._log_debug_event(
"on_retriever_end", run_id, parent_run_id, documents=documents
)
observation = self._detach_observation(run_id)
if observation is not None:
observation.update(
output=documents,
input=kwargs.get("inputs"),
).end()
except Exception as e:
langfuse_logger.exception(e)
def on_tool_end(
self,
output: str,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
**kwargs: Any,
) -> Any:
try:
self._log_debug_event("on_tool_end", run_id, parent_run_id, output=output)
observation = self._detach_observation(run_id)
if observation is not None:
observation.update(
output=output,
input=kwargs.get("inputs"),
).end()
except Exception as e:
langfuse_logger.exception(e)
def on_tool_error(
self,
error: BaseException,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
**kwargs: Any,
) -> Any:
try:
self._log_debug_event("on_tool_error", run_id, parent_run_id, error=error)
observation = self._detach_observation(run_id)
if observation is not None:
observation.update(
status_message=str(error),
level="ERROR",
input=kwargs.get("inputs"),
cost_details={"total": 0},
).end()
except Exception as e:
langfuse_logger.exception(e)
def __on_llm_action(
self,
serialized: Optional[Dict[str, Any]],
run_id: UUID,
prompts: List[Any],
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> None:
self._child_to_parent_run_id_map[run_id] = parent_run_id
try:
tools = kwargs.get("invocation_params", {}).get("tools", None)
if tools and isinstance(tools, list):
prompts.extend([{"role": "tool", "content": tool} for tool in tools])
model_name = self._parse_model_and_log_errors(
serialized=serialized, metadata=metadata, kwargs=kwargs
)
registered_prompt = None
current_parent_run_id = parent_run_id
# Check all parents for registered prompt
while current_parent_run_id is not None:
registered_prompt = self._prompt_to_parent_run_map.get(
current_parent_run_id
)
if registered_prompt:
self._deregister_langfuse_prompt(current_parent_run_id)
break
else:
current_parent_run_id = self._child_to_parent_run_id_map.get(
current_parent_run_id, None
)
content = {
"name": self.get_langchain_run_name(serialized, **kwargs),
"input": prompts,
"metadata": self.__join_tags_and_metadata(
tags,
metadata,
# If llm is run isolated and outside chain, keep trace attributes
keep_langfuse_trace_attributes=True
if parent_run_id is None
else False,
),
"model": model_name,
"model_parameters": self._parse_model_parameters(kwargs),
"prompt": registered_prompt,
}
generation = self._get_parent_observation(parent_run_id).start_observation(
as_type="generation", **content
) # type: ignore
self._attach_observation(run_id, generation)
self.last_trace_id = self._runs[run_id].trace_id
except Exception as e:
langfuse_logger.exception(e)
@staticmethod
def _parse_model_parameters(kwargs: Dict[str, Any]) -> Dict[str, Any]:
"""Parse the model parameters from the kwargs."""
if kwargs["invocation_params"].get("_type") == "IBM watsonx.ai" and kwargs[
"invocation_params"
].get("params"):
kwargs["invocation_params"] = {
**kwargs["invocation_params"],
**kwargs["invocation_params"]["params"],
}
del kwargs["invocation_params"]["params"]
return {
key: value
for key, value in {
"temperature": kwargs["invocation_params"].get("temperature"),
"max_tokens": kwargs["invocation_params"].get("max_tokens"),
"max_completion_tokens": kwargs["invocation_params"].get(
"max_completion_tokens"
),
"top_p": kwargs["invocation_params"].get("top_p"),
"frequency_penalty": kwargs["invocation_params"].get(
"frequency_penalty"
),
"presence_penalty": kwargs["invocation_params"].get("presence_penalty"),
"request_timeout": kwargs["invocation_params"].get("request_timeout"),
"decoding_method": kwargs["invocation_params"].get("decoding_method"),
"min_new_tokens": kwargs["invocation_params"].get("min_new_tokens"),
"max_new_tokens": kwargs["invocation_params"].get("max_new_tokens"),
"stop_sequences": kwargs["invocation_params"].get("stop_sequences"),
}.items()
if value is not None
}
def _parse_model_and_log_errors(
self,
*,
serialized: Optional[Dict[str, Any]],
metadata: Optional[Dict[str, Any]],
kwargs: Dict[str, Any],
) -> Optional[str]:
"""Parse the model name and log errors if parsing fails."""
try:
model_name = _parse_model_name_from_metadata(
metadata
) or _extract_model_name(serialized, **kwargs)
if model_name:
return model_name
except Exception as e:
langfuse_logger.exception(e)
self._log_model_parse_warning()
return None
def _log_model_parse_warning(self) -> None:
if not hasattr(self, "_model_parse_warning_logged"):
langfuse_logger.warning(
"Langfuse was not able to parse the LLM model. The LLM call will be recorded without model name. Please create an issue: https://github.com/langfuse/langfuse/issues/new/choose"
)
self._model_parse_warning_logged = True
def on_llm_end(
self,
response: LLMResult,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
**kwargs: Any,
) -> Any:
try:
self._log_debug_event(
"on_llm_end", run_id, parent_run_id, response=response, kwargs=kwargs
)
response_generation = response.generations[-1][-1]
extracted_response = (
self._convert_message_to_dict(response_generation.message)
if isinstance(response_generation, ChatGeneration)
else _extract_raw_response(response_generation)
)
llm_usage = _parse_usage(response)
# e.g. azure returns the model name in the response
model = _parse_model(response)
generation = self._detach_observation(run_id)
if generation is not None:
generation.update(
output=extracted_response,
usage=llm_usage,
usage_details=llm_usage,
input=kwargs.get("inputs"),
model=model,
).end()
except Exception as e:
langfuse_logger.exception(e)
finally:
self._updated_completion_start_time_memo.discard(run_id)
if parent_run_id is None:
self._reset()