The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(memory,langfuse): unify recall/reflect calls, client close, hook client+key resolution; dict-comprehension metadata builders
Teknium4c3e5cf2d9d9
diff --git a/plugins/memory/__init__.py b/plugins/memory/__init__.pyindex 6496b77cf2c..e2f24520689 100644--- a/plugins/memory/__init__.py+++ b/plugins/memory/__init__.py@@ -70,13 +70,16 @@ def _module_name(provider_dir: Path, name: str) -> str:return f"plugins.memory.{name}" if _is_bundled(provider_dir) else f"{_USER_NAMESPACE}.{name}"+def _external_source_dirs() -> List[Path]:+ """User then project plugin roots that exist (precedence order)."""+ return [d for d in (_get_user_plugins_dir(), _get_project_plugins_dir()) if d]++def _iter_provider_dirs() -> List[Tuple[str, Path]]:"""``(name, path)`` for bundled, then user-installed, then project-local; first-seen wins."""dirs = [(child.name, child) for child in _loader.iter_plugin_dirs(_MEMORY_PLUGINS_DIR)]seen = {name for name, _ in dirs}- for source_dir in (_get_user_plugins_dir(), _get_project_plugins_dir()):- if not source_dir:- continue+ for source_dir in _external_source_dirs():for child in sorted(source_dir.iterdir()):if (child.is_dir()@@ -111,9 +114,7 @@ def find_provider_dir(name: str) -> Optional[Path]:bundled = _MEMORY_PLUGINS_DIR / nameif bundled.is_dir() and (bundled / "__init__.py").exists():return bundled- for source_dir in (_get_user_plugins_dir(), _get_project_plugins_dir()):- if not source_dir:- continue+ for source_dir in _external_source_dirs():candidate = source_dir / nameif candidate.is_dir() and _is_memory_provider_dir(candidate):return candidate@@ -196,9 +197,7 @@ def load_memory_provider(return _load_provider_from_dir(provider_dir, register_skills=register_skills)return _load_provider_from_entry_point(entry_point, register_skills=register_skills)- return _loader.load_named(- name, provider_dir, _load, kind="Memory provider", noun="provider", logger=logger,- )+ return _loader.load_named(name, provider_dir, _load, kind="Memory provider", noun="provider", logger=logger)def _instantiate_subclass(namespace) -> Optional["MemoryProvider"]:@@ -207,8 +206,7 @@ def _instantiate_subclass(namespace) -> Optional["MemoryProvider"]:for attr_name in dir(namespace):attr = getattr(namespace, attr_name, None)- if (isinstance(attr, type) and issubclass(attr, MemoryProvider)- and attr is not MemoryProvider):+ if isinstance(attr, type) and issubclass(attr, MemoryProvider) and attr is not MemoryProvider:try:return attr()except Exception:diff --git a/plugins/memory/hindsight/__init__.py b/plugins/memory/hindsight/__init__.pyindex 2658bd95868..31ca608e3a3 100644--- a/plugins/memory/hindsight/__init__.py+++ b/plugins/memory/hindsight/__init__.py@@ -90,12 +90,11 @@ def _maybe_upgrade_client() -> None:outcome = install_specs([f"hindsight-client>={_MIN_CLIENT_VERSION}"], timeout=120)if outcome.ok:logger.info("hindsight-client upgraded to >=%s", _MIN_CLIENT_VERSION)- elif outcome.blocked:- logger.warning("Auto-upgrade unavailable: %s. Run: uv pip install 'hindsight-client>=%s'",- outcome.reason, _MIN_CLIENT_VERSION)else:- logger.warning("Auto-upgrade failed: %s. Run: uv pip install 'hindsight-client>=%s'",- (outcome.stderr or "").strip() or "install error", _MIN_CLIENT_VERSION)+ what, why = (("unavailable", outcome.reason) if outcome.blocked+ else ("failed", (outcome.stderr or "").strip() or "install error"))+ logger.warning("Auto-upgrade %s: %s. Run: uv pip install 'hindsight-client>=%s'",+ what, why, _MIN_CLIENT_VERSION)except Exception:pass # packaging not available or other issue — proceed anyway@@ -431,9 +430,9 @@ class HindsightMemoryProvider(MemoryProvider):mode = cfg.get("mode", "cloud")if mode in _LOCAL_MODES:return _check_local_runtime()[0]- if mode == "local_external":- return True- return bool(_cloud_api_key(cfg)) or bool(cfg.get("api_url") or os.environ.get("HINDSIGHT_API_URL", ""))+ return mode == "local_external" or bool(+ _cloud_api_key(cfg) or cfg.get("api_url") or os.environ.get("HINDSIGHT_API_URL", "")+ )except Exception:return False@@ -533,18 +532,18 @@ class HindsightMemoryProvider(MemoryProvider):llm_provider = _daemon_llm_provider(cfg.get("llm_provider", ""))logger.debug("Creating HindsightEmbedded client (profile=%s, provider=%s)",cfg.get("profile", "hermes"), llm_provider)+ self._idle_timeout = self._int_setting(+ "idle_timeout", "HINDSIGHT_IDLE_TIMEOUT", _DEFAULT_IDLE_TIMEOUT, env_default=self._idle_timeout,+ )kwargs = dict(profile=cfg.get("profile", "hermes"),llm_provider=llm_provider,llm_api_key=cfg.get("llmApiKey") or cfg.get("llm_api_key") or get_secret("HINDSIGHT_LLM_API_KEY", ""),llm_model=cfg.get("llm_model", ""),+ idle_timeout=self._idle_timeout,)if self._llm_base_url:kwargs["llm_base_url"] = self._llm_base_url- self._idle_timeout = self._int_setting(- "idle_timeout", "HINDSIGHT_IDLE_TIMEOUT", _DEFAULT_IDLE_TIMEOUT, env_default=self._idle_timeout,- )- kwargs["idle_timeout"] = self._idle_timeoutreturn HindsightEmbedded(**kwargs)def _new_cloud_client(self):@@ -638,11 +637,8 @@ class HindsightMemoryProvider(MemoryProvider):"""Record the async ``operation_id``/``operation_ids`` of an aretain_batch reply(pending until recall-visible). No id (older API / sync completion) leavesonly the local queue drain as a signal."""- ids: list[str] = []- single = getattr(retain_response, "operation_id", None)- if single:- ids.append(str(single))- ids.extend(str(op) for op in (getattr(retain_response, "operation_ids", None) or []) if op)+ raw_ids = [getattr(retain_response, "operation_id", None), *(getattr(retain_response, "operation_ids", None) or [])]+ ids = [str(op) for op in raw_ids if op]if not ids:returnself._retain_ops_bank_id = bank_id@@ -757,9 +753,8 @@ class HindsightMemoryProvider(MemoryProvider):self._config = cfg = _load_config()for name in _SESSION_KWARGS:setattr(self, f"_{name}", str(kwargs.get(name) or "").strip())- self._turn_index = 0+ self._turn_index = self._last_retained_turn_count = 0self._session_turns = []- self._last_retained_turn_count = 0self._mode = cfg.get("mode", "cloud")self._timeout = self._int_setting("timeout", "HINDSIGHT_TIMEOUT", _DEFAULT_TIMEOUT)self._idle_timeout = self._int_setting("idle_timeout", "HINDSIGHT_IDLE_TIMEOUT", _DEFAULT_IDLE_TIMEOUT)@@ -925,11 +920,7 @@ class HindsightMemoryProvider(MemoryProvider):def system_prompt_block(self) -> str:mode = self._memory_mode if self._memory_mode in ("context", "tools") else "hybrid"label = "" if mode == "hybrid" else f" ({mode} mode)"- return (- f"# Hindsight Memory\n"- f"Active{label}. Bank: {self._bank_id}, budget: {self._budget}.\n"- f"{_SYSTEM_PROMPT_TAILS[mode]}"- )+ return f"# Hindsight Memory\nActive{label}. Bank: {self._bank_id}, budget: {self._budget}.\n{_SYSTEM_PROMPT_TAILS[mode]}"# -- recall ------------------------------------------------------------------@@ -946,17 +937,24 @@ class HindsightMemoryProvider(MemoryProvider):return Falsedef _recall_kwargs(self, query: str) -> dict:- kwargs: dict = {- "bank_id": self._bank_id, "query": query,- "budget": self._budget, "max_tokens": self._recall_max_tokens,- }+ kwargs: dict = {"bank_id": self._bank_id, "query": query, "budget": self._budget, "max_tokens": self._recall_max_tokens}if self._recall_tags:- kwargs["tags"] = self._recall_tags- kwargs["tags_match"] = self._recall_tags_match+ kwargs.update(tags=self._recall_tags, tags_match=self._recall_tags_match)if self._recall_types:kwargs["types"] = self._recall_typesreturn kwargs+ def _recall(self, query: str) -> list:+ recall_kwargs = self._recall_kwargs(query)+ resp = self._run_hindsight_operation(lambda client: client.arecall(**recall_kwargs))+ return resp.results or []++ def _reflect(self, query: str) -> str | None:+ resp = self._run_hindsight_operation(+ lambda client: client.areflect(bank_id=self._bank_id, query=query, budget=self._budget)+ )+ return resp.text+def _do_recall(self, query: str) -> _RecallResult:"""One recall/reflect for *query* (background prefetch and ``recall_sync`` paths)."""if self._recall_max_input_chars and len(query) > self._recall_max_input_chars:@@ -964,13 +962,10 @@ class HindsightMemoryProvider(MemoryProvider):try:if self._prefetch_method == "reflect":logger.debug("Recall: calling reflect (bank=%s, query_len=%d)", self._bank_id, len(query))- resp = self._run_hindsight_operation(lambda client: client.areflect(bank_id=self._bank_id, query=query, budget=self._budget))- return _RecallResult(resp.text or "", 0) # synthesis -> no discrete count- recall_kwargs = self._recall_kwargs(query)+ return _RecallResult(self._reflect(query) or "", 0) # synthesis -> no discrete countlogger.debug("Recall: calling recall (bank=%s, query_len=%d, budget=%s)",self._bank_id, len(query), self._budget)- resp = self._run_hindsight_operation(lambda client: client.arecall(**recall_kwargs))- results = resp.results or []+ results = self._recall(query)logger.debug("Recall: returned %d results", len(results))return _RecallResult("\n".join(f"- {r.text}" for r in results if r.text), len(results))except Exception as e:@@ -1030,8 +1025,7 @@ class HindsightMemoryProvider(MemoryProvider):recalled = self._do_recall(query)if recalled.text:with self._prefetch_lock:- self._prefetch_result = recalled.text- self._prefetch_count = recalled.count+ self._prefetch_result, self._prefetch_count = recalled.text, recalled.countself._prefetch_thread = _context_thread(_run, "hindsight-prefetch")self._prefetch_thread.start()@@ -1041,10 +1035,8 @@ class HindsightMemoryProvider(MemoryProvider):def _build_turn_messages(self, user_content: str, assistant_content: str) -> List[Dict[str, str]]:# One conversation turn -> both messages share the turn-level event timestamp.now = _event_timestamp()- return [- {"role": "user", "content": f"{self._retain_user_prefix}: {user_content}", "timestamp": now},- {"role": "assistant", "content": f"{self._retain_assistant_prefix}: {assistant_content}", "timestamp": now},- ]+ return [{"role": role, "content": f"{prefix}: {content}", "timestamp": now} for role, prefix, content in+ (("user", self._retain_user_prefix, user_content), ("assistant", self._retain_assistant_prefix, assistant_content))]def _build_metadata(self, *, message_count: int, turn_index: int) -> Dict[str, str]:metadata: Dict[str, str] = {@@ -1054,10 +1046,7 @@ class HindsightMemoryProvider(MemoryProvider):}if self._retain_source:metadata["source"] = self._retain_source- for name in _METADATA_ATTRS:- value = getattr(self, f"_{name}")- if value:- metadata[name] = value+ metadata.update({name: value for name in _METADATA_ATTRS if (value := getattr(self, f"_{name}"))})return metadatadef _build_retain_kwargs(@@ -1200,11 +1189,9 @@ class HindsightMemoryProvider(MemoryProvider):def _tool_recall(self, args: dict) -> str:query = args["query"]- recall_kwargs = self._recall_kwargs(query)logger.debug("Tool hindsight_recall: bank=%s, query_len=%d, budget=%s",self._bank_id, len(query), self._budget)- resp = self._run_hindsight_operation(lambda client: client.arecall(**recall_kwargs))- results = resp.results or []+ results = self._recall(query)logger.debug("Tool hindsight_recall: %d results", len(results))if not results:return "No relevant memories found."@@ -1214,11 +1201,9 @@ class HindsightMemoryProvider(MemoryProvider):query = args["query"]logger.debug("Tool hindsight_reflect: bank=%s, query_len=%d, budget=%s",self._bank_id, len(query), self._budget)- resp = self._run_hindsight_operation(- lambda client: client.areflect(bank_id=self._bank_id, query=query, budget=self._budget)- )- logger.debug("Tool hindsight_reflect: response_len=%d", len(resp.text or ""))- return resp.text or "No relevant memories found."+ text = self._reflect(query) or ""+ logger.debug("Tool hindsight_reflect: response_len=%d", len(text))+ return text or "No relevant memories found."# tool name -> (required arg, handler)_TOOL_HANDLERS = {@@ -1274,7 +1259,6 @@ class HindsightMemoryProvider(MemoryProvider):job()except Exception as e:logger.warning("Hindsight flush-on-switch failed: %s", e, exc_info=True)-# Same writer queue as sync_turn: FIFO behind queued old-session retains,# no two threads racing aretain_batch on one document, shutdown drain intact.if not self._shutting_down.is_set():@@ -1291,14 +1275,31 @@ class HindsightMemoryProvider(MemoryProvider):self._session_id = new_idself._document_id = _mint_document_id(new_id)self._session_turns = []- self._turn_counter = 0- self._turn_index = 0- self._last_retained_turn_count = 0+ self._turn_counter = self._turn_index = self._last_retained_turn_count = 0logger.debug("Hindsight on_session_switch: new_session=%s parent=%s reset=%s doc=%s",self._session_id, self._parent_session_id, reset, self._document_id,)+ def _close_client(self) -> None:+ if self._mode != "local_embedded":+ self._run_sync(self._client.aclose())+ return+ # HindsightEmbedded.close() closes its sync client from this thread ("attached+ # to a different loop" before aiohttp releases the session): aclose the inner+ # client on the shared loop first, then let the wrapper clean up bookkeeping.+ inner_client = getattr(self._client, "_client", None)+ if inner_client is not None and hasattr(inner_client, "aclose"):+ _run_sync(inner_client.aclose())+ try:+ self._client._client = None+ except Exception:+ pass+ try:+ self._client.close()+ except RuntimeError:+ pass+def shutdown(self) -> None:logger.debug("Hindsight shutdown: stopping writer + waiting for background threads")# Stop accepting retain jobs first so late sync_turn() calls are dropped.@@ -1318,23 +1319,7 @@ class HindsightMemoryProvider(MemoryProvider):self._join_prefetch(5.0)if self._client is not None:try:- if self._mode == "local_embedded":- # HindsightEmbedded.close() closes its sync client from this thread- # ("attached to a different loop" before aiohttp releases the- # session): aclose the inner client on the shared loop first.- inner_client = getattr(self._client, "_client", None)- if inner_client is not None and hasattr(inner_client, "aclose"):- _run_sync(inner_client.aclose())- try:- self._client._client = None- except Exception:- pass- try:- self._client.close()- except RuntimeError:- pass- else:- self._run_sync(self._client.aclose())+ self._close_client()except Exception:passself._client = Nonediff --git a/plugins/observability/langfuse/__init__.py b/plugins/observability/langfuse/__init__.pyindex c94505b919f..e17620369b8 100644--- a/plugins/observability/langfuse/__init__.py+++ b/plugins/observability/langfuse/__init__.py@@ -57,6 +57,8 @@ _LANGFUSE_CLIENT_LOCK = threading.Lock()_READ_FILE_LINE_RE = re.compile(r"^\s*(\d+)\|(.*)$")_READ_FILE_HEAD_LINES = 25_READ_FILE_TAIL_LINES = 15+_READ_FILE_META_KEYS = ("total_lines", "file_size", "truncated", "is_binary", "is_image", "hint",+ "_warning", "mime_type", "dimensions", "similar_files", "error")# Langfuse-issued keys always carry these prefixes. Anything else is a leftover# template value: the SDK accepts it at construction time but silently drops@@ -223,9 +225,8 @@ def _get_langfuse() -> Optional[Langfuse]:"secret_key": secret_key,"base_url": _env("HERMES_LANGFUSE_BASE_URL") or _env("LANGFUSE_BASE_URL") or "https://cloud.langfuse.com",}- for key, hermes_name, plain_name in (("environment", "HERMES_LANGFUSE_ENV", "LANGFUSE_ENV"),- ("release", "HERMES_LANGFUSE_RELEASE", "LANGFUSE_RELEASE")):- value = _env(hermes_name) or _env(plain_name)+ for key, name in (("environment", "ENV"), ("release", "RELEASE")):+ value = _env(f"HERMES_LANGFUSE_{name}") or _env(f"LANGFUSE_{name}")if value:kwargs[key] = valuesample_rate = _env("HERMES_LANGFUSE_SAMPLE_RATE")@@ -339,12 +340,9 @@ def _parse_read_file_lines(content: str) -> list[dict[str, Any]]:def _normalize_read_file_payload(value: dict[str, Any], *, args: Any = None) -> dict[str, Any]:normalized: dict[str, Any] = {}if isinstance(args, dict):- path = args.get("path")- if isinstance(path, str) and path:- normalized["path"] = path- for key in ("offset", "limit"):- if isinstance(args.get(key), int):- normalized[key] = args[key]+ if isinstance(args.get("path"), str) and args["path"]:+ normalized["path"] = args["path"]+ normalized.update({key: args[key] for key in ("offset", "limit") if isinstance(args.get(key), int)})lines = _parse_read_file_lines(value.get("content", ""))if lines:@@ -361,10 +359,7 @@ def _normalize_read_file_payload(value: dict[str, Any], *, args: Any = None) ->elif value.get("content"):normalized["content_preview"] = {"text": value.get("content", "")}- for key in ("total_lines", "file_size", "truncated", "is_binary", "is_image", "hint",- "_warning", "mime_type", "dimensions", "similar_files", "error"):- if key in value:- normalized[key] = value[key]+ normalized.update({key: value[key] for key in _READ_FILE_META_KEYS if key in value})base64_content = value.get("base64_content")if isinstance(base64_content, str) and base64_content:@@ -441,12 +436,8 @@ def _serialize_system_prompt(system_prompt: Any) -> Optional[dict[str, Any]]:for block in system_prompt:if isinstance(block, dict):# Anthropic: {"type": "text", "text": ...}; Bedrock Converse: {"text": ...}.- block_type = block.get("type")- if block_type == "text" or (block_type is None and "text" in block):- piece = block.get("text", "")- if isinstance(piece, str) and piece:- parts.append(piece)- elif isinstance(block, str) and block:+ block = block.get("text", "") if block.get("type") in ("text", None) and "text" in block else None+ if isinstance(block, str) and block:parts.append(block)text = "\n\n".join(parts)else:@@ -481,9 +472,9 @@ def _serialize_messages(messages: Any) -> list[dict[str, Any]]:item = {"role": role, "content": _capture_content(message.get("content"), parse_json_strings=(role == "tool"))}if role == "tool":if message.get("tool_call_id"):- item["tool_call_id"] = message.get("tool_call_id")+ item["tool_call_id"] = message["tool_call_id"]if message.get("name"):- item["name"] = _safe_value(message.get("name"))+ item["name"] = _safe_value(message["name"])if message.get("tool_calls"):item["tool_calls"] = _capture_content(message.get("tool_calls"), parse_json_strings=True)serialized.append(item)@@ -612,9 +603,7 @@ def _start_root_trace(task_key: str, *, task_id: str, session_id: str, platform:"capture_mode": _capture_mode(),}# session_id must be in trace_context for Langfuse session grouping.- trace_ctx: Dict[str, Any] = {"trace_id": trace_id}- if session_id:- trace_ctx["session_id"] = session_id+ trace_ctx: Dict[str, Any] = {"trace_id": trace_id, **({"session_id": session_id} if session_id else {})}def open_root():ctx = client.start_as_current_observation(@@ -658,12 +647,9 @@ def _end_observation(observation: Any, *, output: Any = None, metadata: Optionalif observation is None:returntry:- update_kwargs: Dict[str, Any] = {}- if output is not None:- update_kwargs["output"] = output- for key, val in (("metadata", metadata), ("usage_details", usage_details), ("cost_details", cost_details)):- if val:- update_kwargs[key] = val+ update_kwargs: Dict[str, Any] = {} if output is None else {"output": output}+ update_kwargs.update({k: v for k, v in (("metadata", metadata), ("usage_details", usage_details),+ ("cost_details", cost_details)) if v})if update_kwargs:observation.update(**update_kwargs)observation.end()@@ -791,6 +777,19 @@ def _request_key(api_call_count: Any) -> str:return str(api_call_count or 0)+def _client_and_key(task_id: str, session_id: str, turn_id: str, api_request_id: str) -> tuple[Any, str]:+ """(client, trace key) for a hook; client is None when tracing is unavailable."""+ client = _get_langfuse()+ if client is None:+ return None, ""+ return client, _trace_key(task_id, session_id, turn_id=turn_id, api_request_id=api_request_id)+++def _add_duration(metadata: Dict[str, Any], api_duration: Any) -> None:+ if api_duration and api_duration > 0:+ metadata["api_duration_s"] = round(api_duration, 3)++def _pop_generation(task_key: str, api_call_count: Any) -> tuple[Optional[TraceState], Any]:"""Detach the open generation for one API call. Returns (state, generation); either may be None."""with _STATE_LOCK:@@ -817,11 +816,9 @@ def on_pre_llm_call(*, task_id: str = "", session_id: str = "", platform: str =# turn-scoped pre_llm_call would otherwise open an orphan root trace.if not isinstance(messages, list):return- client = _get_langfuse()+ client, task_key = _client_and_key(task_id, session_id, turn_id, api_request_id)if client is None:return-- task_key = _trace_key(task_id, session_id, turn_id=turn_id, api_request_id=api_request_id)with _STATE_LOCK:_get_or_start_state_locked(task_key, task_id=task_id, session_id=session_id, platform=platform, provider=provider,@@ -850,19 +847,13 @@ def _emit_moa_reference_generations(state: TraceState, *, client: Langfuse, refeif not isinstance(ref, dict):continueusage = ref.get("usage") or {}- usage_details = {}- if isinstance(usage, dict):- for key, attr, _ in _USAGE_FIELDS:- if usage.get(attr):- usage_details[key] = usage[attr]+ usage_details = {key: usage[attr] for key, attr, _ in _USAGE_FIELDS if usage.get(attr)} if isinstance(usage, dict) else {}cost_usd = ref.get("cost_usd")cost_details = {"total": float(cost_usd)} if isinstance(cost_usd, (int, float)) else {}label = ref.get("label") or "advisor"metadata = {"moa_role": "reference", "label": label}- for key in ("provider", "cost_status", "cost_source", "temperature"):- if ref.get(key) is not None:- metadata[key] = ref[key]+ metadata.update({k: ref[k] for k in ("provider", "cost_status", "cost_source", "temperature") if ref.get(k) is not None})observation = _start_child_observation(state, client=client, name=f"MoA advisor: {label}", as_type="generation",@@ -880,7 +871,7 @@ def on_pre_llm_request(*, task_id: str = "", session_id: str = "", platform: strapprox_input_tokens: int = 0, conversation_history: Any = None,user_message: Any = None, turn_id: str = "", api_request_id: str = "",request: Any = None, system_prompt: Any = None, **_: Any) -> None:- client = _get_langfuse()+ client, task_key = _client_and_key(task_id, session_id, turn_id, api_request_id)if client is None:return@@ -897,8 +888,6 @@ def on_pre_llm_request(*, task_id: str = "", session_id: str = "", platform: strlangfuse_input = _messages_for_langfuse_input(system_prompt=system_prompt, pre_coerced=input_messages)has_system = bool(langfuse_input) and langfuse_input[0].get("role") == "system"system_chars = len(str(langfuse_input[0].get("content") or "")) if has_system else 0-- task_key = _trace_key(task_id, session_id, turn_id=turn_id, api_request_id=api_request_id)req_key = _request_key(api_call_count)with _STATE_LOCK:@@ -929,7 +918,7 @@ def on_post_llm_call(*, task_id: str = "", session_id: str = "", provider: str =assistant_content_chars: int = 0, assistant_tool_call_count: int = 0,assistant_response: Any = None, turn_id: str = "", api_request_id: str = "",response_model: Any = None, moa_references: Any = None, **_: Any) -> None:- client = _get_langfuse()+ client, task_key = _client_and_key(task_id, session_id, turn_id, api_request_id)if client is None:return@@ -937,7 +926,6 @@ def on_post_llm_call(*, task_id: str = "", session_id: str = "", provider: str =if isinstance(response_model, str) and response_model:model = response_model- task_key = _trace_key(task_id, session_id, turn_id=turn_id, api_request_id=api_request_id)state, generation = _pop_generation(task_key, api_call_count)if state is None or generation is None:return@@ -955,7 +943,7 @@ def on_post_llm_call(*, task_id: str = "", session_id: str = "", provider: str =output = {"content": f"[{assistant_content_chars} chars]" if assistant_content_chars else None,"reasoning": None,- "tool_calls": [{"id": f"tc_{i}"} for i in range(assistant_tool_call_count)] if assistant_tool_call_count else [],+ "tool_calls": [{"id": f"tc_{i}"} for i in range(assistant_tool_call_count or 0)],}if output.get("tool_calls"):@@ -975,8 +963,7 @@ def on_post_llm_call(*, task_id: str = "", session_id: str = "", provider: str =usage_details, cost_details = {}, {}gen_metadata: Dict[str, Any] = {"tool_call_count": len(output.get("tool_calls", [])) or assistant_tool_call_count}- if api_duration and api_duration > 0:- gen_metadata["api_duration_s"] = round(api_duration, 3)+ _add_duration(gen_metadata, api_duration)if finish_reason:gen_metadata["finish_reason"] = finish_reason_end_observation(generation, output=output, usage_details=usage_details,@@ -990,11 +977,9 @@ def on_post_llm_call(*, task_id: str = "", session_id: str = "", provider: str =def on_pre_tool_call(*, tool_name: str = "", args: Any = None, task_id: str = "",session_id: str = "", tool_call_id: str = "",turn_id: str = "", api_request_id: str = "", **_: Any) -> None:- client = _get_langfuse()+ client, task_key = _client_and_key(task_id, session_id, turn_id, api_request_id)if client is None:return-- task_key = _trace_key(task_id, session_id, turn_id=turn_id, api_request_id=api_request_id)with _STATE_LOCK:state = _TRACE_STATE.get(task_key)if state is None:@@ -1056,11 +1041,9 @@ def on_api_request_error(*, task_id: str = "", session_id: str = "", api_call_co"""Close (as ERROR) the open generation for a failed API request so the turndoesn't look hung until eviction; a non-retryable failure also finishes theturn, since the agent loop is about to unwind."""- client = _get_langfuse()+ client, task_key = _client_and_key(task_id, session_id, turn_id, api_request_id)if client is None:return-- task_key = _trace_key(task_id, session_id, turn_id=turn_id, api_request_id=api_request_id)state, generation = _pop_generation(task_key, api_call_count)if state is None:return@@ -1070,14 +1053,11 @@ def on_api_request_error(*, task_id: str = "", session_id: str = "", api_call_co# Error messages can embed request fragments (URLs w/ keys, prompt echoes) — capture-pipeline them.error_metadata: Dict[str, Any] = {"error": True, "error_type": error_type, "error_message": _capture_content(error_message)}- for key, val in (("status_code", status_code), ("retry_count", retry_count),- ("max_retries", max_retries), ("retryable", retryable)):- if val is not None:- error_metadata[key] = val+ error_metadata.update({k: v for k, v in (("status_code", status_code), ("retry_count", retry_count),+ ("max_retries", max_retries), ("retryable", retryable)) if v is not None})if reason:error_metadata["reason"] = str(reason)- if api_duration and api_duration > 0:- error_metadata["api_duration_s"] = round(api_duration, 3)+ _add_duration(error_metadata, api_duration)if generation is not None:try: