maitai-python 1.2.33__py3-none-any.whl → 1.2.34__py3-none-any.whl

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.
maitai/_config.py CHANGED
@@ -148,6 +148,19 @@ class Config(MaitaiClient):
148
148
  action_type, config_service.get_default_config()
149
149
  )
150
150
 
151
+ def has_application_action_config(
152
+ self, application_ref_name: str, action_type: str
153
+ ) -> bool:
154
+ """Whether a real (locally-fetched) config exists for this intent.
155
+
156
+ ``get_application_action_config`` falls back to a hardcoded default when
157
+ the store is empty, so callers use this to tell "server said this model"
158
+ apart from "no config known — let the server decide".
159
+ """
160
+ return action_type in self._application_action_configs.get(
161
+ application_ref_name, {}
162
+ )
163
+
151
164
  def store_application_metadata(self, applications: List[Application]):
152
165
  for application in applications:
153
166
  for action_type in application.action_types:
maitai/_inference.py CHANGED
@@ -89,6 +89,9 @@ class Inference(MaitaiClient):
89
89
  "x-api-key": self.config.api_key,
90
90
  "User-Agent": version,
91
91
  }
92
+ client_request_id = request_dict.get("request_id")
93
+ if client_request_id:
94
+ headers["X-Request-ID"] = str(client_request_id)
92
95
 
93
96
  client = self.get_client()
94
97
 
@@ -160,6 +163,9 @@ class Inference(MaitaiClient):
160
163
  "x-api-key": self.config.api_key,
161
164
  "User-Agent": version,
162
165
  }
166
+ client_request_id = request_dict.get("request_id")
167
+ if client_request_id:
168
+ headers["X-Request-ID"] = str(client_request_id)
163
169
 
164
170
  # Log the request being made
165
171
  logger.info(f"Making inference request to {url} with timeout={timeout}")
@@ -100,6 +100,7 @@ class Completions:
100
100
  return_request: bool = False,
101
101
  push_timing_metrics: bool = True,
102
102
  from_workflow: bool = False,
103
+ request_id: Optional[str] = None,
103
104
  # OpenAI Arguments
104
105
  messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
105
106
  model: Union[str, openai_types.ChatModel, openai.NotGiven] = openai.NOT_GIVEN,
@@ -172,6 +173,9 @@ class Completions:
172
173
  if not session_id:
173
174
  session_id = str(uuid.uuid4())
174
175
  maitai_config = self.config.get_application_action_config(application, intent)
176
+ has_local_config = self.config.has_application_action_config(
177
+ application, intent
178
+ )
175
179
  if server_side_inference is None:
176
180
  server_side_inference = (
177
181
  maitai_config.inference_location == InferenceLocations.SERVER
@@ -180,7 +184,12 @@ class Completions:
180
184
  evaluation_enabled = maitai_config.evaluation_enabled
181
185
  if apply_corrections is None:
182
186
  apply_corrections = maitai_config.apply_corrections
183
- defer_to_server = from_workflow and server_side_inference
187
+ # Defer model/param selection to the server when it is doing the
188
+ # inference and we have no locally-known intent config to fill from;
189
+ # otherwise the default config's model would override the intent's.
190
+ defer_to_server = server_side_inference and (
191
+ from_workflow or not has_local_config
192
+ )
184
193
  if model == openai.NOT_GIVEN:
185
194
  if defer_to_server:
186
195
  model = None
@@ -194,7 +203,13 @@ class Completions:
194
203
  response_format = {"type": "text"}
195
204
  if max_completion_tokens and max_completion_tokens != openai.NOT_GIVEN:
196
205
  max_tokens = max_completion_tokens
197
- if not defer_to_server:
206
+ if defer_to_server:
207
+ # Do not inject SDK Config defaults (temperature=1, penalties, …).
208
+ # Send temperature=None explicitly so the backend inherits from the
209
+ # Portal intent instead of treating a missing-vs-default ambiguity.
210
+ if temperature == openai.NOT_GIVEN:
211
+ temperature = None
212
+ else:
198
213
  if temperature == openai.NOT_GIVEN:
199
214
  temperature = maitai_config.temperature
200
215
  if stop == openai.NOT_GIVEN and maitai_config.stop is not None:
@@ -286,6 +301,8 @@ class Completions:
286
301
  "return_request": return_request,
287
302
  "fallback_config": fallback_config,
288
303
  }
304
+ if request_id:
305
+ request_dict["request_id"] = request_id
289
306
 
290
307
  if from_workflow:
291
308
  request_dict["from_workflow"] = True
@@ -303,6 +320,7 @@ class Completions:
303
320
  del retry_args["self"]
304
321
  retry_args["server_side_inference"] = False
305
322
  retry_args["model"] = model
