@langwatch/server 3.1.0-beta.21 → 3.1.0-beta.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/__init__.py +36 -0
  2. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/_logger.py +165 -0
  3. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/batch_clustering.py +153 -0
  4. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/build_response.py +77 -0
  5. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/constants.py +7 -0
  6. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/incremental_clustering.py +325 -0
  7. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/topic_naming.py +432 -0
  8. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/types.py +42 -0
  9. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/utils.py +191 -0
  10. package/langevals/evaluators/topic_clustering/pyproject.toml +52 -0
  11. package/langevals/evaluators/topic_clustering/tests/test_topic_clustering.py +239 -0
  12. package/langevals/evaluators/topic_clustering/tests/test_topic_clustering_integration.py +97 -0
  13. package/langevals/evaluators/topic_clustering/tests/test_topic_naming.py +72 -0
  14. package/langevals/langevals/pytest_plugins/pass_rate_plugin.py +7 -1
  15. package/langevals/langevals/server.py +28 -0
  16. package/langevals/pyproject.toml +3 -0
  17. package/langevals/uv.lock +119 -20
  18. package/langwatch/dist/client/assets/{AnnotationsTable-BDAkYaz6.js → AnnotationsTable-uS_9SQ-g.js} +2 -2
  19. package/langwatch/dist/client/assets/{BatchEvaluationSummary-DMaQM_VB.js → BatchEvaluationSummary-DtFd8yKJ.js} +2 -2
  20. package/langwatch/dist/client/assets/{BudgetEditDrawer-CHaqmdIl.js → BudgetEditDrawer-CHEPz0hH.js} +2 -2
  21. package/langwatch/dist/client/assets/{ChartCard-D14PUg_d.js → ChartCard-s5fMPo7b.js} +2 -2
  22. package/langwatch/dist/client/assets/{ChatWindow-CRDnlP-Q.js → ChatWindow-C0XSteVJ.js} +2 -2
  23. package/langwatch/dist/client/assets/ChatWindow-DFEmNXQL.js +1 -0
  24. package/langwatch/dist/client/assets/{ConfirmDialog-CXIhncvW.js → ConfirmDialog-M94yLNvP.js} +2 -2
  25. package/langwatch/dist/client/assets/{ContactSalesBlock-CijLBwRC.js → ContactSalesBlock-CnnuZ8iI.js} +2 -2
  26. package/langwatch/dist/client/assets/{DSPyExperiment-B1YOL2m8.js → DSPyExperiment-CMA6lrlx.js} +2 -2
  27. package/langwatch/dist/client/assets/{FilterDisplay-BB0xWrLn.js → FilterDisplay-0S3NqCkq.js} +2 -2
  28. package/langwatch/dist/client/assets/{FormatMoney-w9vr_h0X.js → FormatMoney-CCygtAHg.js} +2 -2
  29. package/langwatch/dist/client/assets/{FoundryDrawer-CdJDXtpz.js → FoundryDrawer-B35xZ26C.js} +2 -2
  30. package/langwatch/dist/client/assets/{GatewayErrorPanel-DvE9U2dS.js → GatewayErrorPanel-BsaYQEie.js} +2 -2
  31. package/langwatch/dist/client/assets/{GatewayLayout-lv1p_6B5.js → GatewayLayout-LvwwrwMf.js} +2 -2
  32. package/langwatch/dist/client/assets/{GraphsLayout-BJ68J9e-.js → GraphsLayout-DJ-HI9N1.js} +2 -2
  33. package/langwatch/dist/client/assets/{GroupBindingInputRow-DebZBCnD.js → GroupBindingInputRow-CV-fBkX9.js} +2 -2
  34. package/langwatch/dist/client/assets/{MessagesTable-B6lYde-x.js → MessagesTable-9taaKCOZ.js} +2 -2
  35. package/langwatch/dist/client/assets/{NavigationFooter-CiOVzDUh.js → NavigationFooter-Dzvauw3l.js} +2 -2
  36. package/langwatch/dist/client/assets/{NoDataInfoBlock-quSW_MRm.js → NoDataInfoBlock-CLKl_wlX.js} +2 -2
  37. package/langwatch/dist/client/assets/{OpsPageShell-DJ1WlI6-.js → OpsPageShell-C_mTziRS.js} +2 -2
  38. package/langwatch/dist/client/assets/{OptimizationStudio-BlozXjcN.js → OptimizationStudio-D2zpsmJj.js} +8 -12
  39. package/langwatch/dist/client/assets/{PreconditionsField-BOfcWvmZ.js → PreconditionsField-WXB8kcTK.js} +2 -2
  40. package/langwatch/dist/client/assets/{SettingsLayout-CLCGxMAe.js → SettingsLayout--1gdEuhv.js} +2 -2
  41. package/langwatch/dist/client/assets/{SubscriptionPage-J8b2Zaj6.js → SubscriptionPage-B0ox_4kM.js} +2 -2
  42. package/langwatch/dist/client/assets/{VirtualKeySecretReveal-DR1VDLy7.js → VirtualKeySecretReveal-CRbI1dKQ.js} +2 -2
  43. package/langwatch/dist/client/assets/{WithPermissionGuard-DD8uo3UK.js → WithPermissionGuard-B4Jo8E5-.js} +2 -2
  44. package/langwatch/dist/client/assets/{__...path__-BZVaIayJ.js → __...path__-BF2zkD84.js} +2 -2
  45. package/langwatch/dist/client/assets/{_experiment_-B1aT-wS3.js → _experiment_-D02aoVQk.js} +2 -2
  46. package/langwatch/dist/client/assets/{_id_-oI_eq-I_.js → _id_-Ch8YmTiM.js} +2 -2
  47. package/langwatch/dist/client/assets/{_id_-DAqPuO73.js → _id_-D6ZvwHpH.js} +2 -2
  48. package/langwatch/dist/client/assets/{_id_-DUngklVb.js → _id_-DOC1ZkBm.js} +2 -2
  49. package/langwatch/dist/client/assets/{_id_-jFDAfbob.js → _id_-DfWwW6_N.js} +2 -2
  50. package/langwatch/dist/client/assets/{_id_-BKBrWGG0.js → _id_-DxUo4W7J.js} +2 -2
  51. package/langwatch/dist/client/assets/_not-found-COI3ShsR.js +1 -0
  52. package/langwatch/dist/client/assets/{_project_-Bt1tayHB.js → _project_-_UUt5Ar9.js} +2 -2
  53. package/langwatch/dist/client/assets/{_runId_-CfvnDt5H.js → _runId_-Dimwzp48.js} +2 -2
  54. package/langwatch/dist/client/assets/_slug_-BMvKBwS_.js +2 -0
  55. package/langwatch/dist/client/assets/{_slug_-DZAdl0QS.js → _slug_-CE6VoDSC.js} +2 -2
  56. package/langwatch/dist/client/assets/{_slug_-DmoWXjKT.js → _slug_-OiOLG1Mv.js} +2 -2
  57. package/langwatch/dist/client/assets/{_team_-DL_wKSWK.js → _team_-DKvmwO_5.js} +2 -2
  58. package/langwatch/dist/client/assets/{_workflow_-DcMXLPUe.js → _workflow_-FkilKiB-.js} +3 -3
  59. package/langwatch/dist/client/assets/{_workflow_-NI9bac7d.js → _workflow_-gJZppg3h.js} +2 -2
  60. package/langwatch/dist/client/assets/{access-audit-CFwNwusI.js → access-audit-xcUVYMMT.js} +2 -2
  61. package/langwatch/dist/client/assets/{agents-Di4XRwcn.js → agents-D32g91cu.js} +2 -2
  62. package/langwatch/dist/client/assets/{all-C273mlDB.js → all-vnREzDZj.js} +2 -2
  63. package/langwatch/dist/client/assets/{analytics-CEAcSf6B.js → analytics-DP6Y4Feh.js} +2 -2
  64. package/langwatch/dist/client/assets/{annotation-scores-CHfn4LQp.js → annotation-scores-CjD4CEB6.js} +2 -2
  65. package/langwatch/dist/client/assets/{annotations-CHZQrha6.js → annotations-1rVXiDRQ.js} +2 -2
  66. package/langwatch/dist/client/assets/{api-keys-BT7HExHM.js → api-keys-BJpKyuaz.js} +2 -2
  67. package/langwatch/dist/client/assets/{audit-log-BGk-51Dt.js → audit-log-BdUdZjxp.js} +2 -2
  68. package/langwatch/dist/client/assets/{authentication-DvwXfkp-.js → authentication-8mQB00CC.js} +2 -2
  69. package/langwatch/dist/client/assets/{authorize-tXpHrWyw.js → authorize-BpUueMNW.js} +2 -2
  70. package/langwatch/dist/client/assets/{authorize-CRu9xlpU.js → authorize-CbNBtmxW.js} +2 -2
  71. package/langwatch/dist/client/assets/{automations-CjDvz9Ak.js → automations-34KMkRxd.js} +2 -2
  72. package/langwatch/dist/client/assets/{billing-plans-FUqEPN62.js → billing-plans-BUQp08MI.js} +2 -2
  73. package/langwatch/dist/client/assets/{budgets-BV6_RHrs.js → budgets-CdelE8Hv.js} +2 -2
  74. package/langwatch/dist/client/assets/{cache-rules-CtYA79E_.js → cache-rules-D2m1QlNJ.js} +2 -2
  75. package/langwatch/dist/client/assets/choose-C0LdeUiH.js +2 -0
  76. package/langwatch/dist/client/assets/{command-bar-CaJygoez.js → command-bar-DUK45yin.js} +7 -9
  77. package/langwatch/dist/client/assets/custom-hBq2K4FJ.js +1 -0
  78. package/langwatch/dist/client/assets/{datasets-vLWpH84_.js → datasets-ErNNhmjg.js} +2 -2
  79. package/langwatch/dist/client/assets/{dejaview-DwVR3RGg.js → dejaview-BaD4_v90.js} +2 -2
  80. package/langwatch/dist/client/assets/{dist-SwV3YZv3.js → dist-Cds4Mqhj.js} +4 -6
  81. package/langwatch/dist/client/assets/{edit-CyxsmQmW.js → edit-DpT8ejBV.js} +2 -2
  82. package/langwatch/dist/client/assets/{evaluations-BfgeZMph.js → evaluations-BdQ2Dm2r.js} +2 -2
  83. package/langwatch/dist/client/assets/{evaluations-HSQIMvbX.js → evaluations-C90I4VAr.js} +2 -2
  84. package/langwatch/dist/client/assets/{evaluators-DLHVvnrh.js → evaluators-ig_ugRLt.js} +2 -2
  85. package/langwatch/dist/client/assets/{foundry-Ckq0WjPU.js → foundry-B-X_80pD.js} +2 -2
  86. package/langwatch/dist/client/assets/{gateway-CDSYPZ6w.js → gateway-CS_mtJx-.js} +2 -2
  87. package/langwatch/dist/client/assets/{groups-CCCRUqPj.js → groups-Bp90ChP3.js} +2 -2
  88. package/langwatch/dist/client/assets/{index-Bm6z2fM9.js → index-BEjGS0kI.js} +5 -5
  89. package/langwatch/dist/client/assets/{license-CHOarGWr.js → license-CgnlvyuI.js} +2 -2
  90. package/langwatch/dist/client/assets/{me-CBya_vXs.js → me-DEqhm_KC.js} +2 -2
  91. package/langwatch/dist/client/assets/{members-lIFLh-rh.js → members-CUJANDtH.js} +2 -2
  92. package/langwatch/dist/client/assets/{messages-CG9j8Dz8.js → messages-fQBfCjvp.js} +2 -2
  93. package/langwatch/dist/client/assets/{metrics-C9pzeaI6.js → metrics-DeIxebpD.js} +2 -2
  94. package/langwatch/dist/client/assets/{model-costs-Bc5uqjkl.js → model-costs-C1RbgK--.js} +2 -2
  95. package/langwatch/dist/client/assets/{model-providers-B5UjRgS_.js → model-providers-Pv3ML_-t.js} +2 -2
  96. package/langwatch/dist/client/assets/{my-queue-BkEfiWyR.js → my-queue-BLre2NMr.js} +2 -2
  97. package/langwatch/dist/client/assets/{ops-Cc-g-CMn.js → ops-CCw-FJaT.js} +2 -2
  98. package/langwatch/dist/client/assets/{organization-features-CoIKKHkQ.js → organization-features-rqg-75mI.js} +2 -2
  99. package/langwatch/dist/client/assets/{organizations-DWcQUTzi.js → organizations-DjCzIHVx.js} +2 -2
  100. package/langwatch/dist/client/assets/{persistence-CTQ44vGL.js → persistence-BPvHS0F6.js} +2 -2
  101. package/langwatch/dist/client/assets/{plans-Dq3eFg5K.js → plans-Ch2Ol-Fd.js} +2 -2
  102. package/langwatch/dist/client/assets/{projections-CTNj1QBM.js → projections-it4FOVjm.js} +2 -2
  103. package/langwatch/dist/client/assets/{projects-BxM7C87h.js → projects-CjWZFLfn.js} +2 -2
  104. package/langwatch/dist/client/assets/{prompts-DhXnJT6e.js → prompts-DilmFH_s.js} +2 -2
  105. package/langwatch/dist/client/assets/{providers-DW7VWdqq.js → providers-tlLT_lTF.js} +2 -2
  106. package/langwatch/dist/client/assets/{reports-D3QFKhNP.js → reports-vlrcTrLs.js} +2 -2
  107. package/langwatch/dist/client/assets/{roles-B_0t5DWA.js → roles-DNgi-NQ9.js} +2 -2
  108. package/langwatch/dist/client/assets/{scenarios-BX3XslU0.js → scenarios-BmG_wDkR.js} +2 -2
  109. package/langwatch/dist/client/assets/{scim-DDsLO39r.js → scim-BKr1_FHt.js} +2 -2
  110. package/langwatch/dist/client/assets/{secrets-BvEGwDCy.js → secrets-CU8ocTGv.js} +2 -2
  111. package/langwatch/dist/client/assets/{settings-9giNiAQQ.js → settings-CDzdoYVK.js} +2 -2
  112. package/langwatch/dist/client/assets/{setup-HxXKoVKG.js → setup-nEvn2rjN.js} +2 -2
  113. package/langwatch/dist/client/assets/{subscription-DhyswDze.js → subscription-BPNl_6jF.js} +3 -3
  114. package/langwatch/dist/client/assets/{subscriptions-Dyyau22a.js → subscriptions-D0G-OE5C.js} +2 -2
  115. package/langwatch/dist/client/assets/{teams-DRmeAxzf.js → teams-DThgDQvB.js} +2 -2
  116. package/langwatch/dist/client/assets/{textOverflowHeuristic-JibhpzDV.js → textOverflowHeuristic-DTC8-Ffx.js} +2 -2
  117. package/langwatch/dist/client/assets/{topic-clustering-Bllfw5rZ.js → topic-clustering-BR2Mbpao.js} +2 -2
  118. package/langwatch/dist/client/assets/{topics-CpiGYxqb.js → topics-CI8GoNqp.js} +2 -2
  119. package/langwatch/dist/client/assets/{traceExecutor-CiHXJB0V.js → traceExecutor-CDUGyUaw.js} +2 -2
  120. package/langwatch/dist/client/assets/{usage-BnsstwBY.js → usage-B4mR7ut_.js} +2 -2
  121. package/langwatch/dist/client/assets/{usage-CoyGtJoI.js → usage-C8fbffYi.js} +2 -2
  122. package/langwatch/dist/client/assets/{useAdminResource-SPC5iBHM.js → useAdminResource-SmnnHro6.js} +2 -2
  123. package/langwatch/dist/client/assets/{useAnnotationQueues-2DKZTC7r.js → useAnnotationQueues-CA6Vk--V.js} +2 -2
  124. package/langwatch/dist/client/assets/{useAvailableEvaluators-HndTl2LV.js → useAvailableEvaluators-hmbmcRQr.js} +2 -2
  125. package/langwatch/dist/client/assets/{useDeleteDatasetConfirmation-BgWN6Qqb.js → useDeleteDatasetConfirmation-BCK_zUUe.js} +2 -2
  126. package/langwatch/dist/client/assets/{useWorkflowStore-e1wFCvo2.js → useWorkflowStore-QUJ3J8X9.js} +2 -2
  127. package/langwatch/dist/client/assets/{users-C6wjliCC.js → users-CfhanCfR.js} +2 -2
  128. package/langwatch/dist/client/assets/{users-tF6ZKeV1.js → users-HjuN3o6k.js} +2 -2
  129. package/langwatch/dist/client/assets/{virtual-keys-BL-65S0B.js → virtual-keys-Bj-MhW66.js} +2 -2
  130. package/langwatch/dist/client/assets/{wizard-faGkpZDT.js → wizard-dRWCVVx6.js} +2 -2
  131. package/langwatch/dist/client/assets/{workbench-Oj0s_YR-.js → workbench-CuixH3G1.js} +2 -2
  132. package/langwatch/dist/client/assets/{workflows-Cu9k-Twu.js → workflows-BT6m4Yu9.js} +2 -2
  133. package/langwatch/dist/client/index.html +3 -3
  134. package/langwatch/dist/scenario-child-process.js +20 -10
  135. package/langwatch/package.json +2 -2
  136. package/langwatch/pnpm-lock.yaml +329 -328
  137. package/langwatch/scripts/seed-dogfood-password.ts +163 -0
  138. package/langwatch/src/app/api/workflows/post_event/__tests__/post-event-evaluator.integration.test.ts +458 -0
  139. package/langwatch/src/app/api/workflows/post_event/__tests__/post-event-routing.test.ts +188 -0
  140. package/langwatch/src/app/api/workflows/post_event/__tests__/post-event.integration.test.ts +274 -0
  141. package/langwatch/src/app/api/workflows/post_event/post-event.ts +29 -1
  142. package/langwatch/src/components/agents/AgentCodeEditorDrawer.tsx +4 -5
  143. package/langwatch/src/components/agents/__tests__/AgentCodeEditorDrawer.integration.test.tsx +40 -0
  144. package/langwatch/src/components/evaluations/wizard/hooks/evaluation-wizard-store/slices/factories/__tests__/code-execution-node.factory.unit.test.ts +47 -0
  145. package/langwatch/src/components/evaluations/wizard/hooks/evaluation-wizard-store/slices/factories/code-execution-node.factory.ts +2 -4
  146. package/langwatch/src/components/experiments/BatchEvaluationV2/BatchEvaluationV2EvaluationResults.tsx +6 -1
  147. package/langwatch/src/hooks/usePostHog.ts +11 -0
  148. package/langwatch/src/optimization_studio/__tests__/registry.test.ts +29 -1
  149. package/langwatch/src/optimization_studio/components/Optimize.tsx +17 -3
  150. package/langwatch/src/optimization_studio/components/properties/AgentPropertiesPanel.tsx +4 -5
  151. package/langwatch/src/optimization_studio/hooks/workflowStoreCore.ts +17 -6
  152. package/langwatch/src/optimization_studio/hooks/workflowStoreCore.unit.test.ts +42 -0
  153. package/langwatch/src/optimization_studio/registry.ts +2 -4
  154. package/langwatch/src/optimization_studio/server/lambda/index.ts +12 -2
  155. package/langwatch/src/server/api/routers/workflows.ts +18 -0
  156. package/langwatch/src/server/evaluations-v3/execution/workflowBuilder.ts +3 -2
  157. package/langwatch/src/server/evaluations-v3/services/__tests__/experiment-run.service.getRun-null.unit.test.ts +71 -0
  158. package/langwatch/src/server/evaluations-v3/services/experiment-run.service.ts +18 -9
  159. package/langwatch/src/server/modelProviders/utils.ts +11 -1
  160. package/langwatch/src/server/nlpgo/__tests__/nlpgoFetch.integration.test.ts +248 -0
  161. package/langwatch/src/server/nlpgo/nlpgoFetch.ts +155 -0
  162. package/langwatch/src/server/routes/__tests__/playground-proxy.integration.test.ts +242 -0
  163. package/langwatch/src/server/routes/playground.ts +11 -1
  164. package/langwatch/src/server/routes/workflows.ts +17 -0
  165. package/langwatch/src/server/topicClustering/topicClustering.ts +33 -8
  166. package/langwatch/src/server/workflows/runWorkflow.ts +10 -13
  167. package/langwatch_nlp/langwatch_nlp/studio/execute/execute_component.py +25 -1
  168. package/langwatch_nlp/langwatch_nlp/studio/parser.py +121 -16
  169. package/langwatch_nlp/langwatch_nlp/topic_clustering/topic_naming.py +39 -32
  170. package/langwatch_nlp/scripts/entrypoint.sh +67 -0
  171. package/langwatch_nlp/tests/studio/test_parse.py +198 -0
  172. package/mcp-server/pnpm-lock.yaml +15 -21
  173. package/package.json +1 -1
  174. package/packages/server/dist/cli.cjs +78 -94
  175. package/langwatch/dist/client/assets/ChatWindow-DzB-tNlQ.js +0 -1
  176. package/langwatch/dist/client/assets/_not-found-PEUaWdF3.js +0 -1
  177. package/langwatch/dist/client/assets/_slug_-C-8AjsjC.js +0 -2
  178. package/langwatch/dist/client/assets/choose--PBky27o.js +0 -2
  179. package/langwatch/dist/client/assets/custom-CSiS1liN.js +0 -1
@@ -0,0 +1,36 @@
1
+ """LangEvals Topic Clustering — Special evaluator package.
2
+
3
+ Topic clustering doesn't fit the per-trace evaluator interface (it's a batch
4
+ operation that takes many traces and returns topics+subtopics+assignments).
5
+ This module exposes a `register_routes(app)` hook that mounts two custom
6
+ endpoints on the langevals FastAPI app:
7
+
8
+ - POST /topics/batch_clustering
9
+ - POST /topics/incremental_clustering
10
+
11
+ The langevals server.py imports this module conditionally and calls
12
+ register_routes() so the package is opt-in (won't break per-evaluator
13
+ deployments that don't include topic_clustering).
14
+
15
+ Source: migrated from langwatch_nlp/topic_clustering/* in 2026-04 as part of
16
+ the langwatch_nlp → Go migration. Topic clustering itself stays Python
17
+ (sklearn + scipy + numpy + LiteLLM); only the hosting service changes from
18
+ langwatch_nlp to langevals so all Python long-term lives in one place.
19
+ """
20
+
21
+ from fastapi import FastAPI
22
+
23
+ from langevals_topic_clustering import batch_clustering, incremental_clustering
24
+
25
+
26
+ def register_routes(app: FastAPI) -> None:
27
+ """Mount topic-clustering routes on the given FastAPI app.
28
+
29
+ Idempotent only insofar as FastAPI accepts duplicate route registration:
30
+ do not call twice on the same app instance.
31
+ """
32
+ batch_clustering.setup_endpoints(app)
33
+ incremental_clustering.setup_endpoints(app)
34
+
35
+
36
+ __all__ = ["register_routes"]
@@ -0,0 +1,165 @@
1
+ """
2
+ Structured logger for langwatch_nlp - uses JSON in production, pretty-print in development.
3
+
4
+ Similar to langwatch/src/utils/logger/index.ts (pino).
5
+ """
6
+
7
+ import logging
8
+ import os
9
+ import sys
10
+ from contextvars import ContextVar
11
+ from typing import Any, Optional
12
+
13
+ import structlog
14
+ from structlog.typing import EventDict, WrappedLogger
15
+
16
+ # Context variable for request-scoped data (like project_id)
17
+ # Using None as default to avoid sharing a mutable dict across contexts
18
+ _log_context: ContextVar[Optional[dict[str, Any]]] = ContextVar("log_context", default=None)
19
+
20
+
21
+ def get_log_context() -> dict[str, Any]:
22
+ """Get the current log context."""
23
+ current = _log_context.get()
24
+ return (current or {}).copy()
25
+
26
+
27
+ def set_log_context(**kwargs: Any) -> None:
28
+ """Set values in the log context for the current async context."""
29
+ current = _log_context.get() or {}
30
+ updated = current.copy()
31
+ updated.update(kwargs)
32
+ _log_context.set(updated)
33
+
34
+
35
+ def clear_log_context() -> None:
36
+ """Clear the log context."""
37
+ _log_context.set(None)
38
+
39
+
40
+ def _add_context_processor(
41
+ logger: WrappedLogger, method_name: str, event_dict: EventDict
42
+ ) -> EventDict:
43
+ """Add context variables to log events."""
44
+ context = get_log_context()
45
+ # Insert context at the beginning so it appears before the message details
46
+ for key, value in context.items():
47
+ if key not in event_dict:
48
+ event_dict[key] = value
49
+ return event_dict
50
+
51
+
52
+ def _add_log_level_uppercase(
53
+ logger: WrappedLogger, method_name: str, event_dict: EventDict
54
+ ) -> EventDict:
55
+ """Convert log level to uppercase (matching TypeScript logger)."""
56
+ if "level" in event_dict:
57
+ event_dict["level"] = event_dict["level"].upper()
58
+ return event_dict
59
+
60
+
61
+ def _snake_to_camel(name: str) -> str:
62
+ """Convert snake_case to camelCase."""
63
+ components = name.split("_")
64
+ return components[0] + "".join(x.title() for x in components[1:])
65
+
66
+
67
+ def _convert_keys_to_camel_case(
68
+ logger: WrappedLogger, method_name: str, event_dict: EventDict
69
+ ) -> EventDict:
70
+ """Convert all snake_case keys to camelCase for JSON output (matching JS conventions)."""
71
+ # Keys to keep as-is (standard structlog keys)
72
+ keep_as_is = {"event", "level", "logger", "timestamp"}
73
+
74
+ new_dict: EventDict = {}
75
+ for key, value in event_dict.items():
76
+ if key in keep_as_is or "_" not in key:
77
+ new_dict[key] = value
78
+ else:
79
+ new_dict[_snake_to_camel(key)] = value
80
+ return new_dict
81
+
82
+
83
+ def _configure_structlog() -> None:
84
+ """Configure structlog based on environment."""
85
+ is_test = os.environ.get("NODE_ENV") == "test" or os.environ.get("PYTEST_CURRENT_TEST")
86
+ environment = os.environ.get("ENVIRONMENT", "").lower()
87
+ is_deployed = environment in ("production", "staging", "development")
88
+ is_prod = os.environ.get("NODE_ENV") == "production" or is_deployed
89
+ log_level_str = os.environ.get("LOG_LEVEL", "INFO" if not is_test else "ERROR")
90
+ log_level = getattr(logging, log_level_str.upper(), logging.INFO)
91
+
92
+ # Note: the upstream langwatch_nlp/logger.py defined a nested
93
+ # add_logger_name processor here but never wired it into the
94
+ # processors list (CodeRabbit caught this dead code in #3483).
95
+ # Drop it; structlog already names loggers via the get_logger()
96
+ # bind path the rest of this module configures.
97
+
98
+ # Shared processors for all environments
99
+ shared_processors: list[structlog.types.Processor] = [
100
+ structlog.contextvars.merge_contextvars,
101
+ _add_context_processor,
102
+ structlog.stdlib.add_log_level,
103
+ structlog.processors.TimeStamper(fmt="iso"),
104
+ structlog.processors.StackInfoRenderer(),
105
+ structlog.processors.UnicodeDecoder(),
106
+ structlog.processors.CallsiteParameterAdder(),
107
+ ]
108
+
109
+ if is_prod:
110
+ # Production: JSON to stdout with camelCase keys
111
+ structlog.configure(
112
+ processors=[
113
+ *shared_processors,
114
+ _add_log_level_uppercase,
115
+ _convert_keys_to_camel_case,
116
+ structlog.processors.format_exc_info,
117
+ structlog.processors.JSONRenderer(),
118
+ ],
119
+ wrapper_class=structlog.stdlib.BoundLogger,
120
+ context_class=dict,
121
+ logger_factory=structlog.stdlib.LoggerFactory(),
122
+ cache_logger_on_first_use=True,
123
+ )
124
+ else:
125
+ # Development/Test: Pretty console output
126
+ structlog.configure(
127
+ processors=[
128
+ *shared_processors,
129
+ structlog.dev.ConsoleRenderer(colors=not is_test),
130
+ ],
131
+ wrapper_class=structlog.stdlib.BoundLogger,
132
+ context_class=dict,
133
+ logger_factory=structlog.stdlib.LoggerFactory(),
134
+ cache_logger_on_first_use=True,
135
+ )
136
+
137
+ # Also configure standard library logging to use structlog
138
+ logging.basicConfig(
139
+ format="%(message)s",
140
+ stream=sys.stdout,
141
+ level=log_level,
142
+ )
143
+
144
+
145
+ # Configure structlog on module import
146
+ _configure_structlog()
147
+
148
+
149
+ def get_logger(name: str) -> structlog.stdlib.BoundLogger:
150
+ """
151
+ Get a structured logger instance.
152
+
153
+ Usage:
154
+ logger = get_logger("topic_clustering.batch")
155
+ logger.info("Starting batch clustering", trace_count=100)
156
+
157
+ # With context binding (for project_id, etc.)
158
+ set_log_context(project_id="proj_123")
159
+ logger.info("Processing") # Will include project_id automatically
160
+ """
161
+ return structlog.get_logger(name)
162
+
163
+
164
+ # Type alias for backwards compatibility
165
+ Logger = structlog.stdlib.BoundLogger
@@ -0,0 +1,153 @@
1
+ from typing import Any, Optional
2
+ from fastapi import FastAPI, HTTPException
3
+ from pydantic import BaseModel
4
+ from langevals_topic_clustering.build_response import build_response
5
+ from langevals_topic_clustering.topic_naming import (
6
+ generate_topic_and_subtopic_names,
7
+ )
8
+ from langevals_topic_clustering.utils import (
9
+ calculate_centroid_and_distance,
10
+ fill_embeddings,
11
+ )
12
+ from langevals_topic_clustering.constants import (
13
+ COPHENETIC_DISTANCES_FOR_SUBTOPICS,
14
+ COPHENETIC_DISTANCES_FOR_TOPICS,
15
+ MINIMUM_SUBTOPICS_PER_TOPIC,
16
+ MINIMUM_TRACES_PER_TOPIC,
17
+ )
18
+ from langevals_topic_clustering.types import (
19
+ TopicClusteringResponse,
20
+ Trace,
21
+ TraceWithEmbeddings,
22
+ )
23
+ from scipy.cluster.hierarchy import linkage, fcluster
24
+ from langevals_topic_clustering._logger import get_logger, set_log_context, clear_log_context
25
+
26
+ logger = get_logger("topic_clustering.batch")
27
+
28
+
29
+ def build_hierarchy(
30
+ traces: list[TraceWithEmbeddings],
31
+ cophenetic_distance: int,
32
+ with_embeddings=True,
33
+ maximum_p95_distance: float = 1,
34
+ with_subtopics=True,
35
+ ) -> dict[str, dict[str, list[Trace]]]:
36
+ embeddings = [t["embeddings"] for t in traces]
37
+ Z = linkage(embeddings, "ward")
38
+ topic_ids = fcluster(Z, cophenetic_distance, criterion="distance")
39
+
40
+ # Dictionary to hold our two-level hierarchy
41
+ hierarchy = {}
42
+
43
+ # Iterate over each unique topic to create subtopics
44
+ for topic_id in set(topic_ids):
45
+ # Isolate samples that belong to the current topic
46
+ indices_in_topic = [i for i, t in enumerate(topic_ids) if t == topic_id]
47
+
48
+ traces_in_topic = [traces[i] for i in indices_in_topic]
49
+
50
+ # If there's less than the minimum number of traces, skip this topic
51
+ unique_inputs = set([t["input"] for t in traces_in_topic])
52
+ if len(unique_inputs) < MINIMUM_TRACES_PER_TOPIC:
53
+ continue
54
+
55
+ _, p95_distance = calculate_centroid_and_distance(traces_in_topic)
56
+ # Skip this topic if the p95 distance is too large
57
+ if p95_distance > maximum_p95_distance:
58
+ continue
59
+
60
+ if with_subtopics:
61
+ subtopics = build_hierarchy(
62
+ traces_in_topic,
63
+ COPHENETIC_DISTANCES_FOR_SUBTOPICS,
64
+ with_embeddings,
65
+ maximum_p95_distance,
66
+ False,
67
+ )
68
+
69
+ if len(subtopics.keys()) < MINIMUM_SUBTOPICS_PER_TOPIC:
70
+ continue
71
+
72
+ hierarchy[f"Topic {topic_id}"] = subtopics
73
+ else:
74
+ hierarchy[f"Subtopic {topic_id}"] = [
75
+ Trace(
76
+ trace_id=traces[i]["trace_id"],
77
+ input=traces[i]["input"],
78
+ embeddings=traces[i]["embeddings"] if with_embeddings else "[embeddings]", # type: ignore
79
+ )
80
+ for i in indices_in_topic
81
+ ]
82
+
83
+ return hierarchy
84
+
85
+
86
+ class BatchClusteringParams(BaseModel):
87
+ project_id: str
88
+ traces: list[Trace]
89
+ deployment_name: Optional[str] = None
90
+ litellm_params: dict[str, str]
91
+ embeddings_litellm_params: dict[str, Any]
92
+
93
+
94
+ def setup_endpoints(app: FastAPI):
95
+ @app.post("/topics/batch_clustering")
96
+ def topics_batch_clustering(
97
+ params: BatchClusteringParams,
98
+ ) -> TopicClusteringResponse:
99
+ try:
100
+ set_log_context(project_id=params.project_id)
101
+ logger.info("Starting batch clustering", trace_count=len(params.traces))
102
+
103
+ model = params.litellm_params["model"]
104
+ if model.startswith("azure/") and params.deployment_name:
105
+ model = f"azure/{params.deployment_name}"
106
+
107
+ logger.info("Generating embeddings for traces", step="1/4")
108
+ traces_with_embeddings = fill_embeddings(
109
+ params.traces, params.embeddings_litellm_params
110
+ )
111
+ logger.info(
112
+ "Embeddings complete",
113
+ step="1/4",
114
+ traces_with_embeddings=len(traces_with_embeddings),
115
+ )
116
+
117
+ logger.info("Building hierarchy from embeddings", step="2/4")
118
+ hierarchy = build_hierarchy(
119
+ traces_with_embeddings, COPHENETIC_DISTANCES_FOR_TOPICS
120
+ )
121
+ logger.info("Hierarchy built", step="2/4", topics_identified=len(hierarchy))
122
+
123
+ logger.info("Generating topic and subtopic names", step="3/4")
124
+ topic_names, subtopic_names, cost = generate_topic_and_subtopic_names(
125
+ model=model,
126
+ litellm_params=params.litellm_params,
127
+ embeddings_litellm_params=params.embeddings_litellm_params,
128
+ hierarchy=hierarchy,
129
+ )
130
+ logger.info("Names generated", step="3/4", topic_count=len(topic_names))
131
+
132
+ logger.info("Building final response", step="4/4")
133
+ topics, subtopics, traces_to_assign = build_response(
134
+ hierarchy, topic_names, subtopic_names
135
+ )
136
+ logger.info(
137
+ "Batch clustering complete",
138
+ topic_count=len(topics),
139
+ subtopic_count=len(subtopics),
140
+ trace_assignment_count=len(traces_to_assign),
141
+ )
142
+
143
+ return {
144
+ "topics": topics,
145
+ "subtopics": subtopics,
146
+ "traces": traces_to_assign,
147
+ "cost": cost,
148
+ }
149
+ except Exception as e:
150
+ logger.error("Batch clustering failed", error=str(e), error_type=type(e).__name__)
151
+ raise HTTPException(status_code=500, detail="Batch clustering failed") from e
152
+ finally:
153
+ clear_log_context()
@@ -0,0 +1,77 @@
1
+ from typing import Optional
2
+ import nanoid
3
+ from langevals_topic_clustering.constants import (
4
+ MINIMUM_SUBTOPICS_PER_TOPIC,
5
+ MINIMUM_TRACES_PER_TOPIC,
6
+ )
7
+ from langevals_topic_clustering.utils import calculate_centroid_and_distance
8
+ from langevals_topic_clustering.types import Subtopic, Topic, Trace, TraceTopicMap
9
+
10
+
11
+ def build_response(
12
+ hierarchy: dict[str, dict[str, list[Trace]]],
13
+ topic_names: list[Optional[str]],
14
+ subtopic_names: list[list[Optional[str]]],
15
+ ) -> tuple[list[Topic], list[Subtopic], list[TraceTopicMap]]:
16
+ topics: list[Topic] = []
17
+ subtopics: list[Subtopic] = []
18
+ traces: list[TraceTopicMap] = []
19
+
20
+ for topic_idx, topic in enumerate(hierarchy.values()):
21
+ topic_id = None
22
+
23
+ topic_samples = [
24
+ item for subtopic_samples in topic.values() for item in subtopic_samples
25
+ ]
26
+ unique_values = list(set([item["input"] for item in topic_samples]))
27
+ topic_name = topic_names[topic_idx]
28
+ if (
29
+ len(topic.values()) >= MINIMUM_SUBTOPICS_PER_TOPIC
30
+ and len(unique_values) >= MINIMUM_TRACES_PER_TOPIC
31
+ and topic_name is not None
32
+ ):
33
+ topic_id = f"topic_{nanoid.generate()}"
34
+ topic_centroid, topic_p95_distance = calculate_centroid_and_distance(
35
+ topic_samples
36
+ )
37
+
38
+ topics.append(
39
+ Topic(
40
+ id=topic_id,
41
+ name=topic_name,
42
+ centroid=topic_centroid.tolist(),
43
+ p95_distance=topic_p95_distance,
44
+ )
45
+ )
46
+
47
+ for subtopic_idx, subtopic in enumerate(topic.values()):
48
+ subtopic_id = None
49
+
50
+ unique_values = list(set([item["input"] for item in subtopic]))
51
+ subtopic_name = subtopic_names[topic_idx][subtopic_idx]
52
+ if topic_id and len(unique_values) >= MINIMUM_TRACES_PER_TOPIC and subtopic_name is not None:
53
+ subtopic_id = f"subtopic_{nanoid.generate()}"
54
+ subtopic_centroid, subtopic_p95_distance = (
55
+ calculate_centroid_and_distance(subtopic)
56
+ )
57
+
58
+ subtopics.append(
59
+ Subtopic(
60
+ id=subtopic_id,
61
+ name=subtopic_name,
62
+ centroid=subtopic_centroid.tolist(),
63
+ p95_distance=subtopic_p95_distance,
64
+ parent_id=topic_id,
65
+ )
66
+ )
67
+
68
+ for trace in subtopic:
69
+ traces.append(
70
+ TraceTopicMap(
71
+ trace_id=trace["trace_id"],
72
+ topic_id=topic_id,
73
+ subtopic_id=subtopic_id,
74
+ )
75
+ )
76
+
77
+ return topics, subtopics, traces
@@ -0,0 +1,7 @@
1
+ MINIMUM_SUBTOPICS_PER_TOPIC = 1
2
+ MINIMUM_TRACES_PER_TOPIC = 5
3
+ COPHENETIC_DISTANCES_FOR_TOPICS = 4
4
+ COPHENETIC_DISTANCES_FOR_SUBTOPICS = 2
5
+
6
+ MINIMUM_UNASSIGNED_TRACES_TO_CREATE_NEW_TOPIC = 100
7
+ MINIMUM_UNASSIGNED_TRACES_TO_CREATE_NEW_SUBTOPIC = 50