@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
@@ -24,6 +24,7 @@ import { prisma } from "../db";
24
24
  import { esClient, TRACE_INDEX, traceIndexId } from "../elasticsearch";
25
25
  import { getProjectEmbeddingsModel } from "../embeddings";
26
26
  import { getPayloadSizeHistogram } from "../metrics";
27
+ import { isNlpGoEnabled } from "../nlpgo/nlpgoFetch";
27
28
  import type { ElasticSearchTrace, Trace } from "../tracer/types";
28
29
  import type {
29
30
  BatchClusteringParams,
@@ -827,11 +828,34 @@ export const storeResults = async (
827
828
  }
828
829
  };
829
830
 
831
+ /**
832
+ * Resolve which service hosts topic clustering for the given project. When
833
+ * `release_nlp_go_engine_enabled` is on, route to langevals (the new
834
+ * workspace member at langevals/evaluators/topic_clustering — see
835
+ * specs/nlp-go/_shared/contract.md §11). When off, the legacy langwatch_nlp
836
+ * path is used unchanged.
837
+ *
838
+ * Returns `null` if neither endpoint is configured for the resolved engine —
839
+ * caller should warn-and-skip in that case.
840
+ */
841
+ const resolveTopicClusteringEndpoint = async (
842
+ projectId: string,
843
+ ): Promise<{ baseUrl: string; engine: "langevals" | "langwatch_nlp" } | null> => {
844
+ const goEnabled = await isNlpGoEnabled({ projectId });
845
+ if (goEnabled) {
846
+ if (!env.LANGEVALS_ENDPOINT) return null;
847
+ return { baseUrl: env.LANGEVALS_ENDPOINT, engine: "langevals" };
848
+ }
849
+ if (!env.TOPIC_CLUSTERING_SERVICE) return null;
850
+ return { baseUrl: env.TOPIC_CLUSTERING_SERVICE, engine: "langwatch_nlp" };
851
+ };
852
+
830
853
  export const fetchTopicsBatchClustering = async (
831
854
  projectId: string,
832
855
  params: BatchClusteringParams,
833
856
  ): Promise<TopicClusteringResponse | undefined> => {
834
- if (!env.TOPIC_CLUSTERING_SERVICE) {
857
+ const endpoint = await resolveTopicClusteringEndpoint(projectId);
858
+ if (!endpoint) {
835
859
  logger.warn(
836
860
  { projectId },
837
861
  "Topic clustering service URL not set, skipping topic clustering",
@@ -843,12 +867,12 @@ export const fetchTopicsBatchClustering = async (
843
867
  getPayloadSizeHistogram("topic_clustering_batch").observe(size);
844
868
 
845
869
  logger.info(
846
- { sizeMb: size / 125000, projectId },
870
+ { sizeMb: size / 125000, projectId, engine: endpoint.engine },
847
871
  "uploading traces data for project",
848
872
  );
849
873
 
850
874
  const response = await fetchHTTP2(
851
- `${env.TOPIC_CLUSTERING_SERVICE}/topics/batch_clustering`,
875
+ `${endpoint.baseUrl}/topics/batch_clustering`,
852
876
  { method: "POST", json: params },
853
877
  );
854
878
 
@@ -863,7 +887,7 @@ export const fetchTopicsBatchClustering = async (
863
887
  /* this is just a safe json parse fallback */
864
888
  }
865
889
  throw new Error(
866
- `Failed to fetch topics batch clustering: ${response.statusText}\n\n${body}`,
890
+ `Failed to fetch topics batch clustering (${endpoint.engine}): ${response.statusText}\n\n${body}`,
867
891
  );
868
892
  }
869
893
 
@@ -876,7 +900,8 @@ export const fetchTopicsIncrementalClustering = async (
876
900
  projectId: string,
877
901
  params: IncrementalClusteringParams,
878
902
  ): Promise<TopicClusteringResponse | undefined> => {
879
- if (!env.TOPIC_CLUSTERING_SERVICE) {
903
+ const endpoint = await resolveTopicClusteringEndpoint(projectId);
904
+ if (!endpoint) {
880
905
  logger.warn(
881
906
  { projectId },
882
907
  "Topic clustering service URL not set, skipping topic clustering",
@@ -888,12 +913,12 @@ export const fetchTopicsIncrementalClustering = async (
888
913
  getPayloadSizeHistogram("topic_clustering_incremental").observe(size);
889
914
 
890
915
  logger.info(
891
- { sizeMb: size / 125000, projectId },
916
+ { sizeMb: size / 125000, projectId, engine: endpoint.engine },
892
917
  "uploading traces data for project",
893
918
  );
894
919
 
895
920
  const response = await fetchHTTP2(
896
- `${env.TOPIC_CLUSTERING_SERVICE}/topics/incremental_clustering`,
921
+ `${endpoint.baseUrl}/topics/incremental_clustering`,
897
922
  { method: "POST", json: params },
898
923
  );
899
924
 
@@ -909,7 +934,7 @@ export const fetchTopicsIncrementalClustering = async (
909
934
  }
910
935
 
911
936
  throw new Error(
912
- `Failed to fetch topics incremental clustering: ${response.statusText}\n\n${body}`,
937
+ `Failed to fetch topics incremental clustering (${endpoint.engine}): ${response.statusText}\n\n${body}`,
913
938
  );
914
939
  }
915
940
 
@@ -1,14 +1,13 @@
1
1
  import type { Node } from "@xyflow/react";
2
2
  import { nanoid } from "nanoid";
3
3
  import { addEnvs } from "../../optimization_studio/server/addEnvs";
4
- import { getProjectLambdaArn } from "../../optimization_studio/server/lambda";
5
4
  import type {
6
5
  ExecutionStatus,
7
6
  Workflow,
8
7
  } from "../../optimization_studio/types/dsl";
9
8
  import type { StudioClientEvent } from "../../optimization_studio/types/events";
10
9
  import { getEntryInputs } from "../../optimization_studio/utils/nodeUtils";
11
- import { lambdaFetch } from "../../utils/lambdaFetch";
10
+ import { nlpgoFetch, type NLPOrigin } from "../nlpgo/nlpgoFetch";
12
11
  import { getProjectModelProviders } from "../api/routers/modelProviders.utils";
13
12
  import { prisma } from "../db";
14
13
  import type { SingleEvaluationResult } from "../evaluations/evaluators.generated";
@@ -118,6 +117,7 @@ export async function runEvaluationWorkflow(
118
117
  versionId,
119
118
  true, // do_not_trace
120
119
  false, // run_evaluations - disable evaluators inside the workflow when running as an online evaluation
120
+ "evaluation",
121
121
  );
122
122
 
123
123
  // Process the result
@@ -161,6 +161,7 @@ export async function runWorkflow(
161
161
  versionId?: string,
162
162
  do_not_trace?: boolean,
163
163
  run_evaluations?: boolean,
164
+ origin: NLPOrigin = "workflow",
164
165
  ) {
165
166
  const workflow = await prisma.workflow.findUnique({
166
167
  where: { id: workflowId, projectId },
@@ -209,24 +210,20 @@ export async function runWorkflow(
209
210
  ? inputs.do_not_trace
210
211
  : false,
211
212
  ...(typeof run_evaluations === "boolean" && { run_evaluations }),
212
- origin: "workflow",
213
+ origin,
213
214
  },
214
215
  };
215
216
 
216
217
  const event = await addEnvs(messageWithoutEnvs, projectId);
217
- const functionArn = process.env.LANGWATCH_NLP_LAMBDA_CONFIG
218
- ? await getProjectLambdaArn(projectId)
219
- : process.env.LANGWATCH_NLP_SERVICE!;
220
218
 
221
- const response = await lambdaFetch<{
219
+ const response = await nlpgoFetch<{
222
220
  result: any;
223
221
  status: ExecutionStatus;
224
- }>(functionArn, "/studio/execute_sync", {
225
- method: "POST",
226
- headers: {
227
- "Content-Type": "application/json",
228
- },
229
- body: JSON.stringify(event),
222
+ }>({
223
+ projectId,
224
+ path: "/studio/execute_sync",
225
+ body: event,
226
+ origin,
230
227
  });
231
228
 
232
229
  if (!response.ok) {
@@ -70,7 +70,31 @@ async def execute_component(event: ExecuteComponentPayload):
70
70
  forward_inputs = event.inputs
71
71
  else:
72
72
  forward_inputs = autoparse_fields(node.data.inputs or [], event.inputs) # type: ignore
73
- result = await dspy.asyncify(instance)(
73
+ # PR #3543 back-compat: the parser accepts plain classes
74
+ # with `forward(...)` only (no __call__ and no dspy.Module
75
+ # base). Such classes aren't directly callable —
76
+ # `dspy.asyncify(instance)(...)` would TypeError. Fall back
77
+ # to `instance.forward` when `instance` isn't callable;
78
+ # mirrors the priority-3 path in the Go runner
79
+ # (services/nlpgo/.../codeblock/runner.py). dspy.Module
80
+ # subclasses always have __call__ so they hit the fast
81
+ # path unchanged.
82
+ #
83
+ # `callable(invoke_target)` covers both legs of the failure
84
+ # surface: missing-attribute (`getattr` default = None,
85
+ # `callable(None)` is False) AND non-callable-attribute
86
+ # (e.g. a string class attribute named `forward`). Either
87
+ # case raises a typed error here so the operator sees a
88
+ # message naming the class instead of asyncify's
89
+ # less-informative 'object is not callable'.
90
+ invoke_target = instance if callable(instance) else getattr(instance, "forward", None)
91
+ if not callable(invoke_target):
92
+ raise TypeError(
93
+ f"Class '{class_name}' for component {node.data.name} "
94
+ f"has no callable entrypoint. Define __call__(self, ...) "
95
+ f"or forward(self, ...) on the class."
96
+ )
97
+ result = await dspy.asyncify(invoke_target)(
74
98
  **forward_inputs
75
99
  )
76
100
 
@@ -1,3 +1,4 @@
1
+ import ast
1
2
  from contextlib import contextmanager, redirect_stdout
2
3
  import copy
3
4
  import io
@@ -194,6 +195,112 @@ def _assert_signature_field_types_are_mapped(node: Node) -> None:
194
195
  )
195
196
 
196
197
 
198
+ def _is_dspy_module_base(base: ast.expr) -> bool:
199
+ """True if ``base`` is the AST node ``dspy.Module``.
200
+
201
+ Used by _resolve_code_class_name to detect the legacy preferred
202
+ shape via AST instead of regex — regex over raw source can match
203
+ `class Fake:` inside a comment or docstring and pick the wrong
204
+ name; AST sees only real class declarations.
205
+ """
206
+ return (
207
+ isinstance(base, ast.Attribute)
208
+ and isinstance(base.value, ast.Name)
209
+ and base.value.id == "dspy"
210
+ and base.attr == "Module"
211
+ )
212
+
213
+
214
+ def _top_level_class_defs(code: str) -> list[ast.ClassDef]:
215
+ """Return top-level ``ast.ClassDef`` nodes in user-supplied code.
216
+
217
+ Returns an empty list on syntax errors so the caller can surface
218
+ a clean "no class definition found" error rather than letting
219
+ SyntaxError propagate from this discovery step (the user code
220
+ will be black-formatted later anyway, which is where actual
221
+ syntax errors get reported with a nicer message).
222
+
223
+ Top-level only: nested classes inside an entry class don't count
224
+ as candidates — the legacy regex behavior was effectively the
225
+ same (it picked whatever ``class X:`` line came first), and
226
+ customer fixtures consistently put the entry class at the top.
227
+ """
228
+ try:
229
+ tree = ast.parse(code)
230
+ except SyntaxError:
231
+ return []
232
+ return [node for node in tree.body if isinstance(node, ast.ClassDef)]
233
+
234
+
235
+ def _resolve_code_class_name(
236
+ code: str, node_name: str | None, kind: str = "component"
237
+ ) -> str:
238
+ """Pick the user-defined class to instantiate from ``code``.
239
+
240
+ Resolution order matches the **class-based** shapes the Go runtime
241
+ accepts (services/nlpgo/app/engine/blocks/codeblock/runner.py), so
242
+ the same customer code runs identically on FF=on and FF=off:
243
+
244
+ 1. ``class X(dspy.Module):`` (or any class whose bases include
245
+ ``dspy.Module``) — preferred (legacy default; the dspy.Module
246
+ wrapper provides cost-tracing + tracking).
247
+ 2. ``class X:`` matching the node's display name (after
248
+ normalization to a class identifier) — picks the right class
249
+ when the user defines helpers alongside the entry class.
250
+ 3. First top-level ``class X:`` declaration in the file.
251
+
252
+ The Go runtime ALSO accepts a fourth shape — a top-level ``def
253
+ execute(**inputs)`` callable with no enclosing class — but that
254
+ shape is intentionally NOT supported on the Python side. This
255
+ parser is a class-name extractor (the resolved name is later passed
256
+ to ``getattr(module, class_name)``); a top-level function has no
257
+ class to extract. Source with a top-level ``execute`` and no class
258
+ raises a clear ValueError listing the supported shapes. If parity
259
+ is ever needed, swap the resolver for an importer-then-inspect flow
260
+ similar to the Go runner.
261
+
262
+ Method-level shape within the chosen class (``__call__`` vs
263
+ ``forward`` vs neither) is NOT inspected here because the source
264
+ is not yet imported. The downstream invoker
265
+ (``execute_component.py`` / ``execute_flow.py``) handles the
266
+ dispatch — ``execute_component`` falls back from ``instance(...)``
267
+ to ``instance.forward(...)`` for plain forward-only classes; see
268
+ the import-time fallback in those modules.
269
+
270
+ AST-based discovery (not regex over raw source) so commented-out
271
+ or docstring text like ``class Fake:`` can't false-match. Anchors
272
+ PR #3483's per-shape contract back-compat for FF=off so customers
273
+ using the new ``class X: def __call__(...)`` template don't error
274
+ before the FF rolls to them.
275
+ """
276
+ class_defs = _top_level_class_defs(code)
277
+
278
+ # Priority 1: any class with `dspy.Module` in its bases (handles
279
+ # both the strict `class X(dspy.Module):` and the multi-base
280
+ # `class X(dspy.Module, SomeMixin):` cases).
281
+ for cls in class_defs:
282
+ if any(_is_dspy_module_base(base) for base in cls.bases):
283
+ return cls.name
284
+
285
+ if not class_defs:
286
+ raise ValueError(
287
+ f"Could not find a class definition for {kind} {node_name}. "
288
+ f"Supported shapes: dspy.Module subclass, class with __call__, "
289
+ f"or class with forward()."
290
+ )
291
+
292
+ # Priority 2: name-disambiguation against the (normalized) node
293
+ # name when multiple candidate classes exist.
294
+ if node_name:
295
+ target = normalize_name_to_class_name(node_name)
296
+ for cls in class_defs:
297
+ if cls.name == target:
298
+ return cls.name
299
+
300
+ # Priority 3: first top-level class declaration.
301
+ return class_defs[0].name
302
+
303
+
197
304
  def parse_component(
198
305
  node: Node, workflow: Workflow, standalone=False, format=False, debug_level=0
199
306
  ) -> Tuple[str, str, Dict[str, Any]]:
@@ -280,14 +387,7 @@ def parse_component(
280
387
  f"Code node has no source content for component {node.data.name}"
281
388
  )
282
389
 
283
- pattern = r"class (.*?)\(dspy\.Module\):"
284
- match = re.search(pattern, code)
285
- if not match:
286
- raise ValueError(
287
- f"Could not find a class that inherits from dspy.Module for component {node.data.name}"
288
- )
289
-
290
- class_name = match.group(1)
390
+ class_name = _resolve_code_class_name(code, node.data.name)
291
391
  try:
292
392
  code = black.format_str(code, mode=black.Mode())
293
393
  except Exception as e:
@@ -366,13 +466,9 @@ def parse_component(
366
466
  raise ValueError(
367
467
  f"Code not specified for agent {node.data.name}"
368
468
  )
369
- pattern = r"class (.*?)\(dspy\.Module\):"
370
- match_result = re.search(pattern, code)
371
- if not match_result:
372
- raise ValueError(
373
- f"Could not find a class that inherits from dspy.Module for agent {node.data.name}"
374
- )
375
- class_name = match_result.group(1)
469
+ class_name = _resolve_code_class_name(
470
+ code, node.data.name, kind="agent"
471
+ )
376
472
  try:
377
473
  code = black.format_str(code, mode=black.Mode())
378
474
  except Exception as e:
@@ -403,7 +499,16 @@ def parse_component(
403
499
  @contextmanager
404
500
  def materialized_component_class(
405
501
  component_code: str, class_name: str
406
- ) -> Generator[Type[dspy.Module], None, None]:
502
+ ) -> Generator[Type[Any], None, None]:
503
+ """Materialize a user-defined class from ``component_code`` and yield it.
504
+
505
+ Return type is ``Type[Any]`` (was ``Type[dspy.Module]``) because the
506
+ Code node now also accepts plain ``class X: def __call__(...)`` and
507
+ ``class X: def forward(...)`` shapes — the caller uses Python's
508
+ normal ``instance(**inputs)`` invocation, which dispatches to
509
+ ``__call__`` if defined and otherwise hits whatever Module subclass
510
+ the legacy dspy path expects.
511
+ """
407
512
  temp_folder = tempfile.mkdtemp()
408
513
  sys.path.insert(0, temp_folder)
409
514
 
@@ -50,40 +50,44 @@ def generate_topic_names(
50
50
  else ""
51
51
  )
52
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
+
53
85
  try:
54
86
  response = litellm.completion(
55
87
  temperature=0.0,
56
- messages=[
57
- {
58
- "role": "system",
59
- "content": f'You are a highly knowledgeable assistant tasked with taxonomy for naming topics \
60
- based on a list of examples. Provide a single, descriptive name for each topic. \
61
- Avoid using "and" or "&" in the name, try to summarize it with a single concept. \
62
- Topic names should not be similar to each other, as the data is already organized, \
63
- the disambiguation between two similar topics should be clear from the name alone.\
64
- {existing_message}',
65
- },
66
- {"role": "user", "content": f"{topic_examples_str}"},
67
- ],
68
- tools=[
69
- {
70
- "type": "function",
71
- "function": {
72
- "name": "topicNames",
73
- "parameters": {
74
- "type": "object",
75
- "properties": dict(
76
- [
77
- (f"topic_{index}", {"type": "string"})
78
- for index in range(len(topic_examples))
79
- ]
80
- ),
81
- },
82
- "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.',
83
- },
84
- }
85
- ],
86
- tool_choice={"type": "function", "function": {"name": "topicNames"}},
88
+ messages=messages,
89
+ tools=tools,
90
+ tool_choice=tool_choice,
87
91
  **litellm_params, # type: ignore
88
92
  )
89
93
  except Exception as e:
@@ -97,8 +101,11 @@ def generate_topic_names(
97
101
  )
98
102
 
99
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
+ )
100
107
 
101
- topic_names: list[str] = list(json.loads(response.choices[0].message.tool_calls[0].function.arguments).values()) # type: ignore
108
+ topic_names: list[str] = list(topic_names_dict.values())
102
109
  topic_names = topic_names[0 : len(topic_examples)]
103
110
  if len(topic_names) != len(topic_examples):
104
111
  raise ValueError("topic_names and topic_examples must have the same length.")
@@ -0,0 +1,67 @@
1
+ #!/bin/sh
2
+ #
3
+ # Entrypoint for the langwatch_nlp container. Implements the parallel-
4
+ # deployment scheme from specs/nlp-go/_shared/contract.md §3:
5
+ #
6
+ # default: nlpgo (Go) is the front door at $PORT; spawns uvicorn as a
7
+ # child on 127.0.0.1:5561; routes /go/* itself, reverse-
8
+ # proxies everything else to uvicorn.
9
+ #
10
+ # NLPGO_BYPASS=1: emergency lever — skip nlpgo entirely and run uvicorn
11
+ # directly on $PORT. Same external surface, no Go in
12
+ # the path. Use this when nlpgo has a regression and
13
+ # we need to fail back instantly without infra changes.
14
+ #
15
+ # PORT defaults to 8080 (Lambda Adapter expectation). Dev/k8s callers can
16
+ # override (5562 on a pod, etc.).
17
+
18
+ set -e
19
+
20
+ PORT="${PORT:-8080}"
21
+ KEEP_ALIVE="${NLP_UVICORN_KEEP_ALIVE_SECONDS:-4500}"
22
+
23
+ # Bypass-mode invocation is env-overridable so the saas runtime images
24
+ # (Dockerfile.langwatch_nlp.{service,lambda}.runtime in langwatch-saas)
25
+ # can use `python -m uvicorn` instead of `uv run uvicorn` — those images
26
+ # don't ship `uv` in the runtime stage to keep the layer lean. The
27
+ # monorepo lambda image ships uv (it builds with `uv build` in the same
28
+ # image), so the defaults match its shape.
29
+ BYPASS_COMMAND="${NLPGO_BYPASS_COMMAND:-uv}"
30
+ BYPASS_ARGS="${NLPGO_BYPASS_ARGS:---no-cache run --no-sync --no-editable uvicorn langwatch_nlp.main:app --host 0.0.0.0 --timeout-keep-alive $KEEP_ALIVE}"
31
+
32
+ run_uvicorn_only() {
33
+ # The bypass invocation appends --port LAST so the args set above don't
34
+ # have to know what port to bind — the entrypoint owns that.
35
+ # shellcheck disable=SC2086 # word-splitting is intentional here
36
+ exec $BYPASS_COMMAND $BYPASS_ARGS --port "$1"
37
+ }
38
+
39
+ if [ "${NLPGO_BYPASS:-0}" = "1" ]; then
40
+ echo "[entrypoint] NLPGO_BYPASS=1 — running uvicorn directly on :$PORT"
41
+ run_uvicorn_only "$PORT"
42
+ fi
43
+
44
+ if [ ! -x /usr/local/bin/nlpgo ]; then
45
+ echo "[entrypoint] nlpgo binary missing — falling back to uvicorn on :$PORT"
46
+ run_uvicorn_only "$PORT"
47
+ fi
48
+
49
+ # nlpgo binds $PORT and spawns uvicorn at 127.0.0.1:5561 as its child.
50
+ # Configure via SERVER_ADDR (parent) and NLPGO_CHILD_* (uvicorn args).
51
+ export SERVER_ADDR=":$PORT"
52
+ export NLPGO_CHILD_COMMAND="${NLPGO_CHILD_COMMAND:-uv}"
53
+ # Space-separated, NOT comma-separated: services/nlpgo/deps.go's
54
+ # splitArgs() splits on space/tab. Original entrypoint shipped commas
55
+ # (a4de2dc95) which silently broke the uvicorn child on every container
56
+ # start — uv would see "--no-cache,run,..." as a single positional
57
+ # argument and exit 2 before serving anything. Caught smoke-testing
58
+ # the lambda image during the PR #3483 deploy pre-flight: nlpgo started
59
+ # fine, /go/* worked, but the child never came up so anything that
60
+ # fell through to legacy /studio/* /api/* paths got 502. Anchored on
61
+ # spaces here to match the deps.go contract.
62
+ export NLPGO_CHILD_ARGS="${NLPGO_CHILD_ARGS:---no-cache run --no-sync --no-editable uvicorn langwatch_nlp.main:app --host 127.0.0.1 --port 5561 --timeout-keep-alive $KEEP_ALIVE}"
63
+ export NLPGO_CHILD_HEALTH_URL="${NLPGO_CHILD_HEALTH_URL:-http://127.0.0.1:5561/health}"
64
+ export NLPGO_CHILD_UPSTREAM_URL="${NLPGO_CHILD_UPSTREAM_URL:-http://127.0.0.1:5561}"
65
+
66
+ echo "[entrypoint] nlpgo (Go) on :$PORT — uvicorn child via ${NLPGO_CHILD_UPSTREAM_URL}"
67
+ exec /usr/local/bin/nlpgo