323
+ retry_args["fallback_config"] = fallback_config
306
324
  return self._process_inference_stream(
307
325
  response,
308
326
  retry_args,
@@ -611,12 +629,17 @@ class Completions:
611
629
  if not timing.time_request_end:
612
630
  timing.time_request_end = time.time()
613
631
  except MaitaiConnectionError as e:
614
- if "gpt" not in retry_args.get("model", "") and "gpt" in (
615
- retry_args.get("fallback_model", "") or ""
616
- ):
617
- retry_args["model"] = retry_args["fallback_model"]
618
- if "gpt" in retry_args.get("model", ""):
619
- retry_args["model"] = retry_args["model"].replace("openai:", "")
632
+ fallback_config = retry_args.get("fallback_config")
633
+ fallback_model = (
634
+ fallback_config.get("model")
635
+ if isinstance(fallback_config, dict)
636
+ else None
637
+ )
638
+ model = retry_args.get("model")
639
+ if "gpt" not in (model or "") and "gpt" in (fallback_model or ""):
640
+ model = fallback_model
641
+ if model and "gpt" in model:
642
+ retry_args["model"] = model.replace("openai:", "")
620
643
  response = self.create(**retry_args)
621
644
  for resp in response:
622
645
  yield resp
@@ -101,6 +101,7 @@ class AsyncCompletions:
101
101
  return_request: bool = False,
102
102
  push_timing_metrics: bool = True,
103
103
  from_workflow: bool = False,
104
+ request_id: Optional[str] = None,
104
105
  # OpenAI Arguments
105
106
  messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
106
107
  model: Union[str, openai_types.ChatModel, openai.NotGiven] = openai.NOT_GIVEN,
@@ -173,6 +174,9 @@ class AsyncCompletions:
173
174
  if not session_id:
174
175
  session_id = str(uuid.uuid4())
175
176
  maitai_config = self.config.get_application_action_config(application, intent)
177
+ has_local_config = self.config.has_application_action_config(
178
+ application, intent
179
+ )
176
180
  if server_side_inference is None:
177
181
  server_side_inference = (
178
182
  maitai_config.inference_location == InferenceLocations.SERVER
@@ -181,7 +185,12 @@ class AsyncCompletions:
181
185
  evaluation_enabled = maitai_config.evaluation_enabled
182
186
  if apply_corrections is None:
183
187
  apply_corrections = maitai_config.apply_corrections
184
- defer_to_server = from_workflow and server_side_inference
188
+ # Defer model/param selection to the server when it is doing the
189
+ # inference and we have no locally-known intent config to fill from;
190
+ # otherwise the default config's model would override the intent's.
191
+ defer_to_server = server_side_inference and (
192
+ from_workflow or not has_local_config
193
+ )
185
194
  if model == openai.NOT_GIVEN:
186
195
  if defer_to_server:
187
196
  model = None
@@ -195,7 +204,11 @@ class AsyncCompletions:
195
204
  response_format = {"type": "text"}
196
205
  if max_completion_tokens and max_completion_tokens != openai.NOT_GIVEN:
197
206
  max_tokens = max_completion_tokens
198
- if not defer_to_server:
207
+ if defer_to_server:
208
+ # Do not inject SDK Config defaults (temperature=1, penalties, …).
209
+ if temperature == openai.NOT_GIVEN:
210
+ temperature = None
211
+ else:
199
212
  if temperature == openai.NOT_GIVEN:
200
213
  temperature = maitai_config.temperature
201
214
  if stop == openai.NOT_GIVEN and maitai_config.stop is not None:
@@ -287,6 +300,8 @@ class AsyncCompletions:
287
300
  "return_request": return_request,
288
301
  "fallback_config": fallback_config,
289
302
  }
303
+ if request_id:
304
+ request_dict["request_id"] = request_id
290
305
 
291
306
  if from_workflow:
292
307
  request_dict["from_workflow"] = True
@@ -304,6 +319,7 @@ class AsyncCompletions:
304
319
  del retry_args["self"]
305
320
  retry_args["server_side_inference"] = False
306
321
  retry_args["model"] = model
322
+ retry_args["fallback_config"] = fallback_config
307
323
  return self._process_inference_stream_async(
308
324
  response,
309
325
  retry_args,
@@ -620,12 +636,17 @@ class AsyncCompletions:
620
636
  if not timing.time_request_end:
621
637
  timing.time_request_end = time.time()
622
638
  except MaitaiConnectionError as e:
623
- if "gpt" not in retry_args.get("model", "") and "gpt" in (
624
- retry_args.get("fallback_model", "") or ""
625
- ):
626
- retry_args["model"] = retry_args["fallback_model"]
627
- if "gpt" in retry_args.get("model", ""):
628
- retry_args["model"] = retry_args["model"].replace("openai:", "")
639
+ fallback_config = retry_args.get("fallback_config")
640
+ fallback_model = (
641
+ fallback_config.get("model")
642
+ if isinstance(fallback_config, dict)
643
+ else None
644
+ )
645
+ model = retry_args.get("model")
646
+ if "gpt" not in (model or "") and "gpt" in (fallback_model or ""):
647
+ model = fallback_model
648
+ if model and "gpt" in model:
649
+ retry_args["model"] = model.replace("openai:", "")
629
650
  logger.warning("Maitai issue, retrying on client side")
630
651
  response = await self.create(**retry_args)
631
652
  async for resp in response:
maitai_common/version.py CHANGED
@@ -1,3 +1,3 @@
1
- version = "1.2.33"
1
+ version = "1.2.34"
2
2
  if __name__ == "__main__":
3
3
  print(version)
@@ -0,0 +1,111 @@
1
+ # codegen: frontend
2
+
3
+ """Decision/audit log for recreating an observed external agent as an editable
4
+ Maitai agent.
5
+
6
+ The recreation pipeline (``maitai_back.agent.shadow_recreate_service``) is
7
+ **deterministic-first**: code extracts the agent's structure, tools, and model
8
+ config from recorded observed traces, and the LLM ("Mojo") runner is consulted
9
+ only for judgment calls (naming, prompt-template slotting, tool-description
10
+ synthesis). Every decision — deterministic or judgment — is recorded here with
11
+ its supporting evidence so the whole reconstruction is reproducible and
12
+ auditable from an internal admin page.
13
+
14
+ The full :class:`ShadowRecreateAuditLog` is persisted under a single key on the
15
+ recreated agent's ``meta`` column: ``agent.meta["shadow_recreate"]``.
16
+ """
17
+
18
+ from enum import Enum
19
+ from typing import Any, Dict, List, Optional
20
+
21
+ from pydantic import BaseModel, Field
22
+
23
+
24
+ class DecisionType(str, Enum):
25
+ """Which reconstruction decision a :class:`DecisionLogEntry` records."""
26
+
27
+ AGENT_NAME = "AGENT_NAME"
28
+ INSTRUCTIONS_TEMPLATE = "INSTRUCTIONS_TEMPLATE"
29
+ MODEL_CONFIG = "MODEL_CONFIG"
30
+ TOOL_EXTRACTION = "TOOL_EXTRACTION"
31
+ TOOL_DESCRIPTION = "TOOL_DESCRIPTION"
32
+ SUBAGENT_TREE = "SUBAGENT_TREE"
33
+ EXECUTION_MODE = "EXECUTION_MODE"
34
+ PUBLISH = "PUBLISH"
35
+
36
+
37
+ class MojoCallRecord(BaseModel):
38
+ """One invocation of the Mojo (headless runner) for a judgment decision.
39
+
40
+ Recorded verbatim so a reviewer can see exactly what the model was asked,
41
+ what it returned, and whether we trusted it or fell back to the
42
+ deterministic default (``parsed_ok=False``).
43
+ """
44
+
45
+ runner_session_id: Optional[str] = None
46
+ prompt: str = ""
47
+ output: Optional[str] = None
48
+ # Mirrors HeadlessRunnerResult.status: finished | error | stopped | timeout.
49
+ status: str = ""
50
+ duration_ms: int = 0
51
+ model: Optional[str] = None
52
+ error: Optional[str] = None
53
+ # False when the runner failed/timed out or returned unparseable JSON and
54
+ # we fell back to the deterministic default.
55
+ parsed_ok: bool = True
56
+
57
+
58
+ class DecisionEvidence(BaseModel):
59
+ """The recorded inputs that justify a decision.
60
+
61
+ Deliberately loose so both deterministic and judgment decisions can point
62
+ at whatever proof is relevant (which traces, how many agreed, sample
63
+ values).
64
+ """
65
+
66
+ trace_ids: List[str] = Field(default_factory=list)
67
+ task_ids: List[str] = Field(default_factory=list)
68
+ # e.g. {"unique_prompts": 3, "traces_analyzed": 5, "gpt-4.1": 4, "gpt-4o": 1}
69
+ counts: Dict[str, int] = Field(default_factory=dict)
70
+ # Representative values: deduped prompt hashes, tool names, sample args, etc.
71
+ samples: List[str] = Field(default_factory=list)
72
+ notes: Optional[str] = None
73
+
74
+
75
+ class DecisionLogEntry(BaseModel):
76
+ """A single reconstruction decision plus its evidence.
77
+
78
+ ``deterministic`` drives the UI badge directly (rather than inferring it
79
+ from ``mojo_call is None``); judgment decisions that fell back to the
80
+ deterministic default are still ``deterministic=False`` but carry a
81
+ ``mojo_call`` with ``parsed_ok=False``.
82
+ """
83
+
84
+ sequence: int
85
+ decision_type: DecisionType
86
+ decision: str
87
+ rationale: str = ""
88
+ deterministic: bool = True
89
+ evidence: DecisionEvidence = Field(default_factory=DecisionEvidence)
90
+ mojo_call: Optional[MojoCallRecord] = None
91
+
92
+
93
+ class ShadowRecreateAuditLog(BaseModel):
94
+ """Full audit trail of one recreate-from-traces run.
95
+
96
+ Serialized to ``agent.meta["shadow_recreate"]`` on the recreated agent and
97
+ rendered decision-by-decision on the internal admin page.
98
+ """
99
+
100
+ # Schema version of THIS log format (not the agent version).
101
+ version: str = "1"
102
+ observed_agent_id: int
103
+ recreated_agent_id: Optional[int] = None
104
+ recreated_version: Optional[str] = None
105
+ sessions_scanned: int = 0
106
+ corpus_task_ids: List[str] = Field(default_factory=list)
107
+ decisions: List[DecisionLogEntry] = Field(default_factory=list)
108
+ warnings: List[str] = Field(default_factory=list)
109
+ created_at_ms: int = 0
110
+ # completed | failed
111
+ status: str = "completed"
maitai_models/model.py CHANGED
@@ -32,6 +32,11 @@ class Model(BaseModel):
32
32
  finetune_run_id: Optional[int] = Field(default=None)
33
33
  instance_id: Optional[int] = Field(default=None)
34
34
  region: Optional[str] = Field(default=None)
35
+ # Application this model belongs to. Only populated for finetuned models on
36
+ # the Models listing (derived from the finetune run, falling back to intent);
37
+ # None elsewhere.
38
+ application_id: Optional[int] = Field(default=None)
39
+ application_name: Optional[str] = Field(default=None)
35
40
  supports_logprobs: bool = Field(default=False)
36
41
  chat_template_kwargs: Optional[dict] = Field(default=None)
37
42
  meta: Optional[dict] = Field(default_factory=dict)
@@ -0,0 +1,451 @@
1
+ # codegen: frontend, sdk
2
+
3
+ """Unified test set models.
4
+
5
+ A `TestSet` is a type-less bag of canonical `(input, expected_output)` items.
6
+ Items can be sourced from production requests, workflow runs, agent tasks,
7
+ or hand-authored manually, and they coexist in the same set. At run time the
8
+ user picks a consumer (model / workflow / agent) and the consumer's adapter
9
+ turns canonical inputs into consumer-native inputs.
10
+
11
+ See `docs/internal/TEST_SET_UNIFICATION.md` for the full design.
12
+ """
13
+
14
+ from enum import Enum
15
+ from typing import Any, Dict, List, Optional
16
+
17
+ from pydantic import BaseModel, ConfigDict, Field
18
+
19
+ from maitai_models.chat import ChatCompletionParams, ChatMessage, ToolCall
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Source provenance and flatten strategy
23
+ # ---------------------------------------------------------------------------
24
+
25
+
26
+ class TestSetItemSourceType(str, Enum):
27
+ """Where the item was imported from. MANUAL items are hand-authored."""
28
+
29
+ REQUEST = "REQUEST"
30
+ WORKFLOW_RUN = "WORKFLOW_RUN"
31
+ AGENT_TASK = "AGENT_TASK"
32
+ MANUAL = "MANUAL"
33
+
34
+
35
+ class TestSetItemFlattenStrategy(str, Enum):
36
+ """How the source artifact was converted into the canonical shape.
37
+
38
+ Stored on `TestSetItem.flatten.strategy` for portal disclosure (the UI
39
+ shows the user how a non-request source was adapted at import time).
40
+ """
41
+
42
+ # Request source: canonical is what the row already stored.
43
+ IDENTITY = "identity"
44
+
45
+ # Workflow run source: pull workflow_run.input + .output.
46
+ WORKFLOW_RUN_INPUT_OUTPUT = "workflow_run_input_output"
47
+
48
+ # Agent task source variants. The "_with_system_prompt" variant
49
+ # additionally prepends the agent's system prompt from the first
50
+ # LLM_CALL action's messages.
51
+ AGENT_FIRST_USER_MESSAGE = "agent_first_user_message"
52
+ AGENT_FIRST_USER_MESSAGE_WITH_SYSTEM_PROMPT = (
53
+ "agent_first_user_message_with_system_prompt"
54
+ )
55
+
56
+ # User-authored from scratch in the portal.
57
+ MANUAL = "manual"
58
+
59
+
60
+ # ---------------------------------------------------------------------------
61
+ # Canonical payload shapes
62
+ # ---------------------------------------------------------------------------
63
+
64
+
65
+ class CanonicalAssistantMessage(BaseModel):
66
+ """Canonical expected/actual output: one assistant message.
67
+
68
+ Same shape OpenAI returns in `choices[0].message`. Nullable at the column
69
+ level (errored runs and manual items may have no expected output).
70
+ """
71
+
72
+ role: str = "assistant"
73
+ content: Optional[str] = ""
74
+ tool_calls: Optional[List[ToolCall]] = None
75
+
76
+
77
+ # Canonical input is just a `ChatCompletionParams`. Reusing the existing model
78
+ # means the request import is identity (no field reshuffling) and every
79
+ # downstream consumer already speaks this shape. Exposed as an alias for
80
+ # documentation; the underlying type is unchanged.
81
+ CanonicalInput = ChatCompletionParams
82
+
83
+
84
+ # ---------------------------------------------------------------------------
85
+ # TestSet and items
86
+ # ---------------------------------------------------------------------------
87
+
88
+
89
+ class TestSet(BaseModel):
90
+ """A type-less collection of canonical test items.
91
+
92
+ Scoped to (company_id, application_id). Items can be of any source type
93
+ and mixed freely.
94
+ """
95
+
96
+ id: Optional[int] = None
97
+ date_created: Optional[str] = None
98
+ date_updated: Optional[str] = None
99
+ company_id: int
100
+ application_id: int
101
+ test_set_name: str
102
+ test_set_description: Optional[str] = None
103
+ is_golden: bool = False
104
+ meta: Dict[str, Any] = Field(default_factory=dict)
105
+ # Enriched on list/detail endpoints, not stored on the row.
106
+ item_count: Optional[int] = None
107
+ # Number of unified test runs that have been executed against this
108
+ # set. Enriched on the list endpoint so the portal can render a
109
+ # "Runs" column without a second per-row round-trip. Optional so
110
+ # write paths (RETURNING) that don't compute it can leave it None.
111
+ run_count: Optional[int] = None
112
+ # Enriched via a LEFT JOIN on ``application`` so the portal can render
113
+ # the human-readable name inline (no separate `/application/` fetch
114
+ # required, and no timing race between the two calls).
115
+ application_name: Optional[str] = None
116
+
117
+
118
+ class TestSetItemFlatten(BaseModel):
119
+ """Metadata about how the source artifact was flattened into canonical.
120
+
121
+ The `strategy` field is required; additional keys are allowed so
122
+ individual strategies can record their own parameters (e.g. which
123
+ fallback was used for an agent task without an obvious first message).
124
+ """
125
+
126
+ model_config = ConfigDict(extra="allow")
127
+
128
+ strategy: TestSetItemFlattenStrategy
129
+
130
+
131
+ class TestSetItem(BaseModel):
132
+ """A single item in a test set.
133
+
134
+ `input` is the canonical chat-completion request payload; `expected_output`
135
+ is the canonical assistant message we expect from a consumer. Provenance
136
+ fields point back at the source artifact for traceability. Exactly one
137
+ `source_*_id` is populated, matching `source_type` (MANUAL items leave
138
+ all three null).
139
+ """
140
+
141
+ id: Optional[int] = None
142
+ date_created: Optional[str] = None
143
+ test_set_id: int
144
+ company_id: int
145
+
146
+ input: CanonicalInput
147
+ expected_output: Optional[CanonicalAssistantMessage] = None
148
+
149
+ source_type: TestSetItemSourceType
150
+ source_request_id: Optional[str] = None
151
+ source_workflow_run_id: Optional[int] = None
152
+ source_agent_task_id: Optional[str] = None
153
+ # Hydrated on read paths that JOIN workflow_run / agent_request so the
154
+ # UI can open a source-appropriate detail modal without a second
155
+ # round-trip. Left null on write RETURNING paths that skip the join.
156
+ source_workflow_run_session_id: Optional[str] = None
157
+ source_agent_task_session_id: Optional[str] = None
158
+ source_agent_task_agent_id: Optional[int] = None
159
+
160
+ flatten: TestSetItemFlatten
161
+
162
+ meta: Dict[str, Any] = Field(default_factory=dict)
163
+
164
+
165
+ class TestSetItemResponseSub(BaseModel):
166
+ """Edited/corrected expected output for a single item.
167
+
168
+ When this row exists, scoring uses `output_content` as the expected;
169
+ otherwise it falls back to `TestSetItem.expected_output`. Mirrors the
170
+ `_response_sub` tables on the legacy request and workflow families.
171
+ """
172
+
173
+ id: Optional[int] = None
174
+ date_created: Optional[str] = None
175
+ company_id: int
176
+ test_set_id: int
177
+ test_set_item_id: int
178
+ output_content: CanonicalAssistantMessage
179
+ meta: Dict[str, Any] = Field(default_factory=dict)
180
+
181
+
182
+ # ---------------------------------------------------------------------------
183
+ # Run-side helpers shared across the three run families
184
+ # ---------------------------------------------------------------------------
185
+
186
+
187
+ class TestRunPhase(str, Enum):
188
+ """Test run lifecycle phases.
189
+
190
+ Values used in the `status` VARCHAR(50) column on test_run,
191
+ workflow_test_run, and agent_test_run. PREPARING_INPUTS is the new
192
+ eager-materialization phase introduced by unification: during it the
193
+ run-item rows exist with `adapted_input = NULL` and the prep job is
194
+ filling them in.
195
+ """
196
+
197
+ CREATED = "CREATED"
198
+ PREPARING_INPUTS = "PREPARING_INPUTS"
199
+ RUNNING = "RUNNING"
200
+ COMPLETED = "COMPLETED"
201
+ # Post-execution scoring pass is in flight (structural diff +
202
+ # evaluation criteria). The run reaches this state via
203
+ # ``POST /score`` and returns to COMPLETED when the background task
204
+ # finishes. Kept distinct from RUNNING so the portal can show a
205
+ # different indicator and disable actions that require a settled run.
206
+ SCORING = "SCORING"
207
+ FAILED = "FAILED"
208
+ # Soft-delete tombstone. Set by ``delete_unified_test_run`` in place
209
+ # of a physical row removal so the row + its items stay queryable
210
+ # for audit/backfill purposes while disappearing from every read
211
+ # path (list/get/progress/etc). Matches the legacy Model + Workflow
212
+ # test-run delete semantics.
213
+ DELETED = "DELETED"
214
+
215
+
216
+ class TestRunConsumerType(str, Enum):
217
+ """Which kind of consumer this run is exercising the set against."""
218
+
219
+ MODEL = "MODEL"
220
+ WORKFLOW = "WORKFLOW"
221
+ AGENT = "AGENT"
222
+
223
+
224
+ # ---------------------------------------------------------------------------
225
+ # Consumer config (discriminated on consumer_type)
226
+ #
227
+ # Stored as free jsonb in `unified_test_run.consumer_config`. Validated in
228
+ # Python before insert. Each variant carries the settings its own consumer
229
+ # needs at execution time; the model variant is the interesting one for
230
+ # the L, workflow/agent variants ship now so their shapes are locked in.
231
+ # ---------------------------------------------------------------------------
232
+
233
+
234
+ class ModelConsumerConfig(BaseModel):
235
+ """Config for a MODEL run.
236
+
237
+ `model` is the required identifier the run will execute against. The
238
+ inference knobs are optional overrides layered on top of whatever the
239
+ canonical input already carries; adapter identity means the canonical
240
+ ChatCompletionParams are what actually gets sent to the model, and
241
+ anything here is applied by the executor as a per-run override.
242
+ """
243
+
244
+ consumer_type: TestRunConsumerType = TestRunConsumerType.MODEL
245
+ model: str
246
+ temperature: Optional[float] = None
247
+ top_p: Optional[float] = None
248
+ max_tokens: Optional[int] = None
249
+ seed: Optional[int] = None
250
+ response_format: Optional[Dict[str, Any]] = None
251
+ extra_params: Dict[str, Any] = Field(default_factory=dict)
252
+
253
+
254
+ class WorkflowConsumerConfig(BaseModel):
255
+ """Config for a WORKFLOW run.
256
+
257
+ `workflow_id` is required and matches `unified_test_run.consumer_id`.
258
+ `workflow_version_id` pins the run to a specific published version; when
259
+ absent the current draft/latest is used (same semantics as the existing
260
+ workflow test run flow).
261
+ """
262
+
263
+ consumer_type: TestRunConsumerType = TestRunConsumerType.WORKFLOW
264
+ workflow_id: int
265
+ workflow_version_id: Optional[int] = None
266
+
267
+
268
+ class AgentConsumerConfig(BaseModel):
269
+ """Config for an AGENT run.
270
+
271
+ `agent_id` is required and matches `unified_test_run.consumer_id`. The
272
+ `flatten_variant` here is only used by the agent adapter's input step,
273
+ not by the executor; it lets a run pick the "with_system_prompt" flavor
274
+ even when the source item's own flatten was different.
275
+ """
276
+
277
+ consumer_type: TestRunConsumerType = TestRunConsumerType.AGENT
278
+ agent_id: int
279
+ max_iterations: Optional[int] = None
280
+ flatten_variant: TestSetItemFlattenStrategy = (
281
+ TestSetItemFlattenStrategy.AGENT_FIRST_USER_MESSAGE
282
+ )
283
+ extra_params: Dict[str, Any] = Field(default_factory=dict)
284
+
285
+
286
+ # ---------------------------------------------------------------------------
287
+ # UnifiedTestRun / UnifiedTestRunItem row models
288
+ # ---------------------------------------------------------------------------
289
+
290
+
291
+ class UnifiedTestRun(BaseModel):
292
+ """One invocation of a test_set against a chosen consumer."""
293
+
294
+ id: Optional[int] = None
295
+ date_created: Optional[str] = None
296
+ date_completed: Optional[str] = None
297
+ company_id: int
298
+ application_id: int
299
+ test_set_id: int
300
+ consumer_type: TestRunConsumerType
301
+ consumer_id: Optional[int] = None
302
+ consumer_config: Dict[str, Any] = Field(default_factory=dict)
303
+ status: TestRunPhase = TestRunPhase.CREATED
304
+ description: Optional[str] = None
305
+ error_message: Optional[str] = None
306
+ meta: Dict[str, Any] = Field(default_factory=dict)
307
+
308
+
309
+ class UnifiedTestRunItem(BaseModel):
310
+ """Per-item state within a unified test run.
311
+
312
+ `adapted_input` is filled at PREPARING_INPUTS; `actual_output` at RUNNING.
313
+ """
314
+
315
+ id: Optional[int] = None
316
+ date_created: Optional[str] = None
317
+ date_executed: Optional[str] = None
318
+ test_run_id: int
319
+ test_set_item_id: int
320
+ company_id: int
321
+ status: str = "CREATED"
322
+ adapted_input: Optional[Dict[str, Any]] = None
323
+ actual_output: Optional[Dict[str, Any]] = None
324
+ matched: Optional[bool] = None
325
+ diff_result: Optional[Dict[str, Any]] = None
326
+ error_message: Optional[str] = None
327
+ duration_ms: Optional[int] = None
328
+ meta: Dict[str, Any] = Field(default_factory=dict)
329
+
330
+
331
+ class UnifiedTestRunScoreSummary(BaseModel):
332
+ """Aggregate scoring result for a run.
333
+
334
+ Counts derive from `unified_test_run_item` rows after a scoring pass.
335
+ `match_rate` excludes items with no expected output and items that
336
+ errored during execution, so it reflects only "answered correctly out
337
+ of items with a ground truth."
338
+ """
339
+
340
+ test_run_id: int
341
+ total: int
342
+ matched: int
343
+ mismatched: int
344
+ no_expected: int
345
+ errored: int
346
+ match_rate: float
347
+
348
+
349
+ class CreateUnifiedTestRunRequest(BaseModel):
350
+ """Create-run payload.
351
+
352
+ ``consumer_config`` shape is validated in the service against the concrete
353
+ consumer variant (Model/Workflow/Agent) matching ``consumer_type``, so this
354
+ stays a plain dict at the wire level.
355
+
356
+ Evaluation fields mirror the legacy per-flavor wizards:
357
+
358
+ - ``evaluation_criteria_ids``: criteria selected for scoring. When omitted,
359
+ MODEL/WORKFLOW runs fall back to the system Exact Match criterion and
360
+ AGENT runs error out (matching legacy behavior).
361
+ - ``criteria_overrides``: per-criterion config overrides, keyed by
362
+ criterion id. Only meaningful for AGENT runs; carries the effective
363
+ LATENCY / STEP_COUNT / etc. thresholds picked in the wizard.
364
+ - ``eval_model`` / ``field_mapping``: stored on ``meta`` so the score-time
365
+ runner can read them the same way the legacy request/workflow flows do.
366
+ """
367
+
368
+ test_set_id: int
369
+ consumer_type: TestRunConsumerType
370
+ consumer_id: Optional[int] = None
371
+ consumer_config: Dict[str, Any] = Field(default_factory=dict)
372
+ description: Optional[str] = None
373
+ meta: Dict[str, Any] = Field(default_factory=dict)
374
+ evaluation_criteria_ids: Optional[List[int]] = None
375
+ criteria_overrides: Optional[Dict[int, Dict[str, Any]]] = None
376
+
377
+
378
+ # ---------------------------------------------------------------------------
379
+ # Request/response models for the v1 API surface
380
+ # ---------------------------------------------------------------------------
381
+
382
+
383
+ class CreateTestSetRequest(BaseModel):
384
+ """Create an empty test set; items are added separately."""
385
+
386
+ test_set_name: str
387
+ test_set_description: Optional[str] = None
388
+ application_id: int
389
+ is_golden: bool = False
390
+ meta: Dict[str, Any] = Field(default_factory=dict)
391
+
392
+
393
+ class UpdateTestSetRequest(BaseModel):
394
+ """Patch mutable metadata on an existing test set.
395
+
396
+ Every field is optional so callers can update a single field without
397
+ having to re-send the rest. ``application_id`` is intentionally not
398
+ editable — moving a set across applications is a separate operation
399
+ (clone into the new app), not an update.
400
+ """
401
+
402
+ test_set_name: Optional[str] = None
403
+ test_set_description: Optional[str] = None
404
+ is_golden: Optional[bool] = None
405
+
406
+
407
+ class CreateManualTestSetItemRequest(BaseModel):
408
+ """Hand-authored item.
409
+
410
+ Both input and expected_output are user-provided. The flatten strategy
411
+ is fixed to MANUAL; the API does not let callers pass `source_*_id` for
412
+ manual items (those are populated only by import endpoints).
413
+ """
414
+
415
+ input: CanonicalInput
416
+ expected_output: Optional[CanonicalAssistantMessage] = None
417
+ meta: Dict[str, Any] = Field(default_factory=dict)
418
+
419
+
420
+ class ImportRequestSourceRequest(BaseModel):
421
+ """Import an existing chat_completion_request into a test set."""
422
+
423
+ source_request_id: str
424
+ meta: Dict[str, Any] = Field(default_factory=dict)
425
+
426
+
427
+ class ImportWorkflowRunSourceRequest(BaseModel):
428
+ """Import a workflow_run into a test set."""
429
+
430
+ source_workflow_run_id: int
431
+ meta: Dict[str, Any] = Field(default_factory=dict)
432
+
433
+
434
+ class ImportAgentTaskSourceRequest(BaseModel):
435
+ """Import a completed agent task into a test set.
436
+
437
+ The strategy choice is exposed to callers because the lossier
438
+ "with_system_prompt" variant is sometimes useful, sometimes not.
439
+ """
440
+
441
+ source_agent_task_id: str
442
+ flatten_strategy: TestSetItemFlattenStrategy = (
443
+ TestSetItemFlattenStrategy.AGENT_FIRST_USER_MESSAGE
444
+ )
445
+ meta: Dict[str, Any] = Field(default_factory=dict)
446
+
447
+
448
+ class UpdateTestSetItemExpectedOutputRequest(BaseModel):
449
+ """Override expected_output for an item via the response_sub mechanism."""
450
+
451
+ output_content: CanonicalAssistantMessage
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: maitai-python
3
- Version: 1.2.33
3
+ Version: 1.2.34
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -1,10 +1,10 @@
1
1
  maitai/__init__.py,sha256=Z9xzwOzzKUTXvaPhe98iXCSi0iPd9r5pH0v3aH3N9sI,902
2
- maitai/_config.py,sha256=hbfl5kvfqzpF-FQ0XZb-72Ovr2FloXFTbeH-zQ2Jd_4,8063
2
+ maitai/_config.py,sha256=IRAQAhuScW9nvO-PvWxo6NN_KlRsXzQa_BcYgoAdpmU,8605
3
3
  maitai/_config_listener.py,sha256=LBMyEXtI3IkUSA5mR2Tv4GsB9VcUOPgKFaNbiWuomFw,5394
4
4
  maitai/_context.py,sha256=ATNShbha6NYzLDGw9eyc_AWzTxnvodncAy90p-9Bmd4,2587
5
5
  maitai/_evaluator.py,sha256=6hRRBI9rIFYYHn52_w1ax-aA-988xalk3iMrSwuA_q8,11467
6
6
  maitai/_files.py,sha256=btbkJC0iu5DxI5r2dWJ30VccgVOIsp3Z0RFLnMQe32Q,4666
7
- maitai/_inference.py,sha256=dzCFzI-TXmHkNPWChJM0O7jgdo2Uh8RNAaYH9eACqqM,13916
7
+ maitai/_inference.py,sha256=MsUcACBmiS_H7J2iVIX5R8TyRG2vBlHoX84DgUDnFgs,14216
8
8
  maitai/_logger.py,sha256=P7yNqApMxMxPnxDul7Xa0HSlKkp-1y2-TFR0014_zAg,10631
9
9
  maitai/_maitai.py,sha256=wIR5M44pk-JQQO-0Y8DSnbzr_AtI1w0CBDDxLw_j06Y,9063
10
10
  maitai/_maitai_async.py,sha256=hZFths2-Bj8f8AKoj2YTgvjFcSxIAF3AyssLJddbHdU,9601
@@ -19,8 +19,8 @@ maitai/agent/_completions_async.py,sha256=BFhnJWex9NVkyclYmCMcwNgE5BOpEaQp7p2BlB
19
19
  maitai/agent/_handle.py,sha256=MBSwb4Uhu9qIiJaopuPwFiqRT1Mp-khUdUChZ6v73lU,7199
20
20
  maitai/agent/_request_wire.py,sha256=PbYLEJsYmnX7iUFRzXn79SUwgxde8DnK71pmpU6cVJQ,4221
21
21
  maitai/chat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
- maitai/chat/_completions.py,sha256=5qjVuyCf6PHINLyzLGmaxcd3K7XudizWb3JoLMYdfc4,27007
23
- maitai/chat/_completions_async.py,sha256=PUhOQpM9sUKg_1njlqU3bcIann0ZXByVkapxkiN8wEI,27624
22
+ maitai/chat/_completions.py,sha256=wFlwQvLnZmZ9VpeJKiLng0-a2fkhRk9usUH3saUxxBs,28077
23
+ maitai/chat/_completions_async.py,sha256=JhG4qRjIqvyV68fkkrKpF28MLbUjly3-upPF66msEBs,28534
24
24
  maitai/integrations/__init__.py,sha256=A1rsB00fN06tjwPGrhnGt22w2W9M8jVMsDPA-Bw4kTA,630
25
25
  maitai/integrations/_observe.py,sha256=l4acUXFPvBRNJp4faXc55rHpaOelWkBotfaW9xztk28,9428
26
26
  maitai/integrations/_session.py,sha256=4baNl2KihgqNsurM4wyF3nifxi1ZKDOPjEorB5N7K1s,2822
@@ -50,7 +50,7 @@ maitai/workflow/_completions_async.py,sha256=J6kaya1PdxN5e5V7o5Rtwi6vjyW0nr3FRwZ
50
50
  maitai/workflow/_local.py,sha256=2VUf5Uvc1LsbssGkLZKfqq0nUfXLZvR5jYSuHMe52bw,16991
51
51
  maitai/workflow/_stream_http.py,sha256=4_xK8tGvECubKKax8FgY7pL_RaASRg2AAaCI5_gwghE,5971
52
52
  maitai_common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
53
- maitai_common/version.py,sha256=k1oXK2gJ1zcq2zGQIH10qEympMDIkbLejo0e0eBye0k,65
53
+ maitai_common/version.py,sha256=uXbNUU2jVW86Na4KM_SpvW9SWY5Tinw6Rowj4-1ooIo,65
54
54
  maitai_common/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
55
55
  maitai_common/config/config_service.py,sha256=xcbmwXr5cGZI0_wE2AEbhXQbQwurkUiv8qfFklNNlXU,1120
56
56
  maitai_models/adapter.py,sha256=DrbFHeeo9tNI10MmZwNSivcvmNfrljqsYikyHzmTZKs,424
@@ -86,7 +86,7 @@ maitai_models/intent_config_version.py,sha256=GxY61gRfUD0D5N4hgRGQDA3WAsFHLu-Crg
86
86
  maitai_models/key.py,sha256=lTLJkn-VE4vNy94He01J8gYp6hyazFYhhEjRsOLAbFo,1260
87
87
  maitai_models/metadata.py,sha256=XYShCcxKmops21I-7U5U6o23YGt0j9X_THdhNThP67I,2609
88
88
  maitai_models/metric.py,sha256=iL1FqaJ-3ii5pgY4cGZKp0nuQVG1XnBggopazQhGN_E,451
89
- maitai_models/model.py,sha256=JlC91gIvEhWHs0Bl8AzliEBhLTT9SSWZd6b_-OtAsPU,2143
89
+ maitai_models/model.py,sha256=2caQtrkZGK0JRYCZ4vjv_5eIIRb1KZQXy-QaDw8Y_ww,2441
90
90
  maitai_models/model_drift.py,sha256=T79YKzyiEj9YW2fntLYWRgv54xLsRdDEaqI0rgz8mo0,1518
91
91
  maitai_models/model_profile.py,sha256=X-xEQBgtvtaUC8edTuhSxM129GERnOAuLD5VdmTXEfw,2597
92
92
  maitai_models/monitor.py,sha256=sijzF_-Pt6fdrjyfx3mbFdvX33ew8cehyBUsrdl3SR8,10437
@@ -99,6 +99,7 @@ maitai_models/session.py,sha256=WuWHRJutKLheva-ZoLqf833cYTgp2ZZR18I67a8D-Ek,1008
99
99
  maitai_models/shared_resource.py,sha256=6iefc7wmT1Vp34MtWFCLihBE0RAuKc6pqiAkHBQx_Cc,505
100
100
  maitai_models/slack_integration.py,sha256=rfgO-6yoLVMKjsc5RVnvLjog1dyq4-b1AvQ5NN4PPMw,402
101
101
  maitai_models/tagging.py,sha256=WaDR1QjwW4UAC9FJtbC0K96iI0QwfcuP4Gm4n3Y-TdQ,2750
102
+ maitai_models/test_set.py,sha256=R6QRrviEtR3buEjDNc5sIMnj-s5HOr5lCO3y21W2k8Q,16288
102
103
  maitai_models/webhook.py,sha256=lf5makYB8CDuEfWohxjz24mmckD9o3TXSEq--6VjokE,827
103
104
  maitai_models/webhook_event.py,sha256=k3cgC-ZjeBtA6yHUE_4DxbnQAXegIrl23xz5P6vB1js,264
104
105
  maitai_models/workflow.py,sha256=vF4LpQiv8Qj60anTrK4ucK_kGHQBY_gxPkK3uOk_QOs,5248
@@ -108,13 +109,14 @@ maitai_models/agent/base.py,sha256=gYhTQnbaQytpe-vZx7QACTIdOq64omBF9WT1-YC31uc,7
108
109
  maitai_models/agent/enum.py,sha256=PVGHoC3xupKBcrmNjmQWT4V8Caa6lBWn5JCldXD6uxE,1950
109
110
  maitai_models/agent/extended.py,sha256=MbwkcfmiLytko-_0p8riI4KclLEuWrKh-wqMjbdfKEo,22940
110
111
  maitai_models/agent/import_manifest.py,sha256=yreDd2Le6z685YfWu0r03QyV9GN2IjzFIEEExy9qiFU,5698
112
+ maitai_models/agent/shadow_recreate.py,sha256=RJIz9Np9LsBmJk7TdDtKL7Vs-2rq3eldMzJo3jVtfT0,4091
111
113
  maitai_workflow/__init__.py,sha256=ZDeaul20aqOMZyh83UAnFarmCuqqTuaF9IErFwJdy1I,346
112
- maitai_workflow/agent_request.py,sha256=8YJC6bzdTy_4LKGfWL1rFpYsy-ttZ10tddyO1pM9eg4,4661
113
- maitai_workflow/context.py,sha256=aGtaodFwQvpD00YlITzE74Jw5MhEMRSuiNcGgXNekbM,74675
114
+ maitai_workflow/agent_request.py,sha256=0QYFfYjodbfblvg2g4eqEh-hrtqfzqe96boas0IVtM8,5299
115
+ maitai_workflow/context.py,sha256=wragfsGUwFQzKI7wC7kCHXfwWb-70BnW3rwnX1xm0-Q,78155
114
116
  maitai_workflow/profile_nav.py,sha256=i9kqAmxMQLtELGvK3X2KMOOcQzaDmbCB2HGi8dkWO7c,2012
115
117
  maitai_workflow/datastore/__init__.py,sha256=PGdETeEJF3z7zuNroQlmjibgcBadpr388zqd1GhtfrA,477
116
118
  maitai_workflow/datastore/filters.py,sha256=rCg9HsQG4iXt_10DeBjaqYnaT0I0hOXk9ngeHkn5stI,9604
117
- maitai_python-1.2.33.dist-info/METADATA,sha256=uZphkFjZCuNvZy4pI56CVwxywbw7uAQW3lv4elVpiAg,1966
118
- maitai_python-1.2.33.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
119
- maitai_python-1.2.33.dist-info/top_level.txt,sha256=xogwYKin1vXFIAWRw3Myqr3hkymwsucp67TCSAWO3Rg,51
120
- maitai_python-1.2.33.dist-info/RECORD,,
119
+ maitai_python-1.2.34.dist-info/METADATA,sha256=XmQJQqvd9pHelXNm1S6vzGLIKPUHDwetRK8qtnqUMvU,1966
120
+ maitai_python-1.2.34.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
121
+ maitai_python-1.2.34.dist-info/top_level.txt,sha256=xogwYKin1vXFIAWRw3Myqr3hkymwsucp67TCSAWO3Rg,51
122
+ maitai_python-1.2.34.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (82.0.1)
2
+ Generator: setuptools (83.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -73,10 +73,19 @@ def build_workflow_agent_request(
73
73
  session_id = kwargs.pop("session_id", None) or default_session_id
74
74
 
75
75
  agent_id = kwargs.pop("agent_id", None)
76
- application = (
77
- kwargs.pop("application_ref_name", None)
78
- or kwargs.pop("application", None)
79
- or default_application
76
+ explicit_application = kwargs.pop("application_ref_name", None) or kwargs.pop(
77
+ "application", None
78
+ )
79
+ # A string agent target ("agent:<id|name>[:<version|release>]") is
80
+ # self-contained and company-scoped — the orchestrator resolves it via
81
+ # resolve_agent_target. Attaching the *default* application (e.g. the
82
+ # workflow's own app ref) makes the orchestrator take its
83
+ # name+application resolution branch and mis-resolve the target as a
84
+ # literal agent name (e.g. "journey:agent:2958"), which does not exist.
85
+ # Only fall back to the default application for bare agent *names*.
86
+ is_string_target = agent_target.startswith("agent:")
87
+ application = explicit_application or (
88
+ None if is_string_target else default_application
80
89
  )
81
90
  application_id = kwargs.pop("application_id", None)
82
91
 
@@ -136,6 +136,14 @@ def _s3_start_keepalive(client: Any, bucket: str) -> None:
136
136
  _s3_keepalive_started = True
137
137
 
138
138
 
139
+ def _truncate_detail(value: str, limit: int = 48) -> str:
140
+ """Trim free-text span detail (e.g. a web-search query) for the profile label."""
141
+ text = " ".join(str(value).split())
142
+ if len(text) <= limit:
143
+ return text
144
+ return text[: limit - 1].rstrip() + "…"
145
+
146
+
139
147
  def _workflow_ref_env_prefix(workflow_ref_name: str) -> str:
140
148
  """Normalize workflow ref for env-var lookup (strip tag, upper snake case)."""
141
149
  base_ref = (workflow_ref_name or "").split(":", 1)[0]
@@ -543,6 +551,22 @@ class WorkflowStreamResponse:
543
551
  return self._resp.text
544
552
 
545
553
 
554
+ def _normalize_orchestration_host(host: Optional[str]) -> Optional[str]:
555
+ """Normalize an agent-orchestration host override.
556
+
557
+ The agent SDK appends ``/agent`` to this host, so strip a trailing
558
+ ``/agent`` (mirrors the SDK's own ``_determine_maitai_orchestration_host``)
559
+ and any trailing slash. Returns ``None`` when unset so callers can fall
560
+ back to the general base URL.
561
+ """
562
+ if not host:
563
+ return None
564
+ host = host.strip().rstrip("/")
565
+ if host.endswith("/agent"):
566
+ host = host[: -len("/agent")].rstrip("/")
567
+ return host or None
568
+
569
+
546
570
  class WorkflowContext:
547
571
  """
548
572
  Context object passed to workflow script execute(ctx).
@@ -560,6 +584,7 @@ class WorkflowContext:
560
584
  maitai_caller_api_key: Optional[str] = None,
561
585
  delegation_token: Optional[str] = None,
562
586
  maitai_inference_host: Optional[str] = None,
587
+ maitai_orchestration_host: Optional[str] = None,
563
588
  session_id: Optional[str] = None,
564
589
  _profile: bool = False,
565
590
  input: Optional[Any] = None,
@@ -585,6 +610,17 @@ class WorkflowContext:
585
610
  self._maitai_inference_host = (
586
611
  maitai_inference_host.rstrip("/") if maitai_inference_host else None
587
612
  )
613
+ # Agent chat-completions (``ctx.agents.completions.create``) live on the
614
+ # agent-orchestration-service, NOT the general API host. In prod the
615
+ # worker's ``maitai_base_url`` points at the internal main backend
616
+ # (correct for files / request_stream / etc.), which does not serve
617
+ # ``/agent/chat/completions`` — so agent invocation must target the
618
+ # orchestration host explicitly. Falls back to the base URL, which is
619
+ # correct for the public ingress (routes /agent/chat/* to orchestration)
620
+ # and for local SDK execution.
621
+ self._maitai_orchestration_host = _normalize_orchestration_host(
622
+ maitai_orchestration_host
623
+ )
588
624
  self._session_id = session_id or str(uuid.uuid4())
589
625
  self.session_id = self._session_id # Public access for workflow scripts
590
626
  self._profile_enabled = _profile
@@ -711,10 +747,14 @@ class WorkflowContext:
711
747
  "end_epoch_ms": end * 1000,
712
748
  "trace_type": "context",
713
749
  }
714
- if trace_kind and refs:
750
+ # trace_kind drives the bar color + legend entry and is meaningful on its
751
+ # own (search / http / embeddings spans have no drill-in target). refs are
752
+ # only needed to build a nav_path for the kinds that support drilling in.
753
+ if trace_kind:
715
754
  span["trace_kind"] = trace_kind
755
+ if refs:
716
756
  span["refs"] = refs
717
- nav_path = build_profile_nav_path(trace_kind, refs)
757
+ nav_path = build_profile_nav_path(trace_kind, refs) if trace_kind else None
718
758
  if nav_path:
719
759
  span["nav_path"] = nav_path
720
760
  self._profile_spans.append(span)
@@ -869,10 +909,10 @@ class WorkflowContext:
869
909
  else None
870
910
  )
871
911
  self._record_span(
872
- "chat_completion",
912
+ f"chat_completion: {intent}",
873
913
  t0,
874
914
  time.time(),
875
- trace_kind="llm" if refs else None,
915
+ trace_kind="llm",
876
916
  refs=refs,
877
917
  )
878
918
 
@@ -881,10 +921,10 @@ class WorkflowContext:
881
921
  result_dict = result.model_dump(exclude_none=True)
882
922
  refs = self._llm_span_refs(result_dict, str(session_id))
883
923
  self._record_span(
884
- "chat_completion",
924
+ f"chat_completion: {intent}",
885
925
  t0,
886
926
  time.time(),
887
- trace_kind="llm" if refs else None,
927
+ trace_kind="llm",
888
928
  refs=refs,
889
929
  )
890
930
  return result_dict
@@ -917,7 +957,17 @@ class WorkflowContext:
917
957
 
918
958
  selected_api_key = self._maitai_caller_api_key
919
959
  config = Config(selected_api_key, server_side_only=True)
920
- config.maitai_orchestration_host = self._maitai_base_url.rstrip("/")
960
+ # Prefer the explicit orchestration host; then MAITAI_AGENT_HOST from the
961
+ # worker env; finally the general base URL. The base URL is only correct
962
+ # for agent completions via the public ingress (which routes
963
+ # /agent/chat/* to orchestration) — internally it points at the main
964
+ # backend, which has no /agent/chat/completions route.
965
+ orchestration_host = (
966
+ self._maitai_orchestration_host
967
+ or _normalize_orchestration_host(os.environ.get("MAITAI_AGENT_HOST"))
968
+ or self._maitai_base_url.rstrip("/")
969
+ )
970
+ config.maitai_orchestration_host = orchestration_host
921
971
  completions = AgentCompletions(config)
922
972
 
923
973
  log_payload = redact_agent_log_fields(
@@ -961,10 +1011,10 @@ class WorkflowContext:
961
1011
  else None
962
1012
  )
963
1013
  self._record_span(
964
- f"agent_completion:{agent}",
1014
+ f"agent_completion: {agent}",
965
1015
  t0,
966
1016
  time.time(),
967
- trace_kind="agent" if refs else None,
1017
+ trace_kind="agent",
968
1018
  refs=refs,
969
1019
  )
970
1020
 
@@ -977,10 +1027,10 @@ class WorkflowContext:
977
1027
  )
978
1028
  refs = self._agent_span_refs(agent, agent_session_id, result_dict)
979
1029
  self._record_span(
980
- f"agent_completion:{agent}",
1030
+ f"agent_completion: {agent}",
981
1031
  t0,
982
1032
  time.time(),
983
- trace_kind="agent" if refs else None,
1033
+ trace_kind="agent",
984
1034
  refs=refs,
985
1035
  )
986
1036
  self.log(
@@ -1073,10 +1123,10 @@ class WorkflowContext:
1073
1123
  result_dict["session_id"] = nested_session_id
1074
1124
  refs = self._workflow_span_refs(result_dict, workflow)
1075
1125
  self._record_span(
1076
- f"workflow_completion:{workflow}",
1126
+ f"workflow_completion: {workflow}",
1077
1127
  t0,
1078
1128
  time.time(),
1079
- trace_kind="workflow" if refs else None,
1129
+ trace_kind="workflow",
1080
1130
  refs=refs,
1081
1131
  )
1082
1132
  return result_dict
@@ -1096,20 +1146,20 @@ class WorkflowContext:
1096
1146
  result["session_id"] = nested_session_id
1097
1147
  refs = self._workflow_span_refs(result, workflow)
1098
1148
  self._record_span(
1099
- f"workflow_completion:{workflow}",
1149
+ f"workflow_completion: {workflow}",
1100
1150
  t0,
1101
1151
  time.time(),
1102
- trace_kind="workflow" if refs else None,
1152
+ trace_kind="workflow",
1103
1153
  refs=refs,
1104
1154
  )
1105
1155
  return result
1106
1156
  wrapped = {"output": result, "session_id": nested_session_id}
1107
1157
  refs = self._workflow_span_refs(wrapped, workflow)
1108
1158
  self._record_span(
1109
- f"workflow_completion:{workflow}",
1159
+ f"workflow_completion: {workflow}",
1110
1160
  t0,
1111
1161
  time.time(),
1112
- trace_kind="workflow" if refs else None,
1162
+ trace_kind="workflow",
1113
1163
  refs=refs,
1114
1164
  )
1115
1165
  return wrapped
@@ -1184,7 +1234,12 @@ class WorkflowContext:
1184
1234
  elapsed_ms=round((time.time() - t0) * 1000, 2),
1185
1235
  )
1186
1236
  return None
1187
- self._record_span(f"workflow_completion_inproc:{base_ref}", t0, time.time())
1237
+ self._record_span(
1238
+ f"workflow_completion_inproc: {base_ref}",
1239
+ t0,
1240
+ time.time(),
1241
+ trace_kind="workflow",
1242
+ )
1188
1243
  raise
1189
1244
 
1190
1245
  t_done = time.time()
@@ -1192,10 +1247,10 @@ class WorkflowContext:
1192
1247
  result if isinstance(result, dict) else {}, base_ref
1193
1248
  )
1194
1249
  self._record_span(
1195
- f"workflow_completion_inproc:{base_ref}",
1250
+ f"workflow_completion_inproc: {base_ref}",
1196
1251
  t0,
1197
1252
  t_done,
1198
- trace_kind="workflow" if refs else None,
1253
+ trace_kind="workflow",
1199
1254
  refs=refs,
1200
1255
  )
1201
1256
  elapsed_ms = round((t_done - t0) * 1000, 2)
@@ -1254,11 +1309,21 @@ class WorkflowContext:
1254
1309
  ],
1255
1310
  )
1256
1311
  answer = (response.choices[0].message.content or "").strip()
1257
- self._record_span("web_search", t0, time.time())
1312
+ self._record_span(
1313
+ f"web_search: {_truncate_detail(query)}",
1314
+ t0,
1315
+ time.time(),
1316
+ trace_kind="search",
1317
+ )
1258
1318
  return answer
1259
1319
  except Exception as e:
1260
1320
  logger.warning("web_search failed: %s", e)
1261
- self._record_span("web_search", t0, time.time())
1321
+ self._record_span(
1322
+ f"web_search: {_truncate_detail(query)}",
1323
+ t0,
1324
+ time.time(),
1325
+ trace_kind="search",
1326
+ )
1262
1327
  return ""
1263
1328
 
1264
1329
  def _perplexity_search_api(self, query: str, api_key: str) -> str:
@@ -1281,11 +1346,21 @@ class WorkflowContext:
1281
1346
  for r in data.get("results", [])
1282
1347
  if r.get("snippet")
1283
1348
  ]
1284
- self._record_span("web_search_raw", t0, time.time())
1349
+ self._record_span(
1350
+ f"web_search: {_truncate_detail(query)}",
1351
+ t0,
1352
+ time.time(),
1353
+ trace_kind="search",
1354
+ )
1285
1355
  return "\n\n".join(snippets)
1286
1356
  except Exception as e:
1287
1357
  logger.warning("Perplexity Search API failed: %s", e)
1288
- self._record_span("web_search_raw", t0, time.time())
1358
+ self._record_span(
1359
+ f"web_search: {_truncate_detail(query)}",
1360
+ t0,
1361
+ time.time(),
1362
+ trace_kind="search",
1363
+ )
1289
1364
  return ""
1290
1365
 
1291
1366
  def _embeddings_create(
@@ -1303,10 +1378,11 @@ class WorkflowContext:
1303
1378
 
1304
1379
  default_model = os.environ.get("EMBEDDING_MODEL", "Qwen/Qwen3-Embedding-4B")
1305
1380
 
1381
+ resolved_model = model or default_model
1306
1382
  url = f"{base_url}/embeddings"
1307
1383
  payload = {
1308
1384
  "input": input if isinstance(input, list) else [input],
1309
- "model": model or default_model,
1385
+ "model": resolved_model,
1310
1386
  **kwargs,
1311
1387
  }
1312
1388
 
@@ -1322,11 +1398,21 @@ class WorkflowContext:
1322
1398
  )
1323
1399
  resp.raise_for_status()
1324
1400
  data = resp.json()
1325
- self._record_span("embeddings_create", t0, time.time())
1401
+ self._record_span(
1402
+ f"embeddings: {resolved_model}",
1403
+ t0,
1404
+ time.time(),
1405
+ trace_kind="embeddings",
1406
+ )
1326
1407
  return data
1327
1408
  except Exception as e:
1328
1409
  logger.error("Embeddings creation failed: %s", e)
1329
- self._record_span("embeddings_create_error", t0, time.time())
1410
+ self._record_span(
1411
+ f"embeddings: {resolved_model}",
1412
+ t0,
1413
+ time.time(),
1414
+ trace_kind="embeddings",
1415
+ )
1330
1416
  raise
1331
1417
 
1332
1418
  def request(
@@ -1398,7 +1484,12 @@ class WorkflowContext:
1398
1484
  if attempt < max_attempts - 1:
1399
1485
  time.sleep(retry_backoff * (2**attempt))
1400
1486
  continue
1401
- self._record_span("api_request", t0, time.time())
1487
+ self._record_span(
1488
+ f"{method_upper} {path or host or url}",
1489
+ t0,
1490
+ time.time(),
1491
+ trace_kind="http",
1492
+ )
1402
1493
  self.log(
1403
1494
  "request_error",
1404
1495
  method=method_upper,
@@ -1424,7 +1515,12 @@ class WorkflowContext:
1424
1515
  assert resp is not None # loop either returns a response or raises
1425
1516
 
1426
1517
  elapsed_ms = round((time.time() - t0) * 1000, 2)
1427
- self._record_span("api_request", t0, time.time())
1518
+ self._record_span(
1519
+ f"{method_upper} {path or host or url}",
1520
+ t0,
1521
+ time.time(),
1522
+ trace_kind="http",
1523
+ )
1428
1524
 
1429
1525
  try:
1430
1526
  parsed_json: Optional[Any] = resp.json()