synth-ai 0.2.17__py3-none-any.whl → 0.2.19__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.
Potentially problematic release.
This version of synth-ai might be problematic. Click here for more details.
- examples/baseline/banking77_baseline.py +204 -0
- examples/baseline/crafter_baseline.py +407 -0
- examples/baseline/pokemon_red_baseline.py +326 -0
- examples/baseline/simple_baseline.py +56 -0
- examples/baseline/warming_up_to_rl_baseline.py +239 -0
- examples/blog_posts/gepa/README.md +355 -0
- examples/blog_posts/gepa/configs/banking77_gepa_local.toml +95 -0
- examples/blog_posts/gepa/configs/banking77_gepa_test.toml +82 -0
- examples/blog_posts/gepa/configs/banking77_mipro_local.toml +52 -0
- examples/blog_posts/gepa/configs/hotpotqa_gepa_local.toml +59 -0
- examples/blog_posts/gepa/configs/hotpotqa_gepa_qwen.toml +36 -0
- examples/blog_posts/gepa/configs/hotpotqa_mipro_local.toml +53 -0
- examples/blog_posts/gepa/configs/hover_gepa_local.toml +59 -0
- examples/blog_posts/gepa/configs/hover_gepa_qwen.toml +36 -0
- examples/blog_posts/gepa/configs/hover_mipro_local.toml +53 -0
- examples/blog_posts/gepa/configs/ifbench_gepa_local.toml +59 -0
- examples/blog_posts/gepa/configs/ifbench_gepa_qwen.toml +36 -0
- examples/blog_posts/gepa/configs/ifbench_mipro_local.toml +53 -0
- examples/blog_posts/gepa/configs/pupa_gepa_local.toml +60 -0
- examples/blog_posts/gepa/configs/pupa_mipro_local.toml +54 -0
- examples/blog_posts/gepa/deploy_banking77_task_app.sh +41 -0
- examples/blog_posts/gepa/gepa_baseline.py +204 -0
- examples/blog_posts/gepa/query_prompts_example.py +97 -0
- examples/blog_posts/gepa/run_gepa_banking77.sh +87 -0
- examples/blog_posts/gepa/task_apps.py +105 -0
- examples/blog_posts/gepa/test_gepa_local.sh +67 -0
- examples/blog_posts/gepa/verify_banking77_setup.sh +123 -0
- examples/blog_posts/pokemon_vl/configs/eval_gpt5nano.toml +26 -0
- examples/blog_posts/pokemon_vl/configs/eval_qwen3_vl.toml +12 -10
- examples/blog_posts/pokemon_vl/configs/train_rl_from_sft.toml +1 -0
- examples/blog_posts/pokemon_vl/extract_images.py +239 -0
- examples/blog_posts/pokemon_vl/pokemon_vl_baseline.py +326 -0
- examples/blog_posts/pokemon_vl/run_eval_extract_images.py +209 -0
- examples/blog_posts/pokemon_vl/run_qwen_eval_extract_images.py +212 -0
- examples/blog_posts/pokemon_vl/text_box_analysis.md +106 -0
- examples/blog_posts/warming_up_to_rl/ARCHITECTURE.md +195 -0
- examples/blog_posts/warming_up_to_rl/FINAL_TEST_RESULTS.md +127 -0
- examples/blog_posts/warming_up_to_rl/INFERENCE_SUCCESS.md +132 -0
- examples/blog_posts/warming_up_to_rl/SMOKE_TESTING.md +164 -0
- examples/blog_posts/warming_up_to_rl/SMOKE_TEST_COMPLETE.md +253 -0
- examples/blog_posts/warming_up_to_rl/configs/eval_baseline_qwen32b_10x20.toml +25 -0
- examples/blog_posts/warming_up_to_rl/configs/eval_ft_qwen4b_10x20.toml +26 -0
- examples/blog_posts/warming_up_to_rl/configs/filter_high_reward_dataset.toml +1 -1
- examples/blog_posts/warming_up_to_rl/configs/smoke_test.toml +75 -0
- examples/blog_posts/warming_up_to_rl/configs/train_rl_from_sft.toml +60 -10
- examples/blog_posts/warming_up_to_rl/configs/train_sft_qwen4b.toml +1 -1
- examples/blog_posts/warming_up_to_rl/warming_up_to_rl_baseline.py +187 -0
- examples/multi_step/configs/VERILOG_REWARDS.md +4 -0
- examples/multi_step/configs/VERILOG_RL_CHECKLIST.md +4 -0
- examples/multi_step/configs/crafter_rl_outcome.toml +1 -0
- examples/multi_step/configs/crafter_rl_stepwise_shaped.toml +1 -0
- examples/multi_step/configs/crafter_rl_stepwise_simple.toml +1 -0
- examples/rl/configs/rl_from_base_qwen17.toml +1 -0
- examples/swe/task_app/hosted/inference/openai_client.py +0 -34
- examples/swe/task_app/hosted/policy_routes.py +17 -0
- examples/swe/task_app/hosted/rollout.py +4 -2
- examples/task_apps/banking77/__init__.py +6 -0
- examples/task_apps/banking77/banking77_task_app.py +841 -0
- examples/task_apps/banking77/deploy_wrapper.py +46 -0
- examples/task_apps/crafter/CREATE_SFT_DATASET.md +4 -0
- examples/task_apps/crafter/FILTER_COMMAND_STATUS.md +4 -0
- examples/task_apps/crafter/FILTER_COMMAND_SUCCESS.md +4 -0
- examples/task_apps/crafter/task_app/grpo_crafter.py +24 -2
- examples/task_apps/crafter/task_app/synth_envs_hosted/hosted_app.py +49 -0
- examples/task_apps/crafter/task_app/synth_envs_hosted/inference/openai_client.py +355 -58
- examples/task_apps/crafter/task_app/synth_envs_hosted/policy_routes.py +68 -7
- examples/task_apps/crafter/task_app/synth_envs_hosted/rollout.py +78 -21
- examples/task_apps/crafter/task_app/synth_envs_hosted/utils.py +194 -1
- examples/task_apps/gepa_benchmarks/__init__.py +7 -0
- examples/task_apps/gepa_benchmarks/common.py +260 -0
- examples/task_apps/gepa_benchmarks/hotpotqa_task_app.py +507 -0
- examples/task_apps/gepa_benchmarks/hover_task_app.py +436 -0
- examples/task_apps/gepa_benchmarks/ifbench_task_app.py +563 -0
- examples/task_apps/gepa_benchmarks/pupa_task_app.py +460 -0
- examples/task_apps/pokemon_red/README_IMAGE_ONLY_EVAL.md +4 -0
- examples/task_apps/pokemon_red/task_app.py +254 -36
- examples/warming_up_to_rl/configs/rl_from_base_qwen4b.toml +1 -0
- examples/warming_up_to_rl/task_app/grpo_crafter.py +53 -4
- examples/warming_up_to_rl/task_app/synth_envs_hosted/hosted_app.py +49 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/inference/openai_client.py +152 -41
- examples/warming_up_to_rl/task_app/synth_envs_hosted/policy_routes.py +31 -1
- examples/warming_up_to_rl/task_app/synth_envs_hosted/rollout.py +33 -3
- examples/warming_up_to_rl/task_app/synth_envs_hosted/utils.py +67 -0
- examples/workflows/math_rl/configs/rl_from_base_qwen17.toml +1 -0
- synth_ai/api/train/builders.py +90 -1
- synth_ai/api/train/cli.py +396 -21
- synth_ai/api/train/config_finder.py +13 -2
- synth_ai/api/train/configs/__init__.py +15 -1
- synth_ai/api/train/configs/prompt_learning.py +442 -0
- synth_ai/api/train/configs/rl.py +29 -0
- synth_ai/api/train/task_app.py +1 -1
- synth_ai/api/train/validators.py +277 -0
- synth_ai/baseline/__init__.py +25 -0
- synth_ai/baseline/config.py +209 -0
- synth_ai/baseline/discovery.py +214 -0
- synth_ai/baseline/execution.py +146 -0
- synth_ai/cli/__init__.py +85 -17
- synth_ai/cli/__main__.py +0 -0
- synth_ai/cli/claude.py +70 -0
- synth_ai/cli/codex.py +84 -0
- synth_ai/cli/commands/__init__.py +1 -0
- synth_ai/cli/commands/baseline/__init__.py +12 -0
- synth_ai/cli/commands/baseline/core.py +637 -0
- synth_ai/cli/commands/baseline/list.py +93 -0
- synth_ai/cli/commands/eval/core.py +13 -10
- synth_ai/cli/commands/filter/core.py +53 -17
- synth_ai/cli/commands/help/core.py +0 -1
- synth_ai/cli/commands/smoke/__init__.py +7 -0
- synth_ai/cli/commands/smoke/core.py +1436 -0
- synth_ai/cli/commands/status/subcommands/pricing.py +22 -0
- synth_ai/cli/commands/status/subcommands/usage.py +203 -0
- synth_ai/cli/commands/train/judge_schemas.py +1 -0
- synth_ai/cli/commands/train/judge_validation.py +1 -0
- synth_ai/cli/commands/train/validation.py +0 -57
- synth_ai/cli/demo.py +35 -3
- synth_ai/cli/deploy/__init__.py +40 -25
- synth_ai/cli/deploy.py +162 -0
- synth_ai/cli/legacy_root_backup.py +14 -8
- synth_ai/cli/opencode.py +107 -0
- synth_ai/cli/root.py +9 -5
- synth_ai/cli/task_app_deploy.py +1 -1
- synth_ai/cli/task_apps.py +53 -53
- synth_ai/environments/examples/crafter_classic/engine_deterministic_patch.py +7 -4
- synth_ai/environments/examples/crafter_classic/engine_serialization_patch_v3.py +9 -5
- synth_ai/environments/examples/crafter_classic/world_config_patch_simple.py +4 -3
- synth_ai/judge_schemas.py +1 -0
- synth_ai/learning/__init__.py +10 -0
- synth_ai/learning/prompt_learning_client.py +276 -0
- synth_ai/learning/prompt_learning_types.py +184 -0
- synth_ai/pricing/__init__.py +2 -0
- synth_ai/pricing/model_pricing.py +57 -0
- synth_ai/streaming/handlers.py +53 -4
- synth_ai/streaming/streamer.py +19 -0
- synth_ai/task/apps/__init__.py +1 -0
- synth_ai/task/config.py +2 -0
- synth_ai/task/tracing_utils.py +25 -25
- synth_ai/task/validators.py +44 -8
- synth_ai/task_app_cfgs.py +21 -0
- synth_ai/tracing_v3/config.py +162 -19
- synth_ai/tracing_v3/constants.py +1 -1
- synth_ai/tracing_v3/db_config.py +24 -38
- synth_ai/tracing_v3/storage/config.py +47 -13
- synth_ai/tracing_v3/storage/factory.py +3 -3
- synth_ai/tracing_v3/turso/daemon.py +113 -11
- synth_ai/tracing_v3/turso/native_manager.py +92 -16
- synth_ai/types.py +8 -0
- synth_ai/urls.py +11 -0
- synth_ai/utils/__init__.py +30 -1
- synth_ai/utils/agents.py +74 -0
- synth_ai/utils/bin.py +39 -0
- synth_ai/utils/cli.py +149 -5
- synth_ai/utils/env.py +17 -17
- synth_ai/utils/json.py +72 -0
- synth_ai/utils/modal.py +283 -1
- synth_ai/utils/paths.py +48 -0
- synth_ai/utils/uvicorn.py +113 -0
- {synth_ai-0.2.17.dist-info → synth_ai-0.2.19.dist-info}/METADATA +102 -4
- {synth_ai-0.2.17.dist-info → synth_ai-0.2.19.dist-info}/RECORD +162 -88
- synth_ai/cli/commands/deploy/__init__.py +0 -23
- synth_ai/cli/commands/deploy/core.py +0 -614
- synth_ai/cli/commands/deploy/errors.py +0 -72
- synth_ai/cli/commands/deploy/validation.py +0 -11
- synth_ai/cli/deploy/core.py +0 -5
- synth_ai/cli/deploy/errors.py +0 -23
- synth_ai/cli/deploy/validation.py +0 -5
- {synth_ai-0.2.17.dist-info → synth_ai-0.2.19.dist-info}/WHEEL +0 -0
- {synth_ai-0.2.17.dist-info → synth_ai-0.2.19.dist-info}/entry_points.txt +0 -0
- {synth_ai-0.2.17.dist-info → synth_ai-0.2.19.dist-info}/licenses/LICENSE +0 -0
- {synth_ai-0.2.17.dist-info → synth_ai-0.2.19.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,841 @@
|
|
|
1
|
+
"""Banking77 intent classification task app for Synth prompt optimization benchmarks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import uuid
|
|
9
|
+
from collections.abc import Iterable, Sequence
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Mapping, cast
|
|
12
|
+
import socket
|
|
13
|
+
from urllib.parse import urlparse
|
|
14
|
+
|
|
15
|
+
# removed top-level httpx and datasets import to allow modal deploy without local deps
|
|
16
|
+
from fastapi import APIRouter, HTTPException, Request
|
|
17
|
+
from pydantic import BaseModel
|
|
18
|
+
from dotenv import load_dotenv
|
|
19
|
+
|
|
20
|
+
from fastapi.exceptions import RequestValidationError
|
|
21
|
+
from fastapi.responses import JSONResponse
|
|
22
|
+
from starlette.requests import Request as StarletteRequest
|
|
23
|
+
|
|
24
|
+
from synth_ai.task.apps import ModalDeploymentConfig, TaskAppEntry, register_task_app
|
|
25
|
+
from synth_ai.task.auth import is_api_key_header_authorized, normalize_environment_api_key
|
|
26
|
+
from synth_ai.task.contracts import (
|
|
27
|
+
RolloutMetrics,
|
|
28
|
+
RolloutRequest,
|
|
29
|
+
RolloutResponse,
|
|
30
|
+
RolloutStep,
|
|
31
|
+
RolloutTrajectory,
|
|
32
|
+
TaskInfo,
|
|
33
|
+
)
|
|
34
|
+
from synth_ai.task.datasets import TaskDatasetRegistry, TaskDatasetSpec
|
|
35
|
+
from synth_ai.task.rubrics import Rubric, load_rubric
|
|
36
|
+
from synth_ai.task.server import ProxyConfig, RubricBundle, TaskAppConfig, create_task_app, run_task_app
|
|
37
|
+
from synth_ai.task.vendors import normalize_vendor_keys
|
|
38
|
+
|
|
39
|
+
def _compute_repo_root() -> Path:
|
|
40
|
+
p = Path(__file__).resolve()
|
|
41
|
+
parents = list(p.parents)
|
|
42
|
+
if len(parents) >= 4:
|
|
43
|
+
# parents[3] exists when file is within repo (e.g., examples/task_apps/…)
|
|
44
|
+
return parents[3]
|
|
45
|
+
# Modal inline deploy: code may be at /root/*.py, but we mount synth_ai at /opt/synth_ai_repo/synth_ai
|
|
46
|
+
if "/opt/synth_ai_repo" in os.getenv("PYTHONPATH", "") or Path("/opt/synth_ai_repo/synth_ai").exists():
|
|
47
|
+
return Path("/opt/synth_ai_repo")
|
|
48
|
+
# Fallback to current working directory
|
|
49
|
+
return Path.cwd()
|
|
50
|
+
|
|
51
|
+
REPO_ROOT = _compute_repo_root()
|
|
52
|
+
|
|
53
|
+
# Dataset configuration
|
|
54
|
+
DATASET_NAME = os.getenv("BANKING77_DATASET_NAME", "banking77")
|
|
55
|
+
DEFAULT_SPLIT = "train"
|
|
56
|
+
AVAILABLE_SPLITS: tuple[str, ...] = ("train", "test")
|
|
57
|
+
TOOL_NAME = "banking77_classify"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Banking77Dataset:
|
|
61
|
+
"""Lazy Hugging Face dataset loader for Banking77."""
|
|
62
|
+
|
|
63
|
+
def __init__(self) -> None:
|
|
64
|
+
self._cache: dict[str, Any] = {}
|
|
65
|
+
self._label_names: list[str] | None = None
|
|
66
|
+
|
|
67
|
+
def _load_split(self, split: str):
|
|
68
|
+
if split not in AVAILABLE_SPLITS:
|
|
69
|
+
raise ValueError(f"Unknown split: {split}. Available: {AVAILABLE_SPLITS}")
|
|
70
|
+
if split not in self._cache:
|
|
71
|
+
try:
|
|
72
|
+
from datasets import load_dataset as _load_dataset # lazy import
|
|
73
|
+
ds = _load_dataset(DATASET_NAME, split=split, trust_remote_code=False)
|
|
74
|
+
self._cache[split] = ds
|
|
75
|
+
if self._label_names is None and hasattr(ds.features.get("label"), "names"):
|
|
76
|
+
self._label_names = ds.features["label"].names
|
|
77
|
+
except Exception as exc:
|
|
78
|
+
raise RuntimeError(
|
|
79
|
+
f"Dataset preparation failed: {split}: Failed to download Banking77 dataset from Hugging Face. "
|
|
80
|
+
f"Dataset: {DATASET_NAME} | Split: {split}"
|
|
81
|
+
) from exc
|
|
82
|
+
return self._cache[split]
|
|
83
|
+
|
|
84
|
+
def ensure_ready(self, splits: Sequence[str]) -> None:
|
|
85
|
+
for split in splits:
|
|
86
|
+
self._load_split(split)
|
|
87
|
+
|
|
88
|
+
def size(self, split: str) -> int:
|
|
89
|
+
dataset = self._load_split(split)
|
|
90
|
+
return len(dataset)
|
|
91
|
+
|
|
92
|
+
def sample(self, *, split: str, index: int) -> dict[str, Any]:
|
|
93
|
+
dataset = self._load_split(split)
|
|
94
|
+
size = len(dataset)
|
|
95
|
+
if size == 0:
|
|
96
|
+
raise RuntimeError(f"Banking77 split '{split}' is empty")
|
|
97
|
+
idx = int(index) % size
|
|
98
|
+
row = dataset[int(idx)]
|
|
99
|
+
|
|
100
|
+
label_idx = int(row.get("label", 0))
|
|
101
|
+
label_text = self.get_label_name(label_idx)
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
"index": idx,
|
|
105
|
+
"split": split,
|
|
106
|
+
"text": str(row.get("text", "")),
|
|
107
|
+
"label": label_text,
|
|
108
|
+
"label_idx": label_idx,
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
def get_label_name(self, label_idx: int) -> str:
|
|
112
|
+
if self._label_names is None:
|
|
113
|
+
self._load_split(DEFAULT_SPLIT)
|
|
114
|
+
if self._label_names and 0 <= label_idx < len(self._label_names):
|
|
115
|
+
return self._label_names[label_idx]
|
|
116
|
+
return f"label_{label_idx}"
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def label_names(self) -> list[str]:
|
|
120
|
+
if self._label_names is None:
|
|
121
|
+
self._load_split(DEFAULT_SPLIT)
|
|
122
|
+
return self._label_names or []
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
banking77_router = APIRouter()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
BANKING77_DATASET_SPEC = TaskDatasetSpec(
|
|
129
|
+
id="banking77",
|
|
130
|
+
name="Banking77 Intent Classification",
|
|
131
|
+
version="1.0.0",
|
|
132
|
+
splits=list(AVAILABLE_SPLITS),
|
|
133
|
+
default_split=DEFAULT_SPLIT,
|
|
134
|
+
description="Banking customer query intent classification with 77 intent categories.",
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class ClassifyRequest(BaseModel):
|
|
139
|
+
query: str
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class ClassifyResponse(BaseModel):
|
|
143
|
+
intent: str
|
|
144
|
+
confidence: float | None = None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@banking77_router.post("/classify", response_model=ClassifyResponse)
|
|
148
|
+
async def classify_endpoint(req: ClassifyRequest, request: Request):
|
|
149
|
+
dataset: Banking77Dataset = request.app.state.banking77_dataset
|
|
150
|
+
return ClassifyResponse(intent="activate_my_card", confidence=None)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
async def call_chat_completion(
|
|
154
|
+
policy_config: dict[str, Any],
|
|
155
|
+
placeholders: dict[str, Any],
|
|
156
|
+
default_messages: list[dict[str, str]],
|
|
157
|
+
) -> tuple[str, dict[str, Any] | None, list[dict[str, Any]]]:
|
|
158
|
+
# STRICT: require all policy fields to come from TOML (no defaults)
|
|
159
|
+
missing_fields: list[str] = []
|
|
160
|
+
# Always require model; provider optional when routing via proxy
|
|
161
|
+
model_val = policy_config.get("model")
|
|
162
|
+
if not isinstance(model_val, str) or not model_val.strip():
|
|
163
|
+
missing_fields.append("model")
|
|
164
|
+
# Resolve routing base from any of the accepted keys
|
|
165
|
+
route_base = (
|
|
166
|
+
(policy_config.get("inference_url") or "").strip()
|
|
167
|
+
or (policy_config.get("api_base") or "").strip()
|
|
168
|
+
or (policy_config.get("base_url") or "").strip()
|
|
169
|
+
)
|
|
170
|
+
if not route_base:
|
|
171
|
+
missing_fields.append("inference_url")
|
|
172
|
+
if missing_fields:
|
|
173
|
+
raise HTTPException(
|
|
174
|
+
status_code=400,
|
|
175
|
+
detail=(
|
|
176
|
+
"Missing policy fields in TOML [prompt_learning.policy]: " + ", ".join(missing_fields)
|
|
177
|
+
),
|
|
178
|
+
)
|
|
179
|
+
model = policy_config["model"].strip()
|
|
180
|
+
provider = str(policy_config.get("provider", "")).strip() or "groq"
|
|
181
|
+
lowered = route_base.lower()
|
|
182
|
+
is_provider_host = ("api.openai.com" in lowered) or ("api.groq.com" in lowered)
|
|
183
|
+
# Normalize inference URL: allow bases like .../v1 and auto-append /chat/completions
|
|
184
|
+
def _normalize_chat_url(url: str) -> str:
|
|
185
|
+
u = (url or "").rstrip("/")
|
|
186
|
+
if u.endswith("/chat/completions"):
|
|
187
|
+
return u
|
|
188
|
+
if u.endswith("/v1"):
|
|
189
|
+
return u + "/chat/completions"
|
|
190
|
+
if u.endswith("/completions"):
|
|
191
|
+
return u.rsplit("/", 1)[0] + "/chat/completions"
|
|
192
|
+
return u + "/chat/completions"
|
|
193
|
+
inference_url = _normalize_chat_url(str(route_base))
|
|
194
|
+
temperature = policy_config.get("temperature", 0.7)
|
|
195
|
+
max_tokens = policy_config.get("max_completion_tokens", 100)
|
|
196
|
+
|
|
197
|
+
# Loud route log
|
|
198
|
+
with contextlib.suppress(Exception):
|
|
199
|
+
print(f"[TASK_APP] POLICY ROUTE → {inference_url}", flush=True)
|
|
200
|
+
|
|
201
|
+
messages = []
|
|
202
|
+
for msg_template in default_messages:
|
|
203
|
+
role = msg_template.get("role", "user")
|
|
204
|
+
pattern = msg_template.get("pattern", "")
|
|
205
|
+
content = pattern.format(**placeholders)
|
|
206
|
+
messages.append({"role": role, "content": content})
|
|
207
|
+
|
|
208
|
+
# Loud logging of rendered messages (trim for safety)
|
|
209
|
+
preview = [
|
|
210
|
+
{"role": m.get("role"), "len": len(m.get("content", "")), "head": (m.get("content", "")[:160])}
|
|
211
|
+
for m in messages
|
|
212
|
+
]
|
|
213
|
+
print(f"[TASK_APP] MESSAGES: {preview}", flush=True)
|
|
214
|
+
|
|
215
|
+
# Assert we are NOT hitting a provider host directly for policy
|
|
216
|
+
if is_provider_host:
|
|
217
|
+
# Print full policy config for forensics
|
|
218
|
+
with contextlib.suppress(Exception):
|
|
219
|
+
print(
|
|
220
|
+
f"[TASK_APP] POLICY_CONFIG: {json.dumps(policy_config, ensure_ascii=False)}",
|
|
221
|
+
flush=True,
|
|
222
|
+
)
|
|
223
|
+
raise HTTPException(status_code=502, detail=f"Direct provider URL not allowed for policy: {route_base}")
|
|
224
|
+
|
|
225
|
+
# If routing to proxy/interceptor, DO NOT require or send provider API key
|
|
226
|
+
headers: dict[str, str]
|
|
227
|
+
headers = {"Content-Type": "application/json"}
|
|
228
|
+
with contextlib.suppress(Exception):
|
|
229
|
+
print("[TASK_APP] PROXY ROUTING (no provider key sent)", flush=True)
|
|
230
|
+
|
|
231
|
+
# Define tool schema for banking77 classification (no enum to keep payload small)
|
|
232
|
+
classify_tool = {
|
|
233
|
+
"type": "function",
|
|
234
|
+
"function": {
|
|
235
|
+
"name": TOOL_NAME,
|
|
236
|
+
"description": "Return the predicted banking77 intent label in the `intent` field.",
|
|
237
|
+
"parameters": {
|
|
238
|
+
"type": "object",
|
|
239
|
+
"properties": {"intent": {"type": "string"}},
|
|
240
|
+
"required": ["intent"],
|
|
241
|
+
},
|
|
242
|
+
},
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
payload = {
|
|
246
|
+
"model": model,
|
|
247
|
+
"messages": messages,
|
|
248
|
+
"temperature": temperature,
|
|
249
|
+
"max_tokens": max_tokens,
|
|
250
|
+
"tools": [classify_tool],
|
|
251
|
+
"tool_choice": {"type": "function", "function": {"name": TOOL_NAME}},
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
print(
|
|
255
|
+
f"[TASK_APP] OUTBOUND: model={model} temp={temperature} max={max_tokens} tools=1 choice={TOOL_NAME}",
|
|
256
|
+
flush=True,
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
# Lazy import httpx to avoid top-level import during modal code gen
|
|
260
|
+
try:
|
|
261
|
+
import httpx # type: ignore
|
|
262
|
+
except Exception as _exc: # pragma: no cover
|
|
263
|
+
raise HTTPException(status_code=500, detail=f"httpx unavailable: {_exc}")
|
|
264
|
+
|
|
265
|
+
# Proxy target diagnostics (no preflight health; we go straight to POST)
|
|
266
|
+
try:
|
|
267
|
+
parsed = urlparse(inference_url)
|
|
268
|
+
host = parsed.hostname or ""
|
|
269
|
+
port = parsed.port or (443 if parsed.scheme == "https" else 80)
|
|
270
|
+
print(f"[TASK_APP] PROXY_TARGET: scheme={parsed.scheme} host={host} port={port} path={parsed.path}", flush=True)
|
|
271
|
+
addrinfo = socket.getaddrinfo(host, None)
|
|
272
|
+
ips = sorted({ai[4][0] for ai in addrinfo})
|
|
273
|
+
print(f"[TASK_APP] PROXY_DNS: ips={ips}", flush=True)
|
|
274
|
+
except Exception as e:
|
|
275
|
+
print(f"[TASK_APP] PROXY_DNS_ERROR: {e}", flush=True)
|
|
276
|
+
|
|
277
|
+
async with httpx.AsyncClient(timeout=30.0) as client:
|
|
278
|
+
try:
|
|
279
|
+
response = await client.post(inference_url, json=payload, headers=headers)
|
|
280
|
+
except Exception as e:
|
|
281
|
+
print(f"[TASK_APP] POST_EXCEPTION: {type(e).__name__}: {e}", flush=True)
|
|
282
|
+
raise HTTPException(status_code=502, detail=f"Proxy POST failed: {e}")
|
|
283
|
+
# Always print status/headers/body BEFORE any error is raised
|
|
284
|
+
print(f"[TASK_APP] RESPONSE_STATUS: {response.status_code}", flush=True)
|
|
285
|
+
print(f"[TASK_APP] RESPONSE_HEADERS: {dict(response.headers)}", flush=True)
|
|
286
|
+
# Try JSON, fallback to text
|
|
287
|
+
try:
|
|
288
|
+
response_json = response.json()
|
|
289
|
+
raw = json.dumps(response_json, ensure_ascii=False)
|
|
290
|
+
print(f"[TASK_APP] RESPONSE_JSON ({len(raw)} bytes): {raw}", flush=True)
|
|
291
|
+
except Exception:
|
|
292
|
+
response_text = response.text
|
|
293
|
+
print(f"[TASK_APP] RESPONSE_TEXT ({len(response_text)} bytes): {response_text}", flush=True)
|
|
294
|
+
response.raise_for_status()
|
|
295
|
+
# If we got here, raise_for_status didn't throw; keep an empty JSON
|
|
296
|
+
response_json = {}
|
|
297
|
+
# After logging, surface HTTP errors
|
|
298
|
+
response.raise_for_status()
|
|
299
|
+
|
|
300
|
+
with contextlib.suppress(Exception):
|
|
301
|
+
usage = response_json.get("usage", {}) if isinstance(response_json, dict) else {}
|
|
302
|
+
ch = (response_json.get("choices") or [{}])[0]
|
|
303
|
+
txt = (ch.get("message", {}) or {}).get("content", "")
|
|
304
|
+
tc = (ch.get("message", {}) or {}).get("tool_calls", [])
|
|
305
|
+
print(
|
|
306
|
+
f"[TASK_APP] RESPONSE: usage={usage} choices={len(response_json.get('choices', []))} first_len={len(txt)} tool_calls={len(tc)}",
|
|
307
|
+
flush=True,
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
# Hard assertions: require either tool_calls or non-empty content
|
|
311
|
+
try:
|
|
312
|
+
choices = response_json.get("choices") or []
|
|
313
|
+
first_msg = (choices[0] or {}).get("message", {}) if choices else {}
|
|
314
|
+
tool_calls = first_msg.get("tool_calls", []) or []
|
|
315
|
+
content_text = str(first_msg.get("content", ""))
|
|
316
|
+
if not tool_calls and not content_text.strip():
|
|
317
|
+
raise HTTPException(status_code=502, detail="Empty model output: no tool_calls and no content")
|
|
318
|
+
# If tool_calls present, validate schema
|
|
319
|
+
if tool_calls:
|
|
320
|
+
for call in tool_calls:
|
|
321
|
+
fn = (call or {}).get("function", {}) or {}
|
|
322
|
+
if fn.get("name") != TOOL_NAME:
|
|
323
|
+
raise HTTPException(status_code=502, detail=f"Unexpected tool name: {fn.get('name')}")
|
|
324
|
+
args_raw = fn.get("arguments", "{}")
|
|
325
|
+
try:
|
|
326
|
+
args = json.loads(args_raw)
|
|
327
|
+
except Exception:
|
|
328
|
+
raise HTTPException(status_code=502, detail="Tool call arguments not valid JSON")
|
|
329
|
+
if not str(args.get("intent", "")).strip():
|
|
330
|
+
raise HTTPException(status_code=502, detail="Tool call missing 'intent'")
|
|
331
|
+
except HTTPException:
|
|
332
|
+
raise
|
|
333
|
+
except Exception as exc:
|
|
334
|
+
# Convert unexpected errors to HTTP for visibility
|
|
335
|
+
raise HTTPException(status_code=500, detail=f"Response validation failed: {exc}")
|
|
336
|
+
|
|
337
|
+
response_text = ""
|
|
338
|
+
tool_calls = []
|
|
339
|
+
|
|
340
|
+
if "choices" in response_json and len(response_json["choices"]) > 0:
|
|
341
|
+
choice = response_json["choices"][0]
|
|
342
|
+
message = choice.get("message", {})
|
|
343
|
+
response_text = message.get("content", "")
|
|
344
|
+
|
|
345
|
+
if "tool_calls" in message and message["tool_calls"]:
|
|
346
|
+
for tc in message["tool_calls"]:
|
|
347
|
+
tool_calls.append({
|
|
348
|
+
"id": tc.get("id", ""),
|
|
349
|
+
"type": tc.get("type", "function"),
|
|
350
|
+
"function": {
|
|
351
|
+
"name": tc.get("function", {}).get("name", ""),
|
|
352
|
+
"arguments": tc.get("function", {}).get("arguments", "{}"),
|
|
353
|
+
}
|
|
354
|
+
})
|
|
355
|
+
|
|
356
|
+
return response_text, response_json, tool_calls
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
async def rollout_executor(request: RolloutRequest, fastapi_request: Request) -> RolloutResponse:
|
|
360
|
+
dataset: Banking77Dataset = fastapi_request.app.state.banking77_dataset
|
|
361
|
+
# Inbound snapshot from GEPA
|
|
362
|
+
with contextlib.suppress(Exception):
|
|
363
|
+
cfg = (request.policy.config or {})
|
|
364
|
+
print(
|
|
365
|
+
f"[TASK_APP] INBOUND_ROLLOUT: run_id={request.run_id} seed={request.env.seed} env={request.env.env_name} "
|
|
366
|
+
f"policy.model={cfg.get('model')} provider={cfg.get('provider')} api_base={cfg.get('inference_url') or cfg.get('api_base') or cfg.get('base_url')}",
|
|
367
|
+
flush=True,
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
split = str(((request.env.config or {}).get("split")) or DEFAULT_SPLIT)
|
|
371
|
+
seed = request.env.seed or 0
|
|
372
|
+
|
|
373
|
+
sample = dataset.sample(split=split, index=seed)
|
|
374
|
+
observation = {
|
|
375
|
+
"query": sample["text"],
|
|
376
|
+
"index": sample["index"],
|
|
377
|
+
"split": sample["split"],
|
|
378
|
+
"available_intents": dataset.label_names,
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
# Format available intents as a numbered list for the prompt
|
|
382
|
+
intents_list = "\n".join(f"{i+1}. {label}" for i, label in enumerate(dataset.label_names))
|
|
383
|
+
placeholders = {
|
|
384
|
+
"query": sample["text"],
|
|
385
|
+
"available_intents": intents_list,
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
default_messages = [
|
|
389
|
+
{
|
|
390
|
+
"role": "system",
|
|
391
|
+
"pattern": (
|
|
392
|
+
"You are an expert banking assistant that classifies customer queries into banking intents. "
|
|
393
|
+
"Given a customer message, respond with exactly one intent label from the provided list using the `banking77_classify` tool."
|
|
394
|
+
),
|
|
395
|
+
},
|
|
396
|
+
{
|
|
397
|
+
"role": "user",
|
|
398
|
+
"pattern": "Customer Query: {query}\n\nClassify this query into one of the banking intents using the tool call.",
|
|
399
|
+
},
|
|
400
|
+
]
|
|
401
|
+
|
|
402
|
+
response_json: dict[str, Any] | None = None
|
|
403
|
+
response_text = ""
|
|
404
|
+
tool_calls = []
|
|
405
|
+
# Render baseline messages for validation/introspection
|
|
406
|
+
rendered_messages: list[dict[str, str]] = []
|
|
407
|
+
for msg_template in default_messages:
|
|
408
|
+
role = msg_template.get("role", "user")
|
|
409
|
+
pattern = msg_template.get("pattern", "")
|
|
410
|
+
content = pattern.format(**placeholders)
|
|
411
|
+
rendered_messages.append({"role": role, "content": content})
|
|
412
|
+
error_info: dict[str, Any] = {}
|
|
413
|
+
|
|
414
|
+
# Call proxy - HARD FAILS on any invalid/empty responses. No soft handling.
|
|
415
|
+
response_text, response_json, tool_calls = await call_chat_completion(
|
|
416
|
+
request.policy.config or {},
|
|
417
|
+
placeholders,
|
|
418
|
+
default_messages,
|
|
419
|
+
)
|
|
420
|
+
# Full upstream JSON must be present and non-empty
|
|
421
|
+
try:
|
|
422
|
+
raw_upstream = json.dumps(response_json, ensure_ascii=False)
|
|
423
|
+
except Exception:
|
|
424
|
+
raw_upstream = str(response_json)
|
|
425
|
+
print(f"[TASK_APP] UPSTREAM_RESPONSE_JSON ({len(raw_upstream)} bytes): {raw_upstream}", flush=True)
|
|
426
|
+
if not isinstance(response_json, dict) or not response_json:
|
|
427
|
+
raise RuntimeError("Proxy returned missing/empty JSON")
|
|
428
|
+
# Must have choices
|
|
429
|
+
choices = response_json.get("choices") or []
|
|
430
|
+
if not isinstance(choices, list) or len(choices) == 0:
|
|
431
|
+
raise RuntimeError("Proxy JSON missing choices")
|
|
432
|
+
first_msg = (choices[0] or {}).get("message", {}) if choices else {}
|
|
433
|
+
if not isinstance(first_msg, dict):
|
|
434
|
+
raise RuntimeError("Proxy JSON message malformed")
|
|
435
|
+
tc_list = first_msg.get("tool_calls") or []
|
|
436
|
+
content_text = str(first_msg.get("content", ""))
|
|
437
|
+
if not tc_list and not content_text.strip():
|
|
438
|
+
raise RuntimeError("Proxy JSON has neither tool_calls nor content")
|
|
439
|
+
print(f"[TASK_APP] RAW_TOOL_CALLS: {tool_calls}", flush=True)
|
|
440
|
+
|
|
441
|
+
predicted_intent = ""
|
|
442
|
+
if tool_calls:
|
|
443
|
+
for tc in tool_calls:
|
|
444
|
+
if tc.get("function", {}).get("name") == TOOL_NAME:
|
|
445
|
+
args_str = tc.get("function", {}).get("arguments", "{}")
|
|
446
|
+
try:
|
|
447
|
+
args = json.loads(args_str)
|
|
448
|
+
predicted_intent = args.get("intent", "")
|
|
449
|
+
print(f"[TASK_APP] PARSED_TOOL_INTENT: {predicted_intent}", flush=True)
|
|
450
|
+
except Exception:
|
|
451
|
+
print(f"[TASK_APP] TOOL_PARSE_ERROR: {args_str}", flush=True)
|
|
452
|
+
elif response_text:
|
|
453
|
+
predicted_intent = response_text.strip().split()[0] if response_text.strip() else ""
|
|
454
|
+
print(f"[TASK_APP] CONTENT_FALLBACK_INTENT: {predicted_intent} text_len={len(response_text or '')}", flush=True)
|
|
455
|
+
|
|
456
|
+
# Hard-crash if no prediction produced at this point
|
|
457
|
+
if not str(predicted_intent or "").strip():
|
|
458
|
+
raise RuntimeError("No prediction produced from proxy response")
|
|
459
|
+
|
|
460
|
+
expected_intent = sample["label"]
|
|
461
|
+
is_correct = (predicted_intent.lower().replace("_", " ") == expected_intent.lower().replace("_", " "))
|
|
462
|
+
reward = 1.0 if is_correct else 0.0
|
|
463
|
+
|
|
464
|
+
print(
|
|
465
|
+
f"[TASK_APP] PREDICTION: expected={expected_intent} predicted={predicted_intent} correct={is_correct}",
|
|
466
|
+
flush=True,
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
info_payload = {
|
|
470
|
+
"expected_intent": expected_intent,
|
|
471
|
+
"predicted_intent": predicted_intent,
|
|
472
|
+
"response_json": response_json,
|
|
473
|
+
"tool_calls": tool_calls,
|
|
474
|
+
"correct": is_correct,
|
|
475
|
+
# Provide messages so pattern validation can extract them reliably
|
|
476
|
+
"messages": rendered_messages,
|
|
477
|
+
**error_info,
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
with contextlib.suppress(Exception):
|
|
481
|
+
print(
|
|
482
|
+
f"[BANKING77_ROLLOUT] run_id={request.run_id} split={sample['split']} "
|
|
483
|
+
f"index={sample['index']} expected={expected_intent} predicted={predicted_intent} "
|
|
484
|
+
f"reward={reward}",
|
|
485
|
+
flush=True,
|
|
486
|
+
)
|
|
487
|
+
|
|
488
|
+
step = RolloutStep(
|
|
489
|
+
obs=observation,
|
|
490
|
+
tool_calls=tool_calls,
|
|
491
|
+
reward=reward,
|
|
492
|
+
done=True,
|
|
493
|
+
info=info_payload,
|
|
494
|
+
)
|
|
495
|
+
|
|
496
|
+
inference_url = (request.policy.config or {}).get("inference_url")
|
|
497
|
+
trajectory = RolloutTrajectory(
|
|
498
|
+
env_id=f"banking77::{sample['split']}::{sample['index']}",
|
|
499
|
+
policy_id=request.policy.policy_id or request.policy.policy_name or "policy",
|
|
500
|
+
steps=[step],
|
|
501
|
+
final={"observation": observation, "reward": reward},
|
|
502
|
+
length=1,
|
|
503
|
+
inference_url=str(inference_url or ""),
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
metrics = RolloutMetrics(
|
|
507
|
+
episode_returns=[reward],
|
|
508
|
+
mean_return=reward,
|
|
509
|
+
num_steps=1,
|
|
510
|
+
num_episodes=1,
|
|
511
|
+
outcome_score=reward,
|
|
512
|
+
events_score=reward,
|
|
513
|
+
details={"correct": is_correct},
|
|
514
|
+
)
|
|
515
|
+
|
|
516
|
+
trace_payload = None
|
|
517
|
+
include_trace = bool(
|
|
518
|
+
(request.record and getattr(request.record, "return_trace", False))
|
|
519
|
+
or os.getenv("TASKAPP_TRACING_ENABLED")
|
|
520
|
+
)
|
|
521
|
+
if include_trace:
|
|
522
|
+
trace_payload = {
|
|
523
|
+
"session_id": str(uuid.uuid4()),
|
|
524
|
+
"events_count": 1,
|
|
525
|
+
"decision_rewards": [reward],
|
|
526
|
+
"metadata": {
|
|
527
|
+
"env": "banking77",
|
|
528
|
+
"split": sample["split"],
|
|
529
|
+
"index": sample["index"],
|
|
530
|
+
"correct": is_correct,
|
|
531
|
+
},
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
return RolloutResponse(
|
|
535
|
+
run_id=request.run_id,
|
|
536
|
+
trajectories=[trajectory],
|
|
537
|
+
branches={},
|
|
538
|
+
metrics=metrics,
|
|
539
|
+
aborted=False,
|
|
540
|
+
ops_executed=2,
|
|
541
|
+
trace=trace_payload,
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def build_dataset() -> tuple[TaskDatasetRegistry, Banking77Dataset]:
|
|
546
|
+
registry = TaskDatasetRegistry()
|
|
547
|
+
dataset = Banking77Dataset()
|
|
548
|
+
# Lazy load dataset on first use to avoid cold-start latency/timeouts
|
|
549
|
+
registry.register(BANKING77_DATASET_SPEC, lambda _spec: dataset, cache=True)
|
|
550
|
+
return registry, dataset
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _base_task_info() -> TaskInfo:
|
|
554
|
+
return TaskInfo(
|
|
555
|
+
task={
|
|
556
|
+
"id": "banking77",
|
|
557
|
+
"name": "Banking77 Intent Classification",
|
|
558
|
+
"version": "1.0.0",
|
|
559
|
+
"action_space": {
|
|
560
|
+
"type": "tool_call",
|
|
561
|
+
"tool_name": TOOL_NAME,
|
|
562
|
+
"description": "Classify banking queries into one of 77 intent categories.",
|
|
563
|
+
},
|
|
564
|
+
},
|
|
565
|
+
environment="banking77",
|
|
566
|
+
dataset={
|
|
567
|
+
**BANKING77_DATASET_SPEC.model_dump(),
|
|
568
|
+
"hf_dataset": DATASET_NAME,
|
|
569
|
+
},
|
|
570
|
+
rubric={
|
|
571
|
+
"version": "1",
|
|
572
|
+
"criteria_count": 1,
|
|
573
|
+
"source": "inline",
|
|
574
|
+
},
|
|
575
|
+
inference={
|
|
576
|
+
"supports_proxy": True,
|
|
577
|
+
"tool": TOOL_NAME,
|
|
578
|
+
},
|
|
579
|
+
limits={"max_turns": 1},
|
|
580
|
+
task_metadata={"format": "tool_call"},
|
|
581
|
+
)
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def describe_taskset(dataset: Banking77Dataset) -> Mapping[str, Any]:
|
|
585
|
+
return {
|
|
586
|
+
**BANKING77_DATASET_SPEC.model_dump(),
|
|
587
|
+
"hf_dataset": DATASET_NAME,
|
|
588
|
+
"num_labels": len(dataset.label_names),
|
|
589
|
+
"sizes": {split: dataset.size(split) for split in AVAILABLE_SPLITS},
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def provide_task_instances(dataset: Banking77Dataset, seeds: Sequence[int]) -> Iterable[TaskInfo]:
|
|
594
|
+
base_info = _base_task_info()
|
|
595
|
+
for seed in seeds:
|
|
596
|
+
sample = dataset.sample(split=DEFAULT_SPLIT, index=seed)
|
|
597
|
+
yield TaskInfo(
|
|
598
|
+
task=base_info.task,
|
|
599
|
+
environment=base_info.environment,
|
|
600
|
+
dataset={
|
|
601
|
+
**base_info.dataset,
|
|
602
|
+
"split": sample["split"],
|
|
603
|
+
"index": sample["index"],
|
|
604
|
+
},
|
|
605
|
+
rubric=base_info.rubric,
|
|
606
|
+
inference=base_info.inference,
|
|
607
|
+
limits=base_info.limits,
|
|
608
|
+
task_metadata={
|
|
609
|
+
**base_info.task_metadata,
|
|
610
|
+
"query": sample["text"],
|
|
611
|
+
},
|
|
612
|
+
)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
OUTCOME_RUBRIC: Rubric = cast(
|
|
616
|
+
Rubric,
|
|
617
|
+
load_rubric(
|
|
618
|
+
{
|
|
619
|
+
"version": "1",
|
|
620
|
+
"goal_text": "Classify banking customer queries into the correct intent category.",
|
|
621
|
+
"aggregation": "weighted_sum",
|
|
622
|
+
"criteria": [
|
|
623
|
+
{
|
|
624
|
+
"id": "intent_accuracy",
|
|
625
|
+
"description": "Correctly classify the customer query into the appropriate banking intent.",
|
|
626
|
+
"weight": 1.0,
|
|
627
|
+
}
|
|
628
|
+
],
|
|
629
|
+
}
|
|
630
|
+
),
|
|
631
|
+
)
|
|
632
|
+
|
|
633
|
+
EVENTS_RUBRIC: Rubric = cast(
|
|
634
|
+
Rubric,
|
|
635
|
+
load_rubric(
|
|
636
|
+
{
|
|
637
|
+
"version": "1",
|
|
638
|
+
"goal_text": "Use the banking77_classify tool correctly.",
|
|
639
|
+
"aggregation": "weighted_sum",
|
|
640
|
+
"criteria": [
|
|
641
|
+
{
|
|
642
|
+
"id": "tool_usage",
|
|
643
|
+
"description": "Properly invoke the banking77_classify tool with the correct format.",
|
|
644
|
+
"weight": 1.0,
|
|
645
|
+
}
|
|
646
|
+
],
|
|
647
|
+
}
|
|
648
|
+
),
|
|
649
|
+
)
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def build_config() -> TaskAppConfig:
|
|
653
|
+
registry, dataset = build_dataset()
|
|
654
|
+
base_info = _base_task_info()
|
|
655
|
+
|
|
656
|
+
proxy_keys = normalize_vendor_keys()
|
|
657
|
+
proxy_config = ProxyConfig(
|
|
658
|
+
enable_openai=proxy_keys.get("OPENAI_API_KEY") is not None,
|
|
659
|
+
enable_groq=proxy_keys.get("GROQ_API_KEY") is not None,
|
|
660
|
+
system_hint="Use the banking77_classify tool to classify the customer query.",
|
|
661
|
+
)
|
|
662
|
+
|
|
663
|
+
config = TaskAppConfig(
|
|
664
|
+
app_id="banking77",
|
|
665
|
+
name="Banking77 Intent Classification Task",
|
|
666
|
+
description="Banking77 dataset task app for classifying customer queries into banking intents.",
|
|
667
|
+
base_task_info=base_info,
|
|
668
|
+
describe_taskset=lambda: describe_taskset(dataset),
|
|
669
|
+
provide_task_instances=lambda seeds: provide_task_instances(dataset, seeds),
|
|
670
|
+
rollout=rollout_executor,
|
|
671
|
+
dataset_registry=registry,
|
|
672
|
+
rubrics=RubricBundle(outcome=OUTCOME_RUBRIC, events=EVENTS_RUBRIC),
|
|
673
|
+
proxy=proxy_config,
|
|
674
|
+
routers=(banking77_router,),
|
|
675
|
+
app_state={"banking77_dataset": dataset},
|
|
676
|
+
cors_origins=["*"],
|
|
677
|
+
)
|
|
678
|
+
return config
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
register_task_app(
|
|
682
|
+
entry=TaskAppEntry(
|
|
683
|
+
app_id="banking77",
|
|
684
|
+
description="Banking77 intent classification task app using the banking77 dataset.",
|
|
685
|
+
config_factory=build_config,
|
|
686
|
+
aliases=("banking-intents",),
|
|
687
|
+
modal=ModalDeploymentConfig(
|
|
688
|
+
app_name="synth-banking77",
|
|
689
|
+
pip_packages=(
|
|
690
|
+
"datasets>=2.14.0",
|
|
691
|
+
"fastapi>=0.115.0",
|
|
692
|
+
"pydantic>=2.0.0",
|
|
693
|
+
"httpx>=0.26.0",
|
|
694
|
+
),
|
|
695
|
+
extra_local_dirs=((str(REPO_ROOT / "synth_ai"), "/opt/synth_ai_repo/synth_ai"),),
|
|
696
|
+
),
|
|
697
|
+
)
|
|
698
|
+
)
|
|
699
|
+
|
|
700
|
+
# Modal deployment
|
|
701
|
+
try:
|
|
702
|
+
import modal
|
|
703
|
+
|
|
704
|
+
# For direct Modal deployment (modal deploy banking77_task_app.py)
|
|
705
|
+
app = modal.App("synth-banking77")
|
|
706
|
+
|
|
707
|
+
_image = (
|
|
708
|
+
modal.Image.debian_slim(python_version="3.11")
|
|
709
|
+
.pip_install(
|
|
710
|
+
"synth-ai",
|
|
711
|
+
"datasets>=2.14.0",
|
|
712
|
+
"fastapi>=0.115.0",
|
|
713
|
+
"pydantic>=2.0.0",
|
|
714
|
+
"httpx>=0.26.0",
|
|
715
|
+
"python-dotenv>=1.0.0",
|
|
716
|
+
)
|
|
717
|
+
.env({"PYTHONPATH": "/opt/synth_ai_repo"})
|
|
718
|
+
.add_local_dir(str(REPO_ROOT / "synth_ai"), "/opt/synth_ai_repo/synth_ai", copy=True)
|
|
719
|
+
)
|
|
720
|
+
_env_file = REPO_ROOT / ".env"
|
|
721
|
+
if _env_file.exists():
|
|
722
|
+
_image = _image.add_local_file(str(_env_file), "/opt/synth_ai_repo/.env")
|
|
723
|
+
|
|
724
|
+
@app.function(
|
|
725
|
+
image=_image,
|
|
726
|
+
timeout=600,
|
|
727
|
+
)
|
|
728
|
+
@modal.asgi_app()
|
|
729
|
+
def web():
|
|
730
|
+
return fastapi_app()
|
|
731
|
+
|
|
732
|
+
except ImportError:
|
|
733
|
+
pass
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def fastapi_app():
|
|
737
|
+
"""Return the FastAPI application for Modal or other ASGI hosts."""
|
|
738
|
+
|
|
739
|
+
# Load environment from .env if present (works in Modal via added local file)
|
|
740
|
+
with contextlib.suppress(Exception):
|
|
741
|
+
load_dotenv(str(REPO_ROOT / ".env"), override=False)
|
|
742
|
+
|
|
743
|
+
app = create_task_app(build_config())
|
|
744
|
+
|
|
745
|
+
# Replace default health endpoints with auth-tolerant handlers
|
|
746
|
+
filtered_routes = []
|
|
747
|
+
for route in app.router.routes:
|
|
748
|
+
path = getattr(route, "path", None)
|
|
749
|
+
methods = getattr(route, "methods", set()) or set()
|
|
750
|
+
if path in {"/health", "/health/rollout"} and "GET" in methods:
|
|
751
|
+
continue
|
|
752
|
+
filtered_routes.append(route)
|
|
753
|
+
app.router.routes = filtered_routes
|
|
754
|
+
|
|
755
|
+
def _log_env_key_prefix(source: str, env_key: str | None) -> str | None:
|
|
756
|
+
if not env_key:
|
|
757
|
+
return None
|
|
758
|
+
prefix = env_key[: max(1, len(env_key) // 2)]
|
|
759
|
+
print(f"[{source}] expected ENVIRONMENT_API_KEY prefix: {prefix}")
|
|
760
|
+
return prefix
|
|
761
|
+
|
|
762
|
+
@app.get("/health")
|
|
763
|
+
async def health(request: StarletteRequest):
|
|
764
|
+
env_key = normalize_environment_api_key()
|
|
765
|
+
if not env_key:
|
|
766
|
+
return JSONResponse(
|
|
767
|
+
status_code=503,
|
|
768
|
+
content={"status": "unhealthy", "detail": "Missing ENVIRONMENT_API_KEY"},
|
|
769
|
+
)
|
|
770
|
+
if not is_api_key_header_authorized(request):
|
|
771
|
+
prefix = _log_env_key_prefix("health", env_key)
|
|
772
|
+
content = {"status": "healthy", "authorized": False}
|
|
773
|
+
if prefix:
|
|
774
|
+
content["expected_api_key_prefix"] = prefix
|
|
775
|
+
return JSONResponse(status_code=200, content=content)
|
|
776
|
+
return {"status": "healthy", "authorized": True}
|
|
777
|
+
|
|
778
|
+
@app.get("/health/rollout")
|
|
779
|
+
async def health_rollout(request: StarletteRequest):
|
|
780
|
+
env_key = normalize_environment_api_key()
|
|
781
|
+
if not env_key:
|
|
782
|
+
return JSONResponse(
|
|
783
|
+
status_code=503,
|
|
784
|
+
content={"status": "unhealthy", "detail": "Missing ENVIRONMENT_API_KEY"},
|
|
785
|
+
)
|
|
786
|
+
if not is_api_key_header_authorized(request):
|
|
787
|
+
prefix = _log_env_key_prefix("health/rollout", env_key)
|
|
788
|
+
content = {"status": "healthy", "authorized": False}
|
|
789
|
+
if prefix:
|
|
790
|
+
content["expected_api_key_prefix"] = prefix
|
|
791
|
+
return JSONResponse(status_code=200, content=content)
|
|
792
|
+
return {"ok": True, "authorized": True}
|
|
793
|
+
|
|
794
|
+
@app.exception_handler(RequestValidationError)
|
|
795
|
+
async def _on_validation_error(request: StarletteRequest, exc: RequestValidationError):
|
|
796
|
+
try:
|
|
797
|
+
hdr = request.headers
|
|
798
|
+
snapshot = {
|
|
799
|
+
"path": str(request.url.path),
|
|
800
|
+
"have_x_api_key": bool(hdr.get("x-api-key")),
|
|
801
|
+
"have_x_api_keys": bool(hdr.get("x-api-keys")),
|
|
802
|
+
"have_authorization": bool(hdr.get("authorization")),
|
|
803
|
+
"errors": exc.errors()[:5],
|
|
804
|
+
}
|
|
805
|
+
print("[422] validation", snapshot, flush=True)
|
|
806
|
+
except Exception:
|
|
807
|
+
pass
|
|
808
|
+
return JSONResponse(
|
|
809
|
+
status_code=422,
|
|
810
|
+
content={"status": "invalid", "detail": exc.errors()[:5]},
|
|
811
|
+
)
|
|
812
|
+
|
|
813
|
+
return app
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
if __name__ == "__main__":
|
|
817
|
+
import argparse
|
|
818
|
+
|
|
819
|
+
parser = argparse.ArgumentParser(description="Run the Banking77 task app locally")
|
|
820
|
+
parser.add_argument("--host", default="0.0.0.0")
|
|
821
|
+
parser.add_argument("--port", type=int, default=8102)
|
|
822
|
+
parser.add_argument("--reload", action="store_true", help="Enable uvicorn autoreload")
|
|
823
|
+
parser.add_argument(
|
|
824
|
+
"--env-file",
|
|
825
|
+
action="append",
|
|
826
|
+
default=[],
|
|
827
|
+
help="Additional .env files to load before startup",
|
|
828
|
+
)
|
|
829
|
+
args = parser.parse_args()
|
|
830
|
+
|
|
831
|
+
default_env = Path(__file__).resolve().parents[2] / ".env"
|
|
832
|
+
env_files = [str(default_env)] if default_env.exists() else []
|
|
833
|
+
env_files.extend(args.env_file or [])
|
|
834
|
+
|
|
835
|
+
run_task_app(
|
|
836
|
+
build_config,
|
|
837
|
+
host=args.host,
|
|
838
|
+
port=args.port,
|
|
839
|
+
reload=args.reload,
|
|
840
|
+
env_files=env_files,
|
|
841
|
+
)
|