|
56 | 56 |
|
57 | 57 |
|
58 | 58 | class LangchainCallbackHandler(LangchainBaseCallbackHandler): |
59 | | - def __init__(self, *, public_key: Optional[str] = None) -> None: |
| 59 | + def __init__( |
| 60 | + self, *, public_key: Optional[str] = None, update_trace: Optional[bool] = False |
| 61 | + ) -> None: |
60 | 62 | self.client = get_client(public_key=public_key) |
61 | 63 |
|
62 | 64 | self.runs: Dict[UUID, Union[LangfuseSpan, LangfuseGeneration]] = {} |
63 | 65 | self.prompt_to_parent_run_map: Dict[UUID, Any] = {} |
64 | 66 | self.updated_completion_start_time_memo: Set[UUID] = set() |
65 | 67 |
|
66 | 68 | self.last_trace_id: Optional[str] = None |
| 69 | + self.update_trace = update_trace |
67 | 70 |
|
68 | 71 | def on_llm_new_token( |
69 | 72 | self, |
@@ -207,7 +210,19 @@ def on_chain_start( |
207 | 210 | ), |
208 | 211 | ) |
209 | 212 | span.update_trace( |
210 | | - **self._parse_langfuse_trace_attributes_from_metadata(metadata) |
| 213 | + **( |
| 214 | + cast( |
| 215 | + Any, |
| 216 | + { |
| 217 | + "input": inputs, |
| 218 | + "name": span_name, |
| 219 | + "metadata": span_metadata, |
| 220 | + }, |
| 221 | + ) |
| 222 | + if self.update_trace |
| 223 | + else {} |
| 224 | + ), |
| 225 | + **self._parse_langfuse_trace_attributes_from_metadata(metadata), |
211 | 226 | ) |
212 | 227 | self.runs[run_id] = span |
213 | 228 | else: |
@@ -322,14 +337,21 @@ def on_chain_end( |
322 | 337 | if run_id not in self.runs: |
323 | 338 | raise Exception("run not found") |
324 | 339 |
|
325 | | - self.runs[run_id].update( |
| 340 | + span = self.runs[run_id] |
| 341 | + span.update( |
326 | 342 | output=outputs, |
327 | 343 | input=kwargs.get("inputs"), |
328 | | - ).end() |
| 344 | + ) |
| 345 | + |
| 346 | + if parent_run_id is None and self.update_trace: |
| 347 | + span.update_trace(output=outputs, input=kwargs.get("inputs")) |
| 348 | + |
| 349 | + span.end() |
329 | 350 |
|
330 | 351 | del self.runs[run_id] |
331 | 352 |
|
332 | 353 | self._deregister_langfuse_prompt(run_id) |
| 354 | + |
333 | 355 | except Exception as e: |
334 | 356 | langfuse_logger.exception(e) |
335 | 357 |
|
|
0 commit comments