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

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 (171) 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-DDh108-i.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-TNQ6uyis.js} +4 -4
  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/scripts/seed-dogfood-password.ts +163 -0
  135. package/langwatch/src/app/api/workflows/post_event/__tests__/post-event-evaluator.integration.test.ts +458 -0
  136. package/langwatch/src/app/api/workflows/post_event/__tests__/post-event-routing.test.ts +180 -0
  137. package/langwatch/src/app/api/workflows/post_event/__tests__/post-event.integration.test.ts +274 -0
  138. package/langwatch/src/app/api/workflows/post_event/post-event.ts +29 -1
  139. package/langwatch/src/components/agents/AgentCodeEditorDrawer.tsx +4 -5
  140. package/langwatch/src/components/agents/__tests__/AgentCodeEditorDrawer.integration.test.tsx +40 -0
  141. package/langwatch/src/components/evaluations/wizard/hooks/evaluation-wizard-store/slices/factories/__tests__/code-execution-node.factory.unit.test.ts +47 -0
  142. package/langwatch/src/components/evaluations/wizard/hooks/evaluation-wizard-store/slices/factories/code-execution-node.factory.ts +2 -4
  143. package/langwatch/src/components/experiments/BatchEvaluationV2/BatchEvaluationV2EvaluationResults.tsx +6 -1
  144. package/langwatch/src/optimization_studio/__tests__/registry.test.ts +29 -1
  145. package/langwatch/src/optimization_studio/components/Optimize.tsx +17 -3
  146. package/langwatch/src/optimization_studio/components/properties/AgentPropertiesPanel.tsx +4 -5
  147. package/langwatch/src/optimization_studio/hooks/workflowStoreCore.ts +17 -6
  148. package/langwatch/src/optimization_studio/hooks/workflowStoreCore.unit.test.ts +42 -0
  149. package/langwatch/src/optimization_studio/registry.ts +2 -4
  150. package/langwatch/src/optimization_studio/server/lambda/index.ts +12 -2
  151. package/langwatch/src/server/api/routers/workflows.ts +18 -0
  152. package/langwatch/src/server/evaluations-v3/execution/workflowBuilder.ts +3 -2
  153. package/langwatch/src/server/evaluations-v3/services/__tests__/experiment-run.service.getRun-null.unit.test.ts +71 -0
  154. package/langwatch/src/server/evaluations-v3/services/experiment-run.service.ts +18 -9
  155. package/langwatch/src/server/modelProviders/utils.ts +11 -1
  156. package/langwatch/src/server/nlpgo/__tests__/nlpgoFetch.integration.test.ts +248 -0
  157. package/langwatch/src/server/nlpgo/nlpgoFetch.ts +142 -0
  158. package/langwatch/src/server/routes/__tests__/playground-proxy.integration.test.ts +242 -0
  159. package/langwatch/src/server/routes/playground.ts +11 -1
  160. package/langwatch/src/server/routes/workflows.ts +17 -0
  161. package/langwatch/src/server/topicClustering/topicClustering.ts +33 -8
  162. package/langwatch/src/server/workflows/runWorkflow.ts +10 -13
  163. package/langwatch_nlp/langwatch_nlp/topic_clustering/topic_naming.py +39 -32
  164. package/langwatch_nlp/scripts/entrypoint.sh +67 -0
  165. package/package.json +1 -1
  166. package/packages/server/dist/cli.cjs +67 -94
  167. package/langwatch/dist/client/assets/ChatWindow-DzB-tNlQ.js +0 -1
  168. package/langwatch/dist/client/assets/_not-found-PEUaWdF3.js +0 -1
  169. package/langwatch/dist/client/assets/_slug_-C-8AjsjC.js +0 -2
  170. package/langwatch/dist/client/assets/choose--PBky27o.js +0 -2
  171. package/langwatch/dist/client/assets/custom-CSiS1liN.js +0 -1
@@ -0,0 +1,432 @@
1
+ from concurrent.futures import Future, ThreadPoolExecutor
2
+ import contextvars
3
+ import math
4
+ from typing import Optional
5
+ import litellm
6
+ from litellm.cost_calculator import completion_cost
7
+ import numpy as np
8
+ import os
9
+ import json
10
+ from random import random
11
+ from typing import Iterable, TypeVar, Optional
12
+
13
+ from tenacity import retry, stop_after_attempt, wait_exponential
14
+
15
+ from langevals_topic_clustering.types import Money, Trace
16
+
17
+ from langevals_topic_clustering.utils import (
18
+ generate_embeddings,
19
+ )
20
+ from langevals_topic_clustering._logger import get_logger
21
+
22
+ T = TypeVar("T")
23
+
24
+ logger = get_logger("topic_clustering.naming")
25
+
26
+ os.environ["AZURE_API_VERSION"] = "2024-02-01"
27
+
28
+
29
+ @retry(wait=wait_exponential(min=12, max=60), stop=stop_after_attempt(4), reraise=True)
30
+ def generate_topic_names(
31
+ litellm_params: dict[str, str],
32
+ topic_examples: list[list[str]],
33
+ existing: Optional[list[str]] = None,
34
+ ) -> tuple[list[str], Money]:
35
+ example_count = sum([len(examples) for examples in topic_examples])
36
+ logger.info("Generating names for topics", topic_count=len(topic_examples), example_count=example_count)
37
+ topic_examples_str = "\n\n\n".join(
38
+ [
39
+ f"# Topic {index} Samples\n\n" + "\n".join(samples)
40
+ for index, samples in enumerate(topic_examples)
41
+ ]
42
+ )
43
+
44
+ existing_str = "\n".join(existing) if existing else ""
45
+ existing_message = (
46
+ f"\n\nThose are the topics that already exist, avoid using any names that may overlap \
47
+ in meaning with them, think how the current sample data is unique and different from those instead:\n\n\
48
+ {existing_str}"
49
+ if existing_str
50
+ else ""
51
+ )
52
+
53
+ messages = [
54
+ {
55
+ "role": "system",
56
+ "content": f'You are a highly knowledgeable assistant tasked with taxonomy for naming topics \
57
+ based on a list of examples. Provide a single, descriptive name for each topic. \
58
+ Avoid using "and" or "&" in the name, try to summarize it with a single concept. \
59
+ Topic names should not be similar to each other, as the data is already organized, \
60
+ the disambiguation between two similar topics should be clear from the name alone.\
61
+ {existing_message}',
62
+ },
63
+ {"role": "user", "content": f"{topic_examples_str}"},
64
+ ]
65
+ tools = [
66
+ {
67
+ "type": "function",
68
+ "function": {
69
+ "name": "topicNames",
70
+ "parameters": {
71
+ "type": "object",
72
+ "properties": dict(
73
+ [
74
+ (f"topic_{index}", {"type": "string"})
75
+ for index in range(len(topic_examples))
76
+ ]
77
+ ),
78
+ },
79
+ "description": 'use this function to name the topics based on the examples provided, avoid using "and" or "&" in the name, try to name it with a single 2-3 words concept.',
80
+ },
81
+ }
82
+ ]
83
+ tool_choice = {"type": "function", "function": {"name": "topicNames"}}
84
+
85
+ try:
86
+ response = litellm.completion(
87
+ temperature=0.0,
88
+ messages=messages,
89
+ tools=tools,
90
+ tool_choice=tool_choice,
91
+ **litellm_params, # type: ignore
92
+ )
93
+ except Exception as e:
94
+ logger.error(
95
+ "Failed to generate topic names",
96
+ topic_count=len(topic_examples),
97
+ error=str(e),
98
+ )
99
+ raise ValueError(
100
+ f"Failed to generate topic names for {len(topic_examples)} topics: {e}\n\nExisting: {existing_str}\n\nTopic examples: {topic_examples_str}\n\n. Error: {e}"
101
+ )
102
+
103
+ total_cost = completion_cost(response)
104
+ topic_names_dict = json.loads(
105
+ response.choices[0].message.tool_calls[0].function.arguments # type: ignore
106
+ )
107
+
108
+ # Look up by the explicit `topic_{idx}` keys we sent in the tool
109
+ # schema instead of trusting json.loads() to preserve the model's
110
+ # output order. Insertion order is well-defined in CPython but
111
+ # the LLM is free to reorder fields in its JSON, which would
112
+ # silently mis-pair names with topics.
113
+ missing = [
114
+ idx for idx in range(len(topic_examples))
115
+ if not topic_names_dict.get(f"topic_{idx}")
116
+ ]
117
+ if missing:
118
+ raise ValueError(
119
+ f"Missing topic names for indexes {missing}; got keys {list(topic_names_dict.keys())}"
120
+ )
121
+ topic_names: list[str] = [
122
+ topic_names_dict[f"topic_{idx}"] for idx in range(len(topic_examples))
123
+ ]
124
+
125
+ return topic_names, Money(amount=total_cost, currency="USD")
126
+
127
+
128
+ def shuffled(x: Iterable[T]) -> list[T]:
129
+ return sorted(x, key=lambda _: random())
130
+
131
+
132
+ def get_subtopic_samples(samples: list[Trace], n=5):
133
+ unique_values = list(set([item["input"] for item in samples]))
134
+ return [item[0:140] for item in shuffled(unique_values)[0:n]]
135
+
136
+
137
+ def generate_topic_names_split(
138
+ litellm_params: dict[str, str],
139
+ topic_examples: list[list[str]],
140
+ existing: Optional[list[str]] = None,
141
+ ) -> tuple[list[Optional[str]], Money]:
142
+ total_samples = sum([len(examples) for examples in topic_examples])
143
+ split_point = min(
144
+ math.ceil(total_samples / max(1, math.ceil(total_samples / 150))), 150
145
+ )
146
+
147
+ batch: list[list[str]] = []
148
+
149
+ results: list[Optional[str]] = []
150
+ cost = Money(amount=0, currency="USD")
151
+ for examples in topic_examples:
152
+ batch.append(examples)
153
+ batch_len = sum([len(examples) for examples in batch])
154
+
155
+ if batch_len >= split_point:
156
+ try:
157
+ result, cost_ = generate_topic_names(litellm_params, batch, existing)
158
+ cost["amount"] += cost_["amount"]
159
+ results += result
160
+ except Exception as e:
161
+ logger.error("Failed to generate topic names for batch", batch_size=len(batch), error=str(e))
162
+ results += [None] * len(batch)
163
+ batch = []
164
+
165
+ if len(batch) > 0:
166
+ try:
167
+ result, cost_ = generate_topic_names(litellm_params, batch, existing)
168
+ cost["amount"] += cost_["amount"]
169
+ results += result
170
+ except Exception as e:
171
+ logger.error("Failed to generate topic names for final batch", batch_size=len(batch), error=str(e))
172
+ results += [None] * len(batch)
173
+
174
+ return results, cost
175
+
176
+
177
+ @retry(wait=wait_exponential(min=12, max=60), stop=stop_after_attempt(2), reraise=True)
178
+ def generate_topic_names_split_and_improve_similar_names(
179
+ litellm_params: dict[str, str],
180
+ embeddings_litellm_params: dict[str, str],
181
+ topic_examples: list[list[str]],
182
+ existing: Optional[list[str]] = None,
183
+ ) -> tuple[list[Optional[str]], Money]:
184
+ topic_names, cost1 = generate_topic_names_split(
185
+ litellm_params,
186
+ topic_examples=topic_examples,
187
+ existing=existing,
188
+ )
189
+ topic_names, cost2 = improve_similar_names(
190
+ litellm_params,
191
+ embeddings_litellm_params,
192
+ topic_names=topic_names,
193
+ topic_examples=topic_examples,
194
+ max_iterations=3,
195
+ )
196
+ return topic_names, Money(amount=cost1["amount"] + cost2["amount"], currency="USD")
197
+
198
+
199
+ def improve_similar_names(
200
+ litellm_params: dict[str, str],
201
+ embeddings_litellm_params: dict[str, str],
202
+ topic_names: list[Optional[str]],
203
+ topic_examples: list[list[str]],
204
+ cost=Money(amount=0, currency="USD"),
205
+ iteration=0,
206
+ max_iterations=3,
207
+ ) -> tuple[list[Optional[str]], Money]:
208
+
209
+ if len(topic_names) != len(topic_examples):
210
+ raise ValueError("topic_names and topic_examples must have the same length.")
211
+
212
+ names = [name if name else "" for name in topic_names]
213
+ embeddings = generate_embeddings(names, embeddings_litellm_params)
214
+
215
+ # find the two closest embeddings
216
+ closest_distance = float("inf")
217
+ closest_pair = None
218
+ for i, embedding_a in enumerate(embeddings):
219
+ for j, embedding_b in enumerate(embeddings):
220
+ if embedding_a is None or embedding_b is None:
221
+ continue
222
+
223
+ if i == j or not topic_names[i] or not topic_names[j]:
224
+ continue
225
+ # calculate cosine distance
226
+ distance = 1 - np.dot(embedding_a, embedding_b) / (
227
+ np.linalg.norm(embedding_a) * np.linalg.norm(embedding_b)
228
+ )
229
+ if distance < closest_distance:
230
+ closest_distance = distance
231
+ closest_pair = (i, j)
232
+
233
+ if closest_distance > 0.6 or not closest_pair:
234
+ logger.info("No similar names found, stopping improvement", iteration=iteration + 1)
235
+ return topic_names, cost
236
+
237
+ topic_a_index, topic_b_index = closest_pair
238
+ topic_a_name = topic_names[topic_a_index]
239
+ topic_b_name = topic_names[topic_b_index]
240
+ topic_a_examples = topic_examples[topic_a_index]
241
+ topic_b_examples = topic_examples[topic_b_index]
242
+
243
+ logger.info(
244
+ "Improving similar names",
245
+ iteration=iteration + 1,
246
+ topic_a_name=topic_a_name,
247
+ topic_a_examples=len(topic_a_examples),
248
+ topic_b_name=topic_b_name,
249
+ topic_b_examples=len(topic_b_examples),
250
+ cosine_distance=round(closest_distance, 3),
251
+ )
252
+
253
+ new_topic_a_name, new_topic_b_name, cost_ = improve_name_between_two_topics(
254
+ litellm_params,
255
+ topic_a_name,
256
+ topic_b_name,
257
+ topic_a_examples,
258
+ topic_b_examples,
259
+ )
260
+
261
+ topic_names_ = topic_names.copy()
262
+ topic_names_[topic_a_index] = new_topic_a_name
263
+ topic_names_[topic_b_index] = new_topic_b_name
264
+
265
+ cost__ = Money(amount=cost["amount"] + cost_["amount"], currency="USD")
266
+
267
+ iteration_ = iteration + 1
268
+ if iteration_ < max_iterations:
269
+ return improve_similar_names(
270
+ litellm_params,
271
+ embeddings_litellm_params,
272
+ topic_names=topic_names_,
273
+ topic_examples=topic_examples,
274
+ cost=cost__,
275
+ iteration=iteration_,
276
+ max_iterations=max_iterations,
277
+ )
278
+
279
+ return topic_names_, cost__
280
+
281
+
282
+ def improve_name_between_two_topics(
283
+ litellm_params: dict[str, str],
284
+ topic_a_name: Optional[str],
285
+ topic_b_name: Optional[str],
286
+ topic_a_examples: list[str],
287
+ topic_b_examples: list[str],
288
+ ) -> tuple[Optional[str], Optional[str], Money]:
289
+ if topic_a_name is None or topic_b_name is None:
290
+ return topic_a_name, topic_b_name, Money(amount=0, currency="USD")
291
+
292
+ topic_examples_str = (
293
+ (f"# Topic A: {topic_a_name}\n\n" + "\n".join(topic_a_examples))
294
+ + f"\n\n# Topic B: {topic_b_name}\n\n"
295
+ + "\n".join(topic_b_examples)
296
+ )
297
+
298
+ try:
299
+ response = litellm.completion(
300
+ temperature=0.0,
301
+ messages=[
302
+ {
303
+ "role": "system",
304
+ "content": f"You are a highly knowledgeable assistant tasked with taxonomy for naming topics, \
305
+ right now we have two topics with very similar names, and we need to disambiguate between them, \
306
+ to have a better name that really contrasts what one topic is about versus the other. \
307
+ Please look at the topics A and B and come up with a new, concise but constrasting name for each, \
308
+ based on their examples.",
309
+ },
310
+ {"role": "user", "content": f"{topic_examples_str}"},
311
+ ],
312
+ tools=[
313
+ {
314
+ "type": "function",
315
+ "function": {
316
+ "name": "topicNames",
317
+ "parameters": {
318
+ "type": "object",
319
+ "properties": {
320
+ "topic_a": {"type": "string"},
321
+ "topic_b": {"type": "string"},
322
+ },
323
+ },
324
+ "description": 'use this function to name the topics based on the examples provided, avoid using "and" or "&" in the name, try to name it with a single 2-3 words concept.',
325
+ },
326
+ }
327
+ ],
328
+ tool_choice={"type": "function", "function": {"name": "topicNames"}},
329
+ **litellm_params, # type: ignore
330
+ )
331
+ except Exception as e:
332
+ logger.error(
333
+ "Failed to improve names between topics",
334
+ topic_a_name=topic_a_name,
335
+ topic_b_name=topic_b_name,
336
+ error=str(e),
337
+ )
338
+ raise ValueError(
339
+ f"Failed to improve names between {topic_a_name} and {topic_b_name}: {e}\n\nTopic examples: {topic_examples_str}\n\n. Error: {e}"
340
+ )
341
+
342
+ total_cost = completion_cost(response)
343
+
344
+ arguments = json.loads(response.choices[0].message.tool_calls[0].function.arguments) # type: ignore
345
+ new_topic_a_name = arguments["topic_a"]
346
+ new_topic_b_name = arguments["topic_b"]
347
+
348
+ logger.info("Generated new disambiguated names", new_topic_a_name=new_topic_a_name, new_topic_b_name=new_topic_b_name)
349
+
350
+ return new_topic_a_name, new_topic_b_name, Money(amount=total_cost, currency="USD")
351
+
352
+
353
+ def generate_topic_and_subtopic_names(
354
+ model: str,
355
+ litellm_params: dict[str, str],
356
+ embeddings_litellm_params: dict[str, str],
357
+ hierarchy: dict[str, dict[str, list[Trace]]],
358
+ existing: Optional[list[str]] = None,
359
+ skip_topic_names: bool = False,
360
+ ) -> tuple[list[Optional[str]], list[list[Optional[str]]], Money]:
361
+ total_topics = len(hierarchy)
362
+ total_subtopics = sum(len(subtopics) for subtopics in hierarchy.values())
363
+ logger.info("Starting name generation", total_topics=total_topics, total_subtopics=total_subtopics)
364
+
365
+ with ThreadPoolExecutor() as executor:
366
+ cost = Money(amount=0, currency="USD")
367
+ topic_examples = [
368
+ shuffled(
369
+ [
370
+ item
371
+ for samples in subtopics.values()
372
+ for item in get_subtopic_samples(samples, n=5)
373
+ ]
374
+ )[0:30]
375
+ for subtopics in hierarchy.values()
376
+ ]
377
+
378
+ def noop_topic_names(
379
+ litellm_params: dict[str, str],
380
+ embeddings_litellm_params: dict[str, str],
381
+ topic_examples: list[list[str]],
382
+ existing: Optional[list[str]] = None,
383
+ ) -> tuple[list[Optional[str]], Money]:
384
+ return list(hierarchy.keys()), Money(amount=0, currency="USD")
385
+
386
+ logger.info("Submitting topic naming task")
387
+ topic_future = executor.submit(
388
+ contextvars.copy_context().run,
389
+ (
390
+ noop_topic_names
391
+ if skip_topic_names
392
+ else generate_topic_names_split_and_improve_similar_names
393
+ ),
394
+ litellm_params,
395
+ embeddings_litellm_params,
396
+ topic_examples,
397
+ existing=existing,
398
+ )
399
+
400
+ subtopic_names = []
401
+ futures: list[Future[tuple[list[Optional[str]], Money]]] = []
402
+
403
+ logger.info("Submitting subtopic naming tasks", task_count=total_topics)
404
+ for subtopics in hierarchy.values():
405
+ subtopic_samples = [
406
+ get_subtopic_samples(samples, n=20) for samples in subtopics.values()
407
+ ]
408
+ future = executor.submit(
409
+ contextvars.copy_context().run,
410
+ generate_topic_names_split_and_improve_similar_names,
411
+ litellm_params,
412
+ embeddings_litellm_params,
413
+ subtopic_samples,
414
+ existing,
415
+ )
416
+ futures.append(future)
417
+
418
+ logger.info("Waiting for topic names to complete")
419
+ topic_names, cost_ = topic_future.result()
420
+ cost["amount"] += cost_["amount"]
421
+ logger.info("Topic names complete", names_generated=len(topic_names))
422
+
423
+ logger.info("Waiting for subtopic names to complete", task_count=len(futures))
424
+ for idx, future in enumerate(futures):
425
+ subtopic_names_, cost_ = future.result()
426
+ cost["amount"] += cost_["amount"]
427
+ subtopic_names.append(subtopic_names_)
428
+ if (idx + 1) % 5 == 0 or idx == len(futures) - 1:
429
+ logger.info("Subtopic naming progress", topics_processed=idx + 1, total_topics=len(futures))
430
+
431
+ logger.info("Name generation complete", topic_count=len(topic_names))
432
+ return topic_names, subtopic_names, cost
@@ -0,0 +1,42 @@
1
+ from typing import Literal, Optional
2
+ from typing_extensions import TypedDict
3
+
4
+
5
+ class Trace(TypedDict):
6
+ trace_id: str
7
+ input: str
8
+ topic_id: Optional[str]
9
+ subtopic_id: Optional[str]
10
+
11
+
12
+ class TraceWithEmbeddings(Trace):
13
+ embeddings: list[float]
14
+
15
+
16
+ class Topic(TypedDict):
17
+ id: str
18
+ name: str
19
+ centroid: list[float]
20
+ p95_distance: float
21
+
22
+
23
+ class Subtopic(Topic):
24
+ parent_id: str
25
+
26
+
27
+ class TraceTopicMap(TypedDict):
28
+ trace_id: str
29
+ topic_id: Optional[str]
30
+ subtopic_id: Optional[str]
31
+
32
+
33
+ class Money(TypedDict):
34
+ amount: float
35
+ currency: Literal["USD"]
36
+
37
+
38
+ class TopicClusteringResponse(TypedDict):
39
+ topics: list[Topic]
40
+ subtopics: list[Subtopic]
41
+ traces: list[TraceTopicMap]
42
+ cost: Money
@@ -0,0 +1,191 @@
1
+ from typing import Optional
2
+ import contextvars
3
+ import litellm
4
+ import numpy as np
5
+ from scipy.spatial.distance import cdist
6
+ import concurrent.futures
7
+
8
+ from langevals_topic_clustering.types import Trace, TraceWithEmbeddings
9
+ from langevals_topic_clustering._logger import get_logger
10
+
11
+ logger = get_logger("topic_clustering.utils")
12
+
13
+
14
+ def calculate_centroid_and_distance(samples) -> tuple[np.ndarray, float]:
15
+ centroid = np.mean([np.array(item["embeddings"]) for item in samples], axis=0)
16
+ distances = cdist(
17
+ [np.array(item["embeddings"]) for item in samples],
18
+ np.array([centroid]),
19
+ "cosine",
20
+ ).flatten()
21
+ p95_distance = np.percentile(distances, 95).astype(float)
22
+
23
+ return centroid, p95_distance
24
+
25
+
26
+ def normalize_embedding_dimensions(
27
+ embedding: list[float], target_dim: int = 1536
28
+ ) -> list[float]:
29
+ if len(embedding) == target_dim:
30
+ return embedding
31
+
32
+ if len(embedding) < target_dim:
33
+ return embedding + [0.0] * (target_dim - len(embedding))
34
+
35
+ return embedding[:target_dim]
36
+
37
+
38
+ def _generate_single_embedding(
39
+ text: str,
40
+ embeddings_litellm_params: dict[str, str],
41
+ dimensions: int
42
+ ) -> Optional[list[float]]:
43
+ """Generate embedding for a single text item with proper error handling."""
44
+ try:
45
+ text_to_embed = text if text else "<empty>"
46
+ response = litellm.embedding(
47
+ **embeddings_litellm_params, # type: ignore
48
+ input=text_to_embed,
49
+ )
50
+ return normalize_embedding_dimensions(
51
+ response.data[0]["embedding"],
52
+ target_dim=dimensions,
53
+ )
54
+ except Exception as e:
55
+ logger.warning("Error generating single embedding", error=str(e), text_preview=text[:100])
56
+ raise e # Re-raise the exception to be handled by the caller
57
+
58
+
59
+ def generate_embeddings_threaded(
60
+ texts: list[str],
61
+ embeddings_litellm_params: dict[str, str],
62
+ max_workers: int = 8
63
+ ) -> list[Optional[list[float]]]:
64
+ """Generate embeddings in parallel using ThreadPoolExecutor."""
65
+ dimensions = int(embeddings_litellm_params.get("dimensions", 1536))
66
+ params_copy = embeddings_litellm_params.copy()
67
+ if "dimensions" in params_copy:
68
+ del params_copy["dimensions"]
69
+
70
+ embeddings: list[Optional[list[float]]] = []
71
+ errors = 0
72
+ last_error: Optional[Exception] = None
73
+
74
+ # Process in smaller chunks to handle errors properly
75
+ chunk_size = 20
76
+ total_chunks = (len(texts) + chunk_size - 1) // chunk_size
77
+ logger.info("Generating embeddings (threaded)", text_count=len(texts), chunk_count=total_chunks)
78
+
79
+ for chunk_idx, i in enumerate(range(0, len(texts), chunk_size)):
80
+ chunk = texts[i:i + chunk_size]
81
+ futures = []
82
+
83
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
84
+ # Submit all tasks, propagating log context to threads
85
+ for text in chunk:
86
+ ctx = contextvars.copy_context()
87
+ futures.append(executor.submit(ctx.run, _generate_single_embedding, text, params_copy, dimensions))
88
+
89
+ # Process results as they complete
90
+ for future in futures:
91
+ try:
92
+ result = future.result()
93
+ embeddings.append(result)
94
+ except Exception as e:
95
+ embeddings.append(None)
96
+ errors += 1
97
+ last_error = e
98
+ logger.warning("Error generating embedding", error=str(e))
99
+ if errors >= 3:
100
+ logger.error("Too many errors generating embeddings, reraising", error_count=errors)
101
+ raise e
102
+
103
+ if (chunk_idx + 1) % 5 == 0 or chunk_idx == total_chunks - 1:
104
+ logger.info("Embeddings progress (threaded)", chunks_processed=chunk_idx + 1, total_chunks=total_chunks)
105
+
106
+ if last_error and errors == len(texts):
107
+ logger.error("All embeddings failed to generate, reraising last error", error_count=errors, error=str(last_error))
108
+ raise last_error
109
+
110
+ return embeddings
111
+
112
+
113
+ def generate_embeddings(
114
+ texts: list[str], embeddings_litellm_params: dict[str, str], batch_size: int = 20
115
+ ) -> list[Optional[list[float]]]:
116
+ embeddings = []
117
+ errors = 0
118
+ last_error: Optional[Exception] = None
119
+ batches = list(range(0, len(texts), batch_size))
120
+ total_batches = len(batches)
121
+
122
+ dimensions = int(embeddings_litellm_params.get("dimensions", 1536))
123
+ params_copy = embeddings_litellm_params.copy()
124
+ if "dimensions" in params_copy:
125
+ # TODO: target_dim is throwing errors for text-embedding-3-small because litellm drop_params is also not working for some reason
126
+ del params_copy["dimensions"]
127
+
128
+ logger.info("Generating embeddings", text_count=len(texts), batch_count=total_batches)
129
+
130
+ for batch_idx, i in enumerate(batches):
131
+ batch = [t if t else "<empty>" for t in texts[i : i + batch_size]]
132
+ try:
133
+ response = litellm.embedding(
134
+ **params_copy, # type: ignore
135
+ input=batch if batch_size > 1 else batch[0],
136
+ )
137
+ embeddings += [
138
+ normalize_embedding_dimensions(
139
+ item["embedding"],
140
+ target_dim=dimensions,
141
+ )
142
+ for item in response.data
143
+ ]
144
+ except Exception as e:
145
+ if batch_size > 1:
146
+ # Don't fallback for auth errors — same key will fail for every individual request
147
+ if isinstance(e, litellm.exceptions.AuthenticationError):
148
+ logger.warning("Embedding authentication failed, not retrying", error=str(e))
149
+ raise
150
+ # For other errors, fall back to threaded implementation
151
+ logger.info("Batch embedding failed, falling back to threaded implementation")
152
+ return generate_embeddings_threaded(texts, embeddings_litellm_params)
153
+
154
+ embeddings += [None] * batch_size
155
+
156
+ errors += 1
157
+ last_error = e
158
+ logger.warning("Error generating embeddings", error=str(e), batch_preview=batch[:3])
159
+ if errors >= 3:
160
+ logger.error("Too many errors generating embeddings, reraising", error_count=errors)
161
+ raise e
162
+
163
+ # Log progress every 5 batches or at the end
164
+ if (batch_idx + 1) % 5 == 0 or batch_idx == total_batches - 1:
165
+ logger.info("Embeddings progress", batches_processed=batch_idx + 1, total_batches=total_batches, embeddings_generated=len(embeddings), total_texts=len(texts))
166
+
167
+ if last_error and errors == len(batches):
168
+ logger.error("All embeddings failed to generate, reraising last error", error_count=errors, error=str(last_error))
169
+ raise last_error
170
+
171
+ return embeddings
172
+
173
+
174
+ def fill_embeddings(
175
+ traces: list[Trace], embeddings_litellm_params: dict[str, str]
176
+ ) -> list[TraceWithEmbeddings]:
177
+ traces_ = [t for t in traces if t["input"] and len(t["input"].strip()) > 0]
178
+ embeddings = generate_embeddings(
179
+ [t["input"] for t in traces_], embeddings_litellm_params
180
+ )
181
+ return [
182
+ TraceWithEmbeddings(
183
+ trace_id=trace["trace_id"],
184
+ input=trace["input"],
185
+ embeddings=embedding,
186
+ topic_id=trace["topic_id"],
187
+ subtopic_id=trace["subtopic_id"],
188
+ )
189
+ for trace, embedding in zip(traces_, embeddings)
190
+ if embedding is not None
191
+ ]