Spaces:
Sleeping
Sleeping
Patchwise Agent Studio: Oracle AI Agent Studio cycles
Browse files- coworker/api/app.py +2 -2
- coworker/api/routes/agent_studio.py +37 -0
- coworker/api/routes/ai_monitoring.py +96 -0
- coworker/evals/datasets/chat_answer.json +20 -0
- coworker/evals/datasets/chat_intent.json +22 -0
- coworker/evals/datasets/self_heal.json +23 -0
- coworker/evals/datasets/summary.json +18 -0
- coworker/evals/datasets/triage.json +36 -0
- coworker/graph/services.py +2 -0
- coworker/llm/providers/frontier.py +4 -0
- coworker/llm/providers/ollama.py +3 -0
- coworker/llm/router.py +41 -2
- coworker/llm/usage.py +24 -0
- coworker/platform/agent_studio.py +158 -14
- coworker/platform/langsmith.py +203 -0
- coworker/platform/llm_evals.py +196 -0
- coworker/platform/llm_telemetry.py +96 -0
- coworker/platform/migrations/024_agent_fusion_delivery.sql +5 -0
- coworker/platform/migrations/025_llm_monitoring.sql +40 -0
- coworker/tests/test_agent_studio_fusion.py +131 -0
- coworker/tests/test_llm_monitoring.py +135 -0
- docs/AGENT_STUDIO.md +29 -0
- docs/AI_MONITORING.md +72 -0
- web/src/App.tsx +2 -0
- web/src/api/openapi.json +698 -21
- web/src/api/schema.d.ts +609 -0
- web/src/components/shell/AppSidebar.tsx +4 -2
- web/src/components/shell/IconRail.tsx +2 -2
- web/src/components/shell/TopNav.tsx +2 -2
- web/src/pages/AgentStudioPage.tsx +62 -5
- web/src/pages/AiMonitoringPage.tsx +250 -0
- web/src/pages/ai-monitoring.css +55 -0
coworker/api/app.py
CHANGED
|
@@ -16,7 +16,7 @@ from ..platform.scheduler import Scheduler
|
|
| 16 |
from . import errors
|
| 17 |
from .middleware import RequestContext, setup_logging
|
| 18 |
from . import a2a, mcp
|
| 19 |
-
from .routes import admin, agent_studio, assistant, auth, channels, chat, consultant, custom_cases, gates, integrations, live, llm, notifications, pods, review, runs, screens, tokens
|
| 20 |
from .runner import RunManager
|
| 21 |
|
| 22 |
log = logging.getLogger("fpt.api")
|
|
@@ -103,7 +103,7 @@ def create_app(svc: Services | None = None, cfg: Settings | None = None, *, back
|
|
| 103 |
app.add_middleware(RequestContext)
|
| 104 |
|
| 105 |
api = APIRouter(prefix="/api")
|
| 106 |
-
for r in (auth.router, runs.router, gates.router, review.router, admin.router, pods.router, screens.router, consultant.router, live.router, chat.router, assistant.router, llm.router, notifications.router, channels.router, integrations.router, tokens.router, custom_cases.router, agent_studio.router):
|
| 107 |
api.include_router(r)
|
| 108 |
app.include_router(api)
|
| 109 |
app.include_router(agent_studio.oauth) # /oauth/token: the Oracle AI Agent Studio client (docs/AGENT_STUDIO.md)
|
|
|
|
| 16 |
from . import errors
|
| 17 |
from .middleware import RequestContext, setup_logging
|
| 18 |
from . import a2a, mcp
|
| 19 |
+
from .routes import admin, agent_studio, ai_monitoring, assistant, auth, channels, chat, consultant, custom_cases, gates, integrations, live, llm, notifications, pods, review, runs, screens, tokens
|
| 20 |
from .runner import RunManager
|
| 21 |
|
| 22 |
log = logging.getLogger("fpt.api")
|
|
|
|
| 103 |
app.add_middleware(RequestContext)
|
| 104 |
|
| 105 |
api = APIRouter(prefix="/api")
|
| 106 |
+
for r in (auth.router, runs.router, gates.router, review.router, admin.router, pods.router, screens.router, consultant.router, live.router, chat.router, assistant.router, llm.router, notifications.router, channels.router, integrations.router, tokens.router, custom_cases.router, agent_studio.router, ai_monitoring.router):
|
| 107 |
api.include_router(r)
|
| 108 |
app.include_router(api)
|
| 109 |
app.include_router(agent_studio.oauth) # /oauth/token: the Oracle AI Agent Studio client (docs/AGENT_STUDIO.md)
|
coworker/api/routes/agent_studio.py
CHANGED
|
@@ -174,6 +174,43 @@ def update_client(client_id: str, body: ClientPatch, request: Request, user: Pri
|
|
| 174 |
_fail(e)
|
| 175 |
|
| 176 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
@router.delete("/agent-studio/clients/{client_id}", status_code=204)
|
| 178 |
def revoke_client(client_id: str, request: Request, user: Principal = Depends(require("admin"))):
|
| 179 |
try:
|
|
|
|
| 174 |
_fail(e)
|
| 175 |
|
| 176 |
|
| 177 |
+
class FusionDeliveryIn(BaseModel):
|
| 178 |
+
base_url: str = Field(min_length=8, max_length=300, description="https://<pod host>")
|
| 179 |
+
token_url: str = Field(min_length=8, max_length=400, description="the OCI IAM token address of the identity domain")
|
| 180 |
+
client_id: str = Field(min_length=1, max_length=200, description="the confidential app allowed to call invokeAsync")
|
| 181 |
+
client_secret: str | None = Field(None, max_length=400, description="write-only: kept in the vault")
|
| 182 |
+
scope: str | None = Field(None, max_length=300)
|
| 183 |
+
workflow_code: str | None = Field(None, max_length=80, description="default PATCH_TEST_CALLBACK_V3_7")
|
| 184 |
+
invocation_mode: Literal["END_USER", "ADMIN"] | None = None
|
| 185 |
+
workflow_status: Literal["PUBLISHED", "DRAFT"] | None = None
|
| 186 |
+
conversational: bool | None = None
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class DeliveryIn(BaseModel):
|
| 190 |
+
mode: Literal["url", "fusion"]
|
| 191 |
+
fusion: FusionDeliveryIn | None = None
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@router.put("/agent-studio/clients/{client_id}/delivery")
|
| 195 |
+
def set_delivery(client_id: str, body: DeliveryIn, request: Request, user: Principal = Depends(require("admin"))):
|
| 196 |
+
"""Where this client's events go: signed POSTs to its callback address, or straight to Oracle Fusion (invokeAsync)."""
|
| 197 |
+
f = body.fusion.model_dump(exclude_none=True) if body.fusion else {}
|
| 198 |
+
secret = f.pop("client_secret", None)
|
| 199 |
+
try:
|
| 200 |
+
return _studio(request).set_delivery(client_id, user.username, body.mode, f, secret)
|
| 201 |
+
except AgentStudioError as e:
|
| 202 |
+
_fail(e)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
@router.post("/agent-studio/clients/{client_id}/delivery/test")
|
| 206 |
+
def test_delivery(client_id: str, request: Request, user: Principal = Depends(require("admin"))):
|
| 207 |
+
"""Signs in to the Oracle identity domain with the saved app (no workflow is started)."""
|
| 208 |
+
try:
|
| 209 |
+
return _studio(request).test_delivery(client_id, user.username)
|
| 210 |
+
except AgentStudioError as e:
|
| 211 |
+
_fail(e)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
@router.delete("/agent-studio/clients/{client_id}", status_code=204)
|
| 215 |
def revoke_client(client_id: str, request: Request, user: Principal = Depends(require("admin"))):
|
| 216 |
try:
|
coworker/api/routes/ai_monitoring.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Settings > AI monitoring: how the AI models behave (calls, failures, fallbacks, latency, tokens), their evaluations,
|
| 2 |
+
and the optional LangSmith export. Admin only."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from fastapi import APIRouter, Depends, Query, Request
|
| 6 |
+
from pydantic import BaseModel, ConfigDict, Field
|
| 7 |
+
|
| 8 |
+
from ...platform import langsmith, llm_evals, llm_telemetry
|
| 9 |
+
from ..auth import Principal, require
|
| 10 |
+
from ..errors import ApiError
|
| 11 |
+
|
| 12 |
+
router = APIRouter(tags=["ai-monitoring"])
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class _Strict(BaseModel):
|
| 16 |
+
model_config = ConfigDict(extra="forbid")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class LangSmithIn(_Strict):
|
| 20 |
+
enabled: bool | None = None
|
| 21 |
+
project: str | None = Field(None, min_length=1, max_length=120)
|
| 22 |
+
endpoint: str | None = Field(None, max_length=300)
|
| 23 |
+
send_content: bool | None = None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class KeyIn(_Strict):
|
| 27 |
+
api_key: str = Field(min_length=8, max_length=400)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class EvalIn(_Strict):
|
| 31 |
+
target: str = Field(description="stub, local or external")
|
| 32 |
+
tasks: list[str] | None = None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@router.get("/ai/monitoring")
|
| 36 |
+
def monitoring(request: Request, days: int = Query(7, ge=1, le=90), user: Principal = Depends(require("admin"))):
|
| 37 |
+
return llm_telemetry.summary(request.app.state.svc.db, days)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@router.get("/ai/calls")
|
| 41 |
+
def calls(request: Request, limit: int = Query(100, ge=1, le=500), task: str | None = None, user: Principal = Depends(require("admin"))):
|
| 42 |
+
return {"items": llm_telemetry.recent(request.app.state.svc.db, limit, task)}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@router.get("/ai/langsmith")
|
| 46 |
+
def langsmith_view(request: Request, user: Principal = Depends(require("admin"))):
|
| 47 |
+
return langsmith.get(request.app.state.svc).view()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@router.put("/ai/langsmith")
|
| 51 |
+
def langsmith_save(body: LangSmithIn, request: Request, user: Principal = Depends(require("admin"))):
|
| 52 |
+
try:
|
| 53 |
+
return langsmith.get(request.app.state.svc).save(body.model_dump(exclude_none=True), user.username)
|
| 54 |
+
except ValueError as e:
|
| 55 |
+
raise ApiError(422, "BAD_SETTING", str(e)) from e
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@router.post("/ai/langsmith/key")
|
| 59 |
+
def langsmith_key(body: KeyIn, request: Request, user: Principal = Depends(require("admin"))):
|
| 60 |
+
return langsmith.get(request.app.state.svc).set_key(body.api_key, user.username)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@router.delete("/ai/langsmith/key")
|
| 64 |
+
def langsmith_key_delete(request: Request, user: Principal = Depends(require("admin"))):
|
| 65 |
+
return langsmith.get(request.app.state.svc).set_key(None, user.username)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@router.post("/ai/langsmith/test")
|
| 69 |
+
def langsmith_test(request: Request, user: Principal = Depends(require("admin"))):
|
| 70 |
+
return langsmith.get(request.app.state.svc).test(user.username)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@router.get("/ai/evals/datasets")
|
| 74 |
+
def eval_datasets(user: Principal = Depends(require("admin"))):
|
| 75 |
+
return {"items": llm_evals.catalog()}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@router.get("/ai/evals")
|
| 79 |
+
def eval_history(request: Request, user: Principal = Depends(require("admin"))):
|
| 80 |
+
return {"items": llm_evals.history(request.app.state.svc)}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@router.post("/ai/evals", status_code=202)
|
| 84 |
+
def eval_start(body: EvalIn, request: Request, user: Principal = Depends(require("admin"))):
|
| 85 |
+
try:
|
| 86 |
+
return llm_evals.start(request.app.state.svc, body.target, body.tasks, user.username)
|
| 87 |
+
except llm_evals.EvalError as e:
|
| 88 |
+
raise ApiError(e.status, e.code, str(e)) from e
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@router.get("/ai/evals/{eval_id}")
|
| 92 |
+
def eval_get(eval_id: str, request: Request, user: Principal = Depends(require("admin"))):
|
| 93 |
+
try:
|
| 94 |
+
return llm_evals.get(request.app.state.svc, eval_id)
|
| 95 |
+
except llm_evals.EvalError as e:
|
| 96 |
+
raise ApiError(e.status, e.code, str(e)) from e
|
coworker/evals/datasets/chat_answer.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"task": "chat_answer",
|
| 3 |
+
"schema": "ChatAnswer",
|
| 4 |
+
"sensitivity": "client",
|
| 5 |
+
"about": "The assistant rephrases a tool's answer for the person: short plain text, only the numbers the tool gave, no links.",
|
| 6 |
+
"cases": [
|
| 7 |
+
{"id": "ans-001", "payload": {"question": "is procure to pay ready?", "template": "Procure-to-Pay is not ready: 63 of 79 scenarios passed and 2 are failing.",
|
| 8 |
+
"facts_text": "Procure-to-Pay: not ready. 63 of 79 scenarios passed. 2 failing."},
|
| 9 |
+
"expect": {"contains_all": {"text": ["63", "79", "2"]}, "len_between": {"text": [10, 500]}}},
|
| 10 |
+
{"id": "ans-002", "payload": {"question": "how many runs are waiting for me", "template": "3 test runs are waiting for your approval.",
|
| 11 |
+
"facts_text": "Waiting for approval: 3 test runs."},
|
| 12 |
+
"expect": {"contains_all": {"text": ["3"]}, "len_between": {"text": [10, 400]}}},
|
| 13 |
+
{"id": "ans-003", "payload": {"question": "what failed", "template": "2 scenarios failed: P2P-APR-001 (requisition approval) and P2P-INV-001 (invoice entry).",
|
| 14 |
+
"facts_text": "Failed: P2P-APR-001 requisition approval; P2P-INV-001 invoice entry. 2 in all."},
|
| 15 |
+
"expect": {"contains_all": {"text": ["P2P-APR-001", "P2P-INV-001"]}, "len_between": {"text": [10, 500]}}},
|
| 16 |
+
{"id": "ans-004", "payload": {"question": "which environments do we have", "template": "You have 1 test environment: Local mock pod (practice).",
|
| 17 |
+
"facts_text": "Test environments: 1. Local mock pod, practice."},
|
| 18 |
+
"expect": {"contains_all": {"text": ["mock"]}, "len_between": {"text": [10, 400]}}}
|
| 19 |
+
]
|
| 20 |
+
}
|
coworker/evals/datasets/chat_intent.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"task": "chat_intent",
|
| 3 |
+
"schema": "ChatIntent",
|
| 4 |
+
"sensitivity": "client",
|
| 5 |
+
"about": "The assistant picks the tool for a question, only among the ones the deterministic router finds plausible.",
|
| 6 |
+
"cases": [
|
| 7 |
+
{"id": "intent-001", "payload": {"text": "is procure to pay ready for the patch?", "plausible": ["readiness", "run_status", "list_runs"]},
|
| 8 |
+
"expect": {"equals": {"tool": "readiness"}}},
|
| 9 |
+
{"id": "intent-002", "payload": {"text": "what failed in the last run", "plausible": ["failures", "run_status", "list_runs"]},
|
| 10 |
+
"expect": {"equals": {"tool": "failures"}}},
|
| 11 |
+
{"id": "intent-003", "payload": {"text": "show me scenario P2P-INV-004", "plausible": ["scenario", "failures"]},
|
| 12 |
+
"expect": {"equals": {"tool": "scenario"}}},
|
| 13 |
+
{"id": "intent-004", "payload": {"text": "what does update 26C change for payables", "plausible": ["patch_changes", "readiness"]},
|
| 14 |
+
"expect": {"equals": {"tool": "patch_changes"}}},
|
| 15 |
+
{"id": "intent-005", "payload": {"text": "which test environments do we have", "plausible": ["list_pods", "list_runs"]},
|
| 16 |
+
"expect": {"equals": {"tool": "list_pods"}}},
|
| 17 |
+
{"id": "intent-006", "payload": {"text": "how far is the test run that is going now", "plausible": ["run_status", "list_runs"]},
|
| 18 |
+
"expect": {"equals": {"tool": "run_status"}}},
|
| 19 |
+
{"id": "intent-007", "payload": {"text": "what can you do", "plausible": ["help", "list_runs"]},
|
| 20 |
+
"expect": {"equals": {"tool": "help"}}}
|
| 21 |
+
]
|
| 22 |
+
}
|
coworker/evals/datasets/self_heal.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"task": "self_heal",
|
| 3 |
+
"schema": "HealProposal",
|
| 4 |
+
"sensitivity": "client",
|
| 5 |
+
"about": "A screen element was renamed by the patch: pick its new name from the page's own elements (never invent one).",
|
| 6 |
+
"cases": [
|
| 7 |
+
{"id": "heal-001", "payload": {"case_id": "AP-INV-001", "role": "button", "old_name": "Submit Invoice",
|
| 8 |
+
"error": "getByRole('button', { name: 'Submit Invoice' }) resolved to 0 elements", "candidates": ["Submit", "Cancel", "Validate", "Save"]},
|
| 9 |
+
"expect": {"equals": {"new_name": "Submit", "role": "button"}}},
|
| 10 |
+
{"id": "heal-002", "payload": {"case_id": "AP-INV-003", "role": "link", "old_name": "Manage Invoices",
|
| 11 |
+
"error": "getByRole('link', { name: 'Manage Invoices' }) resolved to 0 elements", "candidates": ["Manage Invoices (Redwood)", "Create Invoice", "Reports and Analytics"]},
|
| 12 |
+
"expect": {"equals": {"new_name": "Manage Invoices (Redwood)"}}},
|
| 13 |
+
{"id": "heal-003", "payload": {"case_id": "PO-ORD-001", "role": "button", "old_name": "OK",
|
| 14 |
+
"error": "getByRole('button', { name: 'OK' }) resolved to 0 elements", "candidates": ["Ok", "Cancel", "Help"]},
|
| 15 |
+
"expect": {"equals": {"new_name": "Ok"}}},
|
| 16 |
+
{"id": "heal-004", "payload": {"case_id": "AR-TRX-004", "role": "textbox", "old_name": "Bill-to Customer",
|
| 17 |
+
"error": "getByRole('textbox', { name: 'Bill-to Customer' }) resolved to 0 elements", "candidates": ["Bill-to Account", "Ship-to Site", "Transaction Number"]},
|
| 18 |
+
"expect": {"equals": {"new_name": "Bill-to Account"}}},
|
| 19 |
+
{"id": "heal-005", "payload": {"case_id": "GL-JE-001", "role": "button", "old_name": "Post",
|
| 20 |
+
"error": "getByRole('button', { name: 'Post' }) resolved to 0 elements", "candidates": ["Post Journal", "Reverse", "Delete"]},
|
| 21 |
+
"expect": {"equals": {"new_name": "Post Journal"}}}
|
| 22 |
+
]
|
| 23 |
+
}
|
coworker/evals/datasets/summary.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"task": "summary",
|
| 3 |
+
"schema": "ExecSummary",
|
| 4 |
+
"sensitivity": "redacted",
|
| 5 |
+
"about": "The executive summary of a test run, from integer counts only. It must not invent numbers or state the go/no-go decision (that comes from the rules).",
|
| 6 |
+
"cases": [
|
| 7 |
+
{"id": "sum-001", "payload": {"counts": {"total": 79, "executed": 65, "passed": 63, "failed": 2, "flaky": 0, "skipped": 0, "deferred": 14}, "target": "mock"},
|
| 8 |
+
"expect": {"len_between": {"text": [40, 900]}, "contains_all": {"text": ["63"]}}},
|
| 9 |
+
{"id": "sum-002", "payload": {"counts": {"total": 40, "executed": 40, "passed": 40, "failed": 0, "flaky": 0, "skipped": 0, "deferred": 0}, "target": "fusion"},
|
| 10 |
+
"expect": {"len_between": {"text": [40, 900]}, "not_contains": {"text": ["mock"]}}},
|
| 11 |
+
{"id": "sum-003", "payload": {"counts": {"total": 25, "executed": 20, "passed": 15, "failed": 3, "flaky": 2, "skipped": 5, "deferred": 0}, "target": "mock"},
|
| 12 |
+
"expect": {"len_between": {"text": [40, 900]}, "contains_all": {"text": ["3"]}}},
|
| 13 |
+
{"id": "sum-004", "payload": {"counts": {"total": 12, "executed": 0, "passed": 0, "failed": 0, "flaky": 0, "skipped": 12, "deferred": 0}, "target": "fusion"},
|
| 14 |
+
"expect": {"len_between": {"text": [30, 900]}}},
|
| 15 |
+
{"id": "sum-005", "payload": {"counts": {"total": 150, "executed": 148, "passed": 140, "failed": 6, "flaky": 2, "skipped": 2, "deferred": 0}, "target": "fusion"},
|
| 16 |
+
"expect": {"len_between": {"text": [40, 900]}, "contains_all": {"text": ["6"]}}}
|
| 17 |
+
]
|
| 18 |
+
}
|
coworker/evals/datasets/triage.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"task": "triage",
|
| 3 |
+
"schema": "TriageHint",
|
| 4 |
+
"sensitivity": "client",
|
| 5 |
+
"about": "Classify a failed Fusion browser test: a changed screen (ui_change), missing or wrong test data (data), slowness or the network (timing), or a real product defect. The hint never overrides the rule; it helps the person who decides.",
|
| 6 |
+
"cases": [
|
| 7 |
+
{"id": "tri-001", "payload": {"case_id": "AP-INV-001", "category": "unclassified", "confidence": 0.3,
|
| 8 |
+
"evidence": ["Screenshot: the Invoice Actions menu shows 'Submit for Approval' instead of 'Submit'"],
|
| 9 |
+
"error": "Error: locator.click: Timeout 30000ms exceeded. waiting for getByRole('menuitem', { name: 'Submit' }) - strict mode: 0 elements"},
|
| 10 |
+
"expect": {"in": {"category": ["ui_change"]}}},
|
| 11 |
+
{"id": "tri-002", "payload": {"case_id": "P2P-APR-001", "category": "unclassified", "confidence": 0.35,
|
| 12 |
+
"evidence": ["Approval history shows no approver", "Requisition amount 12000 USD above the 10000 limit"],
|
| 13 |
+
"error": "Error: expect(locator).toHaveText(expected) Expected: 'Pending approval' Received: 'Incomplete' - the approver list is empty after Submit"},
|
| 14 |
+
"expect": {"in": {"category": ["real_defect"]}}},
|
| 15 |
+
{"id": "tri-003", "payload": {"case_id": "AP-INV-007", "category": "unclassified", "confidence": 0.3,
|
| 16 |
+
"evidence": ["Message on the page: The supplier TEST_SUPPLIER_9 does not exist. (POZ-2010107)"],
|
| 17 |
+
"error": "Error: expect(page.getByText('Invoice created')).toBeVisible() failed: the page shows an error message about the supplier"},
|
| 18 |
+
"expect": {"in": {"category": ["data"]}}},
|
| 19 |
+
{"id": "tri-004", "payload": {"case_id": "GL-JE-003", "category": "timing", "confidence": 0.4,
|
| 20 |
+
"evidence": ["The page was still showing the loading indicator in the screenshot"],
|
| 21 |
+
"error": "TimeoutError: page.waitForURL: Timeout 60000ms exceeded while waiting for the Journals page to load"},
|
| 22 |
+
"expect": {"in": {"category": ["timing"]}}},
|
| 23 |
+
{"id": "tri-005", "payload": {"case_id": "PO-ORD-002", "category": "unclassified", "confidence": 0.2,
|
| 24 |
+
"evidence": ["net::ERR_CONNECTION_RESET in the browser log"],
|
| 25 |
+
"error": "Error: page.goto: net::ERR_CONNECTION_RESET at https://fa-test.example/fscmUI/faces/FuseWelcome"},
|
| 26 |
+
"expect": {"in": {"category": ["timing"]}}},
|
| 27 |
+
{"id": "tri-006", "payload": {"case_id": "AR-TRX-004", "category": "unclassified", "confidence": 0.3,
|
| 28 |
+
"evidence": ["Field label on the page is now 'Bill-to Account' (was 'Bill-to Customer')"],
|
| 29 |
+
"error": "Error: getByLabel('Bill-to Customer') resolved to 0 elements"},
|
| 30 |
+
"expect": {"in": {"category": ["ui_change"]}}},
|
| 31 |
+
{"id": "tri-007", "payload": {"case_id": "AP-PAY-002", "category": "unclassified", "confidence": 0.3,
|
| 32 |
+
"evidence": ["Payment created with amount 0.00 for an invoice of 250.00", "No error message on the page"],
|
| 33 |
+
"error": "Error: expect(received).toBe(expected) Expected: '250.00' Received: '0.00' (payment amount)"},
|
| 34 |
+
"expect": {"in": {"category": ["real_defect"]}}}
|
| 35 |
+
]
|
| 36 |
+
}
|
coworker/graph/services.py
CHANGED
|
@@ -129,6 +129,8 @@ def build_services(cfg: Settings | None = None, transport=None, frontier_transpo
|
|
| 129 |
else:
|
| 130 |
llm_settings.apply_environment(svc)
|
| 131 |
router.before_call = lambda: llm_settings.sync(svc)
|
|
|
|
|
|
|
| 132 |
from ..platform import features # switches an administrator set in Settings override the environment
|
| 133 |
features.apply(svc)
|
| 134 |
from ..platform import notify # moments that need a person become notifications (outbox + webhook)
|
|
|
|
| 129 |
else:
|
| 130 |
llm_settings.apply_environment(svc)
|
| 131 |
router.before_call = lambda: llm_settings.sync(svc)
|
| 132 |
+
from ..platform import llm_telemetry # every model call is monitored (Settings > AI monitoring; LangSmith if switched on)
|
| 133 |
+
llm_telemetry.install(svc)
|
| 134 |
from ..platform import features # switches an administrator set in Settings override the environment
|
| 135 |
features.apply(svc)
|
| 136 |
from ..platform import notify # moments that need a person become notifications (outbox + webhook)
|
coworker/llm/providers/frontier.py
CHANGED
|
@@ -9,6 +9,7 @@ import re
|
|
| 9 |
|
| 10 |
from pydantic import BaseModel
|
| 11 |
|
|
|
|
| 12 |
from ..base import LLMRequest, ProviderError, Route
|
| 13 |
from .ollama import render_messages
|
| 14 |
|
|
@@ -74,6 +75,9 @@ class FrontierProvider:
|
|
| 74 |
|
| 75 |
def complete(self, req: LLMRequest) -> BaseModel:
|
| 76 |
out = self.egress.llm_frontier(self.body(req), task=req.task, sensitivity=req.sensitivity.value, run_id=req.run_id)
|
|
|
|
|
|
|
|
|
|
| 77 |
try:
|
| 78 |
msg = out["choices"][0]["message"]
|
| 79 |
except (KeyError, IndexError, TypeError) as e:
|
|
|
|
| 9 |
|
| 10 |
from pydantic import BaseModel
|
| 11 |
|
| 12 |
+
from .. import usage
|
| 13 |
from ..base import LLMRequest, ProviderError, Route
|
| 14 |
from .ollama import render_messages
|
| 15 |
|
|
|
|
| 75 |
|
| 76 |
def complete(self, req: LLMRequest) -> BaseModel:
|
| 77 |
out = self.egress.llm_frontier(self.body(req), task=req.task, sensitivity=req.sensitivity.value, run_id=req.run_id)
|
| 78 |
+
u = out.get("usage") if isinstance(out, dict) else None
|
| 79 |
+
if isinstance(u, dict):
|
| 80 |
+
usage.put(usage.as_int(u.get("prompt_tokens")), usage.as_int(u.get("completion_tokens")))
|
| 81 |
try:
|
| 82 |
msg = out["choices"][0]["message"]
|
| 83 |
except (KeyError, IndexError, TypeError) as e:
|
coworker/llm/providers/ollama.py
CHANGED
|
@@ -7,6 +7,7 @@ from pathlib import Path
|
|
| 7 |
|
| 8 |
from pydantic import BaseModel
|
| 9 |
|
|
|
|
| 10 |
from ..base import LLMRequest, ProviderError, Route
|
| 11 |
|
| 12 |
PROMPTS = Path(__file__).resolve().parents[1] / "prompts"
|
|
@@ -37,6 +38,8 @@ class OllamaProvider:
|
|
| 37 |
"format": req.schema.model_json_schema(), "options": {"temperature": 0}}
|
| 38 |
try:
|
| 39 |
out = self.egress.llm_local(body, task=req.task, run_id=req.run_id)
|
|
|
|
|
|
|
| 40 |
content = out["message"]["content"]
|
| 41 |
return req.schema.model_validate_json(content)
|
| 42 |
except (KeyError, TypeError) as e:
|
|
|
|
| 7 |
|
| 8 |
from pydantic import BaseModel
|
| 9 |
|
| 10 |
+
from .. import usage
|
| 11 |
from ..base import LLMRequest, ProviderError, Route
|
| 12 |
|
| 13 |
PROMPTS = Path(__file__).resolve().parents[1] / "prompts"
|
|
|
|
| 38 |
"format": req.schema.model_json_schema(), "options": {"temperature": 0}}
|
| 39 |
try:
|
| 40 |
out = self.egress.llm_local(body, task=req.task, run_id=req.run_id)
|
| 41 |
+
if isinstance(out, dict):
|
| 42 |
+
usage.put(usage.as_int(out.get("prompt_eval_count")), usage.as_int(out.get("eval_count")))
|
| 43 |
content = out["message"]["content"]
|
| 44 |
return req.schema.model_validate_json(content)
|
| 45 |
except (KeyError, TypeError) as e:
|
coworker/llm/router.py
CHANGED
|
@@ -4,11 +4,13 @@ from __future__ import annotations
|
|
| 4 |
|
| 5 |
import re
|
| 6 |
import threading
|
|
|
|
| 7 |
from collections import deque
|
| 8 |
|
| 9 |
from pydantic import BaseModel, ValidationError
|
| 10 |
|
| 11 |
from ..adapters.legacy import is_redacted_counts
|
|
|
|
| 12 |
from .base import (CHAT_TASKS, FRONTIER_TASKS, LLMRequest, LLMResponse, PolicyViolation, ProviderError, Route, Sensitivity,
|
| 13 |
TaskValidationError)
|
| 14 |
|
|
@@ -66,6 +68,7 @@ class LLMRouter:
|
|
| 66 |
self._lock = threading.Lock()
|
| 67 |
self.records: deque[dict] = deque(maxlen=500) # recent calls only (a long-running server must not grow); all are audited
|
| 68 |
self.before_call = None # set by build_services: picks up AI model settings saved by another process
|
|
|
|
| 69 |
|
| 70 |
def _frontier_on(self) -> bool:
|
| 71 |
return (self.cfg.llm_frontier != "off" and self.frontier is not None and self.frontier.available())
|
|
@@ -120,22 +123,38 @@ class LLMRouter:
|
|
| 120 |
chain = {Route.FRONTIER: [Route.FRONTIER] + ([Route.LOCAL] if self._local_on() else []) + [Route.STUB],
|
| 121 |
Route.LOCAL: [Route.LOCAL, Route.STUB], Route.STUB: [Route.STUB]}[route]
|
| 122 |
fallback, out, used = None, None, None
|
|
|
|
|
|
|
| 123 |
for r in chain:
|
| 124 |
prov = self._provider(r)
|
|
|
|
|
|
|
|
|
|
| 125 |
try:
|
| 126 |
o = prov.complete(req)
|
| 127 |
o = req.schema.model_validate(o.model_dump())
|
| 128 |
validate_task(req, o)
|
| 129 |
out, used = o, r
|
| 130 |
-
|
| 131 |
-
except
|
|
|
|
|
|
|
|
|
|
| 132 |
fallback = f"{r.value} failed: {type(e).__name__}: {str(e)[:200]}"
|
|
|
|
| 133 |
except Exception as e: # noqa: BLE001 - network errors from httpx etc.; never fall through to an external
|
| 134 |
fallback = f"{r.value} failed: {type(e).__name__}: {str(e)[:200]}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
if out is None:
|
| 136 |
if req.baseline is not None:
|
| 137 |
out, used = req.baseline, Route.STUB
|
| 138 |
else:
|
|
|
|
| 139 |
raise ProviderError(f"all providers failed for {req.task}: {fallback}")
|
| 140 |
prov = self._provider(used)
|
| 141 |
rec = {"node": req.node, "task": req.task, "route": used.value, "provider": prov.name, "model": prov.model,
|
|
@@ -145,5 +164,25 @@ class LLMRouter:
|
|
| 145 |
summary=f"{req.task} -> {used.value}/{prov.model}", payload=rec)
|
| 146 |
with self._lock:
|
| 147 |
self.records.append(rec)
|
|
|
|
| 148 |
return LLMResponse(output=out, route=used, provider=prov.name, model=prov.model,
|
| 149 |
fallback_reason=rec["fallback"], audit_seq=rec["audit_seq"], record=rec)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
import re
|
| 6 |
import threading
|
| 7 |
+
import time
|
| 8 |
from collections import deque
|
| 9 |
|
| 10 |
from pydantic import BaseModel, ValidationError
|
| 11 |
|
| 12 |
from ..adapters.legacy import is_redacted_counts
|
| 13 |
+
from . import usage
|
| 14 |
from .base import (CHAT_TASKS, FRONTIER_TASKS, LLMRequest, LLMResponse, PolicyViolation, ProviderError, Route, Sensitivity,
|
| 15 |
TaskValidationError)
|
| 16 |
|
|
|
|
| 68 |
self._lock = threading.Lock()
|
| 69 |
self.records: deque[dict] = deque(maxlen=500) # recent calls only (a long-running server must not grow); all are audited
|
| 70 |
self.before_call = None # set by build_services: picks up AI model settings saved by another process
|
| 71 |
+
self.sink = None # set by build_services: every call (attempts, latency, tokens) goes to monitoring
|
| 72 |
|
| 73 |
def _frontier_on(self) -> bool:
|
| 74 |
return (self.cfg.llm_frontier != "off" and self.frontier is not None and self.frontier.available())
|
|
|
|
| 123 |
chain = {Route.FRONTIER: [Route.FRONTIER] + ([Route.LOCAL] if self._local_on() else []) + [Route.STUB],
|
| 124 |
Route.LOCAL: [Route.LOCAL, Route.STUB], Route.STUB: [Route.STUB]}[route]
|
| 125 |
fallback, out, used = None, None, None
|
| 126 |
+
attempts: list[dict] = []
|
| 127 |
+
t_call = time.perf_counter()
|
| 128 |
for r in chain:
|
| 129 |
prov = self._provider(r)
|
| 130 |
+
usage.take()
|
| 131 |
+
t0 = time.perf_counter()
|
| 132 |
+
att = {"route": r.value, "model": getattr(prov, "model", ""), "ok": False}
|
| 133 |
try:
|
| 134 |
o = prov.complete(req)
|
| 135 |
o = req.schema.model_validate(o.model_dump())
|
| 136 |
validate_task(req, o)
|
| 137 |
out, used = o, r
|
| 138 |
+
att["ok"] = True
|
| 139 |
+
except TaskValidationError as e:
|
| 140 |
+
fallback = f"{r.value} failed: {type(e).__name__}: {str(e)[:200]}"
|
| 141 |
+
att["error"], att["kind"] = fallback, "validation"
|
| 142 |
+
except (ProviderError, ValidationError, ValueError, KeyError, OSError) as e:
|
| 143 |
fallback = f"{r.value} failed: {type(e).__name__}: {str(e)[:200]}"
|
| 144 |
+
att["error"], att["kind"] = fallback, "schema" if isinstance(e, ValidationError) else "provider"
|
| 145 |
except Exception as e: # noqa: BLE001 - network errors from httpx etc.; never fall through to an external
|
| 146 |
fallback = f"{r.value} failed: {type(e).__name__}: {str(e)[:200]}"
|
| 147 |
+
att["error"], att["kind"] = fallback, "provider"
|
| 148 |
+
att["latency_ms"] = round((time.perf_counter() - t0) * 1000)
|
| 149 |
+
att["tokens_in"], att["tokens_out"] = usage.take()
|
| 150 |
+
attempts.append(att)
|
| 151 |
+
if out is not None:
|
| 152 |
+
break
|
| 153 |
if out is None:
|
| 154 |
if req.baseline is not None:
|
| 155 |
out, used = req.baseline, Route.STUB
|
| 156 |
else:
|
| 157 |
+
self._emit(req, route, None, None, attempts, t_call, fallback)
|
| 158 |
raise ProviderError(f"all providers failed for {req.task}: {fallback}")
|
| 159 |
prov = self._provider(used)
|
| 160 |
rec = {"node": req.node, "task": req.task, "route": used.value, "provider": prov.name, "model": prov.model,
|
|
|
|
| 164 |
summary=f"{req.task} -> {used.value}/{prov.model}", payload=rec)
|
| 165 |
with self._lock:
|
| 166 |
self.records.append(rec)
|
| 167 |
+
self._emit(req, route, used, out, attempts, t_call, None, rec)
|
| 168 |
return LLMResponse(output=out, route=used, provider=prov.name, model=prov.model,
|
| 169 |
fallback_reason=rec["fallback"], audit_seq=rec["audit_seq"], record=rec)
|
| 170 |
+
|
| 171 |
+
def _emit(self, req: LLMRequest, planned: Route, used: Route | None, out, attempts: list[dict], t_call: float,
|
| 172 |
+
error: str | None, rec: dict | None = None) -> None:
|
| 173 |
+
"""One call for monitoring: what was planned, each attempt (route, model, latency, tokens, why it failed), what
|
| 174 |
+
answered. Never raises: monitoring must not break a run."""
|
| 175 |
+
if self.sink is None:
|
| 176 |
+
return
|
| 177 |
+
last = next((a for a in reversed(attempts) if a.get("ok")), attempts[-1] if attempts else {})
|
| 178 |
+
tel = {"run_id": req.run_id, "node": req.node, "task": req.task, "prompt": req.prompt or req.task, "planned_route": planned.value,
|
| 179 |
+
"route": used.value if used else None, "provider": self._provider(used).name if used else None,
|
| 180 |
+
"model": self._provider(used).model if used else last.get("model"), "sensitivity": req.sensitivity.value,
|
| 181 |
+
"ok": out is not None, "baseline": out is not None and not any(a.get("ok") for a in attempts),
|
| 182 |
+
"fallback": (rec or {}).get("fallback"), "error": error, "latency_ms": round((time.perf_counter() - t_call) * 1000),
|
| 183 |
+
"tokens_in": sum(a.get("tokens_in") or 0 for a in attempts) or None, "tokens_out": sum(a.get("tokens_out") or 0 for a in attempts) or None,
|
| 184 |
+
"attempts": attempts, "payload": req.payload, "output": out.model_dump() if out is not None else None}
|
| 185 |
+
try:
|
| 186 |
+
self.sink(tel)
|
| 187 |
+
except Exception: # noqa: BLE001
|
| 188 |
+
pass
|
coworker/llm/usage.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Token usage of the last model answer on this thread. A provider records what its API reported; the router takes it
|
| 2 |
+
right after the call (each call runs on one thread, so concurrent runs and chats never mix their numbers)."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import threading
|
| 6 |
+
|
| 7 |
+
_local = threading.local()
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def put(tokens_in: int | None, tokens_out: int | None) -> None:
|
| 11 |
+
_local.usage = (tokens_in, tokens_out)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def take() -> tuple[int | None, int | None]:
|
| 15 |
+
u = getattr(_local, "usage", (None, None))
|
| 16 |
+
_local.usage = (None, None)
|
| 17 |
+
return u
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def as_int(v) -> int | None:
|
| 21 |
+
try:
|
| 22 |
+
return int(v) if v is not None else None
|
| 23 |
+
except (TypeError, ValueError):
|
| 24 |
+
return None
|
coworker/platform/agent_studio.py
CHANGED
|
@@ -17,6 +17,7 @@ egress gate to the client's own callback address only, and retried. Test data is
|
|
| 17 |
anything that looks like personal data (an email, a phone or card number, a national id) is refused."""
|
| 18 |
from __future__ import annotations
|
| 19 |
|
|
|
|
| 20 |
import hashlib
|
| 21 |
import hmac
|
| 22 |
import json
|
|
@@ -31,6 +32,7 @@ from urllib.parse import urlparse
|
|
| 31 |
from .rundb import now_iso
|
| 32 |
|
| 33 |
log = logging.getLogger("fpt.agent_studio")
|
|
|
|
| 34 |
|
| 35 |
SCOPE = "patchwise.invoke"
|
| 36 |
TOKEN_TTL_S = 3600
|
|
@@ -56,6 +58,37 @@ AREA_ALIASES = {"CE": "CM", "PJ": "PPM", "REQ": "PO", "RCV": "PO"}
|
|
| 56 |
TEST_PREFIX = "TEST_"
|
| 57 |
MAX_PACKAGE = 2_000_000
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
def area_code(area) -> str:
|
| 61 |
code = str(area).strip().upper()
|
|
@@ -170,14 +203,114 @@ class AgentStudio:
|
|
| 170 |
self.db.x("DELETE FROM agent_tokens WHERE client_id=?", (client_id,))
|
| 171 |
self.svc.audit.append("agent_studio.client_revoked", actor=actor, summary=client_id, payload={"client_id": client_id})
|
| 172 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
def client(self, client_id: str) -> dict:
|
| 174 |
r = self.db.one("SELECT * FROM agent_clients WHERE client_id=?", (client_id,))
|
| 175 |
if not r:
|
| 176 |
raise AgentStudioError("NO_CLIENT", f"no client {client_id}", 404)
|
| 177 |
-
return
|
| 178 |
|
| 179 |
def clients(self) -> list[dict]:
|
| 180 |
-
return [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
def issue_token(self, client_id: str, client_secret: str, scope: str | None = None) -> dict:
|
| 183 |
"""client_credentials grant. Only the invoke scope exists: start cycles, forward approvals, read their status."""
|
|
@@ -335,6 +468,7 @@ class AgentStudio:
|
|
| 335 |
|
| 336 |
# ------------------------------------------------------------ callbacks
|
| 337 |
def queue(self, client_id: str, url: str | None, event: str, payload: dict, cycle_id: str | None = None) -> str | None:
|
|
|
|
| 338 |
if not url:
|
| 339 |
return None
|
| 340 |
did = "dlv_" + secrets.token_hex(8)
|
|
@@ -349,22 +483,32 @@ class AgentStudio:
|
|
| 349 |
for d in self.db.q("SELECT * FROM agent_callbacks WHERE delivered_at IS NULL AND attempts < ? AND next_at <= ? ORDER BY id LIMIT 20",
|
| 350 |
(MAX_ATTEMPTS, now_iso())):
|
| 351 |
key = self.svc.vault.get(f"agent_studio.{d['client_id']}.signing") or ""
|
| 352 |
-
|
|
|
|
| 353 |
sig = "sha256=" + hmac.new(key.encode(), body, hashlib.sha256).hexdigest()
|
| 354 |
-
code, err = None, None
|
|
|
|
| 355 |
try:
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
except Exception as e: # noqa: BLE001
|
| 364 |
err = f"{type(e).__name__}: {str(e)[:200]}"
|
| 365 |
n = d["attempts"] + 1
|
| 366 |
if err is None:
|
| 367 |
-
self.db.update("agent_callbacks", "id", d["id"], attempts=n, status_code=code, error=None, delivered_at=now_iso())
|
| 368 |
sent += 1
|
| 369 |
else:
|
| 370 |
self.db.update("agent_callbacks", "id", d["id"], attempts=n, status_code=code, error=err, next_at=_later(60 * 2 ** (n - 1)))
|
|
@@ -467,7 +611,7 @@ class AgentStudio:
|
|
| 467 |
found.setdefault(p["release"].upper(), []).extend(self.release_item(c, code, p["release"]) for c in new)
|
| 468 |
sent = 0
|
| 469 |
for rel, items in found.items():
|
| 470 |
-
for cl in self.db.q("SELECT * FROM agent_clients WHERE revoked_at IS NULL AND release_watch_url IS NOT NULL"):
|
| 471 |
if self.queue(cl["client_id"], cl["release_watch_url"], "patch_update", {"release": rel, "changes": items,
|
| 472 |
"count": len(items)}):
|
| 473 |
sent += 1
|
|
@@ -526,7 +670,7 @@ class Courier:
|
|
| 526 |
self.studio.deliver_due()
|
| 527 |
if self.watch_s and time.monotonic() - self._last_watch > self.watch_s:
|
| 528 |
self._last_watch = time.monotonic()
|
| 529 |
-
if self.studio.db.one("SELECT 1 AS x FROM agent_clients WHERE revoked_at IS NULL AND release_watch_url IS NOT NULL"):
|
| 530 |
self.studio.check_releases()
|
| 531 |
|
| 532 |
def _loop(self) -> None:
|
|
|
|
| 17 |
anything that looks like personal data (an email, a phone or card number, a national id) is refused."""
|
| 18 |
from __future__ import annotations
|
| 19 |
|
| 20 |
+
import base64
|
| 21 |
import hashlib
|
| 22 |
import hmac
|
| 23 |
import json
|
|
|
|
| 32 |
from .rundb import now_iso
|
| 33 |
|
| 34 |
log = logging.getLogger("fpt.agent_studio")
|
| 35 |
+
_TOKENS: dict[str, tuple[str, float]] = {} # client_id -> (Oracle access token, expires at); never stored
|
| 36 |
|
| 37 |
SCOPE = "patchwise.invoke"
|
| 38 |
TOKEN_TTL_S = 3600
|
|
|
|
| 58 |
TEST_PREFIX = "TEST_"
|
| 59 |
MAX_PACKAGE = 2_000_000
|
| 60 |
|
| 61 |
+
# Delivery straight to Oracle Fusion (no relay): Patchwise signs in to the client's OCI IAM identity domain (client
|
| 62 |
+
# credentials) and starts the callback workflow with invokeAsync, with the parameters the V3.7 workflow reads.
|
| 63 |
+
FUSION_DEFAULTS = {"workflow_code": "PATCH_TEST_CALLBACK_V3_7", "invocation_mode": "END_USER", "workflow_status": "PUBLISHED",
|
| 64 |
+
"conversational": True, "scope": ""}
|
| 65 |
+
_WF_CODE = re.compile(r"^[A-Z][A-Z0-9_]{1,79}$")
|
| 66 |
+
MAX_PAYLOAD_PARAM = 60_000
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def fusion_envelope(f: dict, source: str, delivery_id: str, payload: dict) -> dict:
|
| 70 |
+
"""The invokeAsync body: {message, parameters}. A workflow sees only parameters, so the event travels as payloadJson
|
| 71 |
+
(lists cut to 50 items when it would pass 60 KB). `verified` tells the workflow the event came over the trusted path
|
| 72 |
+
(Patchwise itself, signed in with the client's own credentials)."""
|
| 73 |
+
event = str(payload.get("event") or ("release_watch" if source == "release_watch" else ""))[:40]
|
| 74 |
+
pj = json.dumps(payload, ensure_ascii=True)
|
| 75 |
+
if len(pj) > MAX_PAYLOAD_PARAM:
|
| 76 |
+
slim = {k: v for k, v in payload.items() if k not in ("scenarios", "items", "changes")}
|
| 77 |
+
for k in ("scenarios", "items", "changes"):
|
| 78 |
+
if isinstance(payload.get(k), list):
|
| 79 |
+
slim[k], slim[k + "_truncated"] = payload[k][:50], len(payload[k])
|
| 80 |
+
pj = json.dumps(slim, ensure_ascii=True)[:MAX_PAYLOAD_PARAM]
|
| 81 |
+
return {"message": f"Patchwise event {event or '(none)'} for cycle {payload.get('cycle_id') or '-'}",
|
| 82 |
+
"conversational": bool(f.get("conversational", True)), "invocationMode": f.get("invocation_mode") or "END_USER",
|
| 83 |
+
"status": f.get("workflow_status") or "PUBLISHED",
|
| 84 |
+
"parameters": {"triggerType": "REST", "event": event, "cycleId": str(payload.get("cycle_id") or ""),
|
| 85 |
+
"correlationId": str(payload.get("correlation_id") or ""), "deliveryId": delivery_id,
|
| 86 |
+
"payloadJson": pj, "verified": "sha256", "source": source}}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def invoke_url(f: dict) -> str:
|
| 90 |
+
return f"{f['base_url'].rstrip('/')}/api/fusion-ai/orchestrator/agent/v2/{f['workflow_code']}/invokeAsync"
|
| 91 |
+
|
| 92 |
|
| 93 |
def area_code(area) -> str:
|
| 94 |
code = str(area).strip().upper()
|
|
|
|
| 203 |
self.db.x("DELETE FROM agent_tokens WHERE client_id=?", (client_id,))
|
| 204 |
self.svc.audit.append("agent_studio.client_revoked", actor=actor, summary=client_id, payload={"client_id": client_id})
|
| 205 |
|
| 206 |
+
def _shown(self, r: dict) -> dict:
|
| 207 |
+
out = {k: v for k, v in r.items() if k not in ("secret_hash", "fusion")}
|
| 208 |
+
out["delivery"] = r.get("delivery") or "url"
|
| 209 |
+
out["fusion"] = {**(_j(r.get("fusion")) or {}), "has_secret": bool(self.svc.vault.get(f"agent_studio.{r['client_id']}.fusion_secret"))} \
|
| 210 |
+
if r.get("fusion") else None
|
| 211 |
+
return out
|
| 212 |
+
|
| 213 |
def client(self, client_id: str) -> dict:
|
| 214 |
r = self.db.one("SELECT * FROM agent_clients WHERE client_id=?", (client_id,))
|
| 215 |
if not r:
|
| 216 |
raise AgentStudioError("NO_CLIENT", f"no client {client_id}", 404)
|
| 217 |
+
return self._shown(r)
|
| 218 |
|
| 219 |
def clients(self) -> list[dict]:
|
| 220 |
+
return [self._shown(r) for r in self.db.q("SELECT * FROM agent_clients ORDER BY id DESC")]
|
| 221 |
+
|
| 222 |
+
# ------------------------------------------------------------ delivery: a signed POST, or straight to Oracle Fusion
|
| 223 |
+
def set_delivery(self, client_id: str, actor: str, mode: str, fusion: dict | None = None, secret: str | None = None) -> dict:
|
| 224 |
+
"""mode "url": signed POSTs to the callback address (a relay, or any receiver). mode "fusion": Patchwise starts
|
| 225 |
+
the callback workflow itself (invokeAsync), signed in with the client's OCI IAM confidential app."""
|
| 226 |
+
self.client(client_id)
|
| 227 |
+
if mode not in ("url", "fusion"):
|
| 228 |
+
raise AgentStudioError("BAD_DELIVERY", "delivery is url or fusion")
|
| 229 |
+
if mode == "url":
|
| 230 |
+
self.db.update("agent_clients", "client_id", client_id, delivery="url")
|
| 231 |
+
else:
|
| 232 |
+
f = {**FUSION_DEFAULTS, **{k: v for k, v in (fusion or {}).items() if v not in (None, "")}}
|
| 233 |
+
f["base_url"] = _check_url(str(f.get("base_url") or "").rstrip("/"), "Fusion address") or ""
|
| 234 |
+
f["token_url"] = _check_url(str(f.get("token_url") or ""), "token address") or ""
|
| 235 |
+
if not f["base_url"] or not f["token_url"] or not str(f.get("client_id") or "").strip():
|
| 236 |
+
raise AgentStudioError("BAD_DELIVERY", "the Fusion address, the token address and the client id are needed")
|
| 237 |
+
if not _WF_CODE.match(str(f["workflow_code"])):
|
| 238 |
+
raise AgentStudioError("BAD_DELIVERY", "the workflow code is upper case letters, digits and _ (PATCH_TEST_CALLBACK_V3_7)")
|
| 239 |
+
if f["invocation_mode"] not in ("END_USER", "ADMIN") or f["workflow_status"] not in ("PUBLISHED", "DRAFT"):
|
| 240 |
+
raise AgentStudioError("BAD_DELIVERY", "invocation mode is END_USER or ADMIN; workflow status PUBLISHED or DRAFT")
|
| 241 |
+
keep = ("base_url", "token_url", "client_id", "scope", "workflow_code", "invocation_mode", "workflow_status", "conversational")
|
| 242 |
+
f = {k: f[k] for k in keep}
|
| 243 |
+
f["client_id"], f["scope"] = str(f["client_id"]).strip()[:200], str(f["scope"] or "").strip()[:300]
|
| 244 |
+
f["conversational"] = bool(f["conversational"])
|
| 245 |
+
if secret:
|
| 246 |
+
self.svc.vault.set(f"agent_studio.{client_id}.fusion_secret", secret)
|
| 247 |
+
if not self.svc.vault.get(f"agent_studio.{client_id}.fusion_secret"):
|
| 248 |
+
raise AgentStudioError("BAD_DELIVERY", "the client secret of the Oracle confidential app is needed once")
|
| 249 |
+
self.db.update("agent_clients", "client_id", client_id, delivery="fusion", fusion=json.dumps(f))
|
| 250 |
+
_TOKENS.pop(client_id, None)
|
| 251 |
+
self.svc.audit.append("agent_studio.delivery_set", actor=actor, summary=f"{client_id} {mode}", payload={"client_id": client_id, "delivery": mode})
|
| 252 |
+
return self.client(client_id)
|
| 253 |
+
|
| 254 |
+
def _fusion(self, client_id: str) -> tuple[dict, str] | None:
|
| 255 |
+
r = self.db.one("SELECT delivery, fusion FROM agent_clients WHERE client_id=?", (client_id,))
|
| 256 |
+
if not r or r.get("delivery") != "fusion" or not r.get("fusion"):
|
| 257 |
+
return None
|
| 258 |
+
return _j(r["fusion"]), self.svc.vault.get(f"agent_studio.{client_id}.fusion_secret") or ""
|
| 259 |
+
|
| 260 |
+
def _fusion_token(self, client_id: str, f: dict, secret: str, force: bool = False) -> str:
|
| 261 |
+
t = _TOKENS.get(client_id)
|
| 262 |
+
if t and not force and time.time() < t[1] - 60:
|
| 263 |
+
return t[0]
|
| 264 |
+
from urllib.parse import urlencode
|
| 265 |
+
form = {"grant_type": "client_credentials", **({"scope": f["scope"]} if f.get("scope") else {})}
|
| 266 |
+
basic = base64.b64encode(f"{f['client_id']}:{secret}".encode()).decode()
|
| 267 |
+
r = self.svc.egress.service_request("fusion_token", "POST", f["token_url"], allowed_base=f["token_url"], content=urlencode(form).encode(),
|
| 268 |
+
headers={"Content-Type": "application/x-www-form-urlencoded", "Authorization": "Basic " + basic},
|
| 269 |
+
log_body={"grant_type": "client_credentials", "client_id": f["client_id"]}, timeout=20)
|
| 270 |
+
if r.status_code != 200:
|
| 271 |
+
raise AgentStudioError("FUSION_SIGN_IN", f"Oracle identity domain answered HTTP {r.status_code} to the token request", 502)
|
| 272 |
+
d = r.json()
|
| 273 |
+
_TOKENS[client_id] = (d["access_token"], time.time() + float(d.get("expires_in") or 3600))
|
| 274 |
+
return d["access_token"]
|
| 275 |
+
|
| 276 |
+
def _fusion_invoke(self, client_id: str, f: dict, secret: str, envelope: dict) -> tuple[int, str]:
|
| 277 |
+
"""(HTTP status, job id or error). One token refresh on 401."""
|
| 278 |
+
url = invoke_url(f)
|
| 279 |
+
for attempt in (1, 2):
|
| 280 |
+
tok = self._fusion_token(client_id, f, secret, force=attempt == 2)
|
| 281 |
+
r = self.svc.egress.service_request("fusion_invoke", "POST", url, allowed_base=f["base_url"], json_body=envelope,
|
| 282 |
+
headers={"Authorization": "Bearer " + tok, "Accept": "application/json"},
|
| 283 |
+
log_body={"workflow": f["workflow_code"], "event": envelope["parameters"]["event"],
|
| 284 |
+
"delivery_id": envelope["parameters"]["deliveryId"]}, timeout=20)
|
| 285 |
+
if r.status_code == 401 and attempt == 1:
|
| 286 |
+
continue
|
| 287 |
+
if 200 <= r.status_code < 300:
|
| 288 |
+
try:
|
| 289 |
+
return r.status_code, str((r.json() or {}).get("jobId") or "")
|
| 290 |
+
except ValueError:
|
| 291 |
+
return r.status_code, ""
|
| 292 |
+
return r.status_code, f"HTTP {r.status_code}: {r.text[:200]}"
|
| 293 |
+
return 401, "unauthorized after a token refresh"
|
| 294 |
+
|
| 295 |
+
def test_delivery(self, client_id: str, actor: str) -> dict:
|
| 296 |
+
"""Signs in to the Oracle identity domain (no workflow is started) and says whether it worked."""
|
| 297 |
+
got = self._fusion(client_id)
|
| 298 |
+
if not got:
|
| 299 |
+
raise AgentStudioError("BAD_DELIVERY", "this client delivers to a callback address, not to Oracle Fusion")
|
| 300 |
+
f, secret = got
|
| 301 |
+
try:
|
| 302 |
+
self._fusion_token(client_id, f, secret, force=True)
|
| 303 |
+
ok, detail = True, f"Signed in to the Oracle identity domain. Events start {f['workflow_code']} on {f['base_url']}."
|
| 304 |
+
except AgentStudioError as e:
|
| 305 |
+
ok, detail = False, str(e)
|
| 306 |
+
except Exception as e: # noqa: BLE001 - shown to the admin as the test result
|
| 307 |
+
ok, detail = False, f"{type(e).__name__}: {str(e)[:200]}"
|
| 308 |
+
self.svc.audit.append("agent_studio.delivery_test", actor=actor, summary=f"{client_id} {'ok' if ok else 'failed'}", payload={"client_id": client_id, "ok": ok})
|
| 309 |
+
return {"ok": ok, "detail": detail}
|
| 310 |
+
|
| 311 |
+
def _target(self, client_id: str, url: str | None) -> str | None:
|
| 312 |
+
got = self._fusion(client_id)
|
| 313 |
+
return invoke_url(got[0]) if got else url
|
| 314 |
|
| 315 |
def issue_token(self, client_id: str, client_secret: str, scope: str | None = None) -> dict:
|
| 316 |
"""client_credentials grant. Only the invoke scope exists: start cycles, forward approvals, read their status."""
|
|
|
|
| 468 |
|
| 469 |
# ------------------------------------------------------------ callbacks
|
| 470 |
def queue(self, client_id: str, url: str | None, event: str, payload: dict, cycle_id: str | None = None) -> str | None:
|
| 471 |
+
url = self._target(client_id, url)
|
| 472 |
if not url:
|
| 473 |
return None
|
| 474 |
did = "dlv_" + secrets.token_hex(8)
|
|
|
|
| 483 |
for d in self.db.q("SELECT * FROM agent_callbacks WHERE delivered_at IS NULL AND attempts < ? AND next_at <= ? ORDER BY id LIMIT 20",
|
| 484 |
(MAX_ATTEMPTS, now_iso())):
|
| 485 |
key = self.svc.vault.get(f"agent_studio.{d['client_id']}.signing") or ""
|
| 486 |
+
payload = _j(d["payload"])
|
| 487 |
+
body = json.dumps(payload).encode()
|
| 488 |
sig = "sha256=" + hmac.new(key.encode(), body, hashlib.sha256).hexdigest()
|
| 489 |
+
code, err, job = None, None, None
|
| 490 |
+
fusion = self._fusion(d["client_id"])
|
| 491 |
try:
|
| 492 |
+
if fusion: # straight to Oracle Fusion: invokeAsync starts the callback workflow
|
| 493 |
+
source = "release_watch" if d["event"] == "patch_update" else "callback"
|
| 494 |
+
code, out = self._fusion_invoke(d["client_id"], *fusion, fusion_envelope(fusion[0], source, d["delivery_id"], payload))
|
| 495 |
+
if 200 <= code < 300:
|
| 496 |
+
job = out or None
|
| 497 |
+
else:
|
| 498 |
+
err = out
|
| 499 |
+
else:
|
| 500 |
+
r = self.svc.egress.service_request("agent_callback", "POST", d["url"], allowed_base=d["url"], content=body,
|
| 501 |
+
headers={"Content-Type": "application/json", "X-Patchwise-Event": d["event"],
|
| 502 |
+
"X-Patchwise-Delivery": d["delivery_id"], "X-Patchwise-Signature": sig},
|
| 503 |
+
log_body={"event": d["event"], "delivery_id": d["delivery_id"]}, timeout=20)
|
| 504 |
+
code = r.status_code
|
| 505 |
+
if not 200 <= code < 300:
|
| 506 |
+
err = f"HTTP {code}"
|
| 507 |
except Exception as e: # noqa: BLE001
|
| 508 |
err = f"{type(e).__name__}: {str(e)[:200]}"
|
| 509 |
n = d["attempts"] + 1
|
| 510 |
if err is None:
|
| 511 |
+
self.db.update("agent_callbacks", "id", d["id"], attempts=n, status_code=code, error=None, delivered_at=now_iso(), job_id=job)
|
| 512 |
sent += 1
|
| 513 |
else:
|
| 514 |
self.db.update("agent_callbacks", "id", d["id"], attempts=n, status_code=code, error=err, next_at=_later(60 * 2 ** (n - 1)))
|
|
|
|
| 611 |
found.setdefault(p["release"].upper(), []).extend(self.release_item(c, code, p["release"]) for c in new)
|
| 612 |
sent = 0
|
| 613 |
for rel, items in found.items():
|
| 614 |
+
for cl in self.db.q("SELECT * FROM agent_clients WHERE revoked_at IS NULL AND (release_watch_url IS NOT NULL OR delivery='fusion')"):
|
| 615 |
if self.queue(cl["client_id"], cl["release_watch_url"], "patch_update", {"release": rel, "changes": items,
|
| 616 |
"count": len(items)}):
|
| 617 |
sent += 1
|
|
|
|
| 670 |
self.studio.deliver_due()
|
| 671 |
if self.watch_s and time.monotonic() - self._last_watch > self.watch_s:
|
| 672 |
self._last_watch = time.monotonic()
|
| 673 |
+
if self.studio.db.one("SELECT 1 AS x FROM agent_clients WHERE revoked_at IS NULL AND (release_watch_url IS NOT NULL OR delivery='fusion')"):
|
| 674 |
self.studio.check_releases()
|
| 675 |
|
| 676 |
def _loop(self) -> None:
|
coworker/platform/langsmith.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Optional export of the AI model calls (and evaluation results) to LangSmith, through the egress gate.
|
| 2 |
+
|
| 3 |
+
Off unless an admin switches it on (Settings > AI monitoring) or the environment sets LANGSMITH_TRACING=true; the API
|
| 4 |
+
key is write-only (vault `langsmith.api_key`, or LANGSMITH_API_KEY). Content policy, so client data never leaves:
|
| 5 |
+
* calls on CLIENT data (anything from the pod, results, screenshots, chat): metadata only (task, model, route,
|
| 6 |
+
latency, tokens, outcome); prompt and answer are replaced by a note;
|
| 7 |
+
* calls on PUBLIC or REDACTED data (already cleared for the external model): the payload and the answer are sent
|
| 8 |
+
only when the admin chose "send content", else metadata only;
|
| 9 |
+
* evaluation calls use synthetic datasets: always sent with content, with a score per case as feedback.
|
| 10 |
+
Runs are batched (POST {endpoint}/runs/batch) by a background thread every few seconds; a failure is retried once and
|
| 11 |
+
then dropped (monitoring never blocks a test run)."""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import logging
|
| 16 |
+
import os
|
| 17 |
+
import threading
|
| 18 |
+
import time
|
| 19 |
+
import uuid
|
| 20 |
+
from collections import deque
|
| 21 |
+
from datetime import datetime, timedelta, timezone
|
| 22 |
+
|
| 23 |
+
log = logging.getLogger("fpt.langsmith")
|
| 24 |
+
|
| 25 |
+
KV = "llm.langsmith"
|
| 26 |
+
VAULT_KEY = "langsmith.api_key"
|
| 27 |
+
DEFAULT_ENDPOINT = "https://api.smith.langchain.com"
|
| 28 |
+
DEFAULT_PROJECT = "patchwise-agent-studio"
|
| 29 |
+
MAX_CONTENT = 20_000
|
| 30 |
+
_INSTANCES: dict[int, "LangSmith"] = {}
|
| 31 |
+
_LOCK = threading.Lock()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def get(svc) -> "LangSmith":
|
| 35 |
+
with _LOCK:
|
| 36 |
+
inst = _INSTANCES.get(id(svc))
|
| 37 |
+
if inst is None:
|
| 38 |
+
inst = _INSTANCES[id(svc)] = LangSmith(svc)
|
| 39 |
+
return inst
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _env_on() -> bool:
|
| 43 |
+
return os.getenv("LANGSMITH_TRACING", os.getenv("LANGCHAIN_TRACING_V2", "")).strip().lower() in ("1", "true", "yes")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _cut(v):
|
| 47 |
+
s = json.dumps(v, default=str, ensure_ascii=False)
|
| 48 |
+
return v if len(s) <= MAX_CONTENT else {"truncated": True, "preview": s[:MAX_CONTENT]}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class LangSmith:
|
| 52 |
+
def __init__(self, svc):
|
| 53 |
+
self.svc = svc
|
| 54 |
+
self.q: deque = deque(maxlen=2000)
|
| 55 |
+
self._thread: threading.Thread | None = None
|
| 56 |
+
self._stop = threading.Event()
|
| 57 |
+
self.state = {"sent": 0, "dropped": 0, "last_ok_at": None, "last_error": None, "last_error_at": None}
|
| 58 |
+
|
| 59 |
+
# ------------------------------------------------------------ settings
|
| 60 |
+
def settings(self) -> dict:
|
| 61 |
+
saved = self.svc.db.kv_get(KV, None) or {}
|
| 62 |
+
on = saved.get("enabled") if "enabled" in saved else _env_on()
|
| 63 |
+
return {"enabled": bool(on), "project": saved.get("project") or os.getenv("LANGSMITH_PROJECT") or DEFAULT_PROJECT,
|
| 64 |
+
"endpoint": (saved.get("endpoint") or os.getenv("LANGSMITH_ENDPOINT") or DEFAULT_ENDPOINT).rstrip("/"),
|
| 65 |
+
"send_content": bool(saved.get("send_content", False))}
|
| 66 |
+
|
| 67 |
+
def key(self) -> str:
|
| 68 |
+
return self.svc.vault.get(VAULT_KEY) or os.getenv("LANGSMITH_API_KEY") or ""
|
| 69 |
+
|
| 70 |
+
def view(self) -> dict:
|
| 71 |
+
s = self.settings()
|
| 72 |
+
return {**s, "has_key": bool(self.key()), "queued": len(self.q), **self.state}
|
| 73 |
+
|
| 74 |
+
def save(self, changes: dict, actor: str) -> dict:
|
| 75 |
+
s = {**(self.svc.db.kv_get(KV, None) or {})}
|
| 76 |
+
for k in ("enabled", "project", "endpoint", "send_content"):
|
| 77 |
+
if k in changes and changes[k] is not None:
|
| 78 |
+
s[k] = changes[k]
|
| 79 |
+
ep = str(s.get("endpoint") or DEFAULT_ENDPOINT)
|
| 80 |
+
if not ep.startswith("https://"):
|
| 81 |
+
raise ValueError("the LangSmith endpoint must be an https address")
|
| 82 |
+
self.svc.db.kv_set(KV, s)
|
| 83 |
+
self.svc.audit.append("settings.langsmith", actor=actor, summary=f"LangSmith export {'on' if s.get('enabled') else 'off'}",
|
| 84 |
+
payload={k: s.get(k) for k in ("enabled", "project", "endpoint", "send_content")})
|
| 85 |
+
return self.view()
|
| 86 |
+
|
| 87 |
+
def set_key(self, value: str | None, actor: str) -> dict:
|
| 88 |
+
self.svc.vault.set(VAULT_KEY, value or "")
|
| 89 |
+
if value:
|
| 90 |
+
self.svc.redactor.add_secrets([value])
|
| 91 |
+
self.svc.audit.append("settings.langsmith_key", actor=actor, summary="LangSmith key set" if value else "LangSmith key removed", payload={})
|
| 92 |
+
return self.view()
|
| 93 |
+
|
| 94 |
+
def active(self) -> bool:
|
| 95 |
+
return self.settings()["enabled"] and bool(self.key())
|
| 96 |
+
|
| 97 |
+
# ------------------------------------------------------------ export
|
| 98 |
+
def call(self, tel: dict, eval_id: str | None = None, run_id: str | None = None) -> str | None:
|
| 99 |
+
"""Queue one model call as a LangSmith run; returns its id (for feedback), or None when export is off."""
|
| 100 |
+
if not self.active():
|
| 101 |
+
return None
|
| 102 |
+
s = self.settings()
|
| 103 |
+
rid = run_id or str(uuid.uuid4())
|
| 104 |
+
end = datetime.now(timezone.utc)
|
| 105 |
+
start = end - timedelta(milliseconds=tel.get("latency_ms") or 0)
|
| 106 |
+
client = tel.get("sensitivity") == "client"
|
| 107 |
+
with_content = bool(eval_id) or (not client and s["send_content"])
|
| 108 |
+
withheld = {"withheld": "client data stays inside Patchwise" if client else "content export is off (Settings > AI monitoring)"}
|
| 109 |
+
attempts = [{k: a.get(k) for k in ("route", "model", "ok", "kind", "latency_ms")} for a in tel.get("attempts") or []]
|
| 110 |
+
out = {"output": _cut(tel.get("output"))} if with_content else dict(withheld)
|
| 111 |
+
if tel.get("tokens_in") or tel.get("tokens_out"):
|
| 112 |
+
out["usage_metadata"] = {"input_tokens": tel.get("tokens_in") or 0, "output_tokens": tel.get("tokens_out") or 0,
|
| 113 |
+
"total_tokens": (tel.get("tokens_in") or 0) + (tel.get("tokens_out") or 0)}
|
| 114 |
+
run = {"id": rid, "trace_id": rid, "dotted_order": start.strftime("%Y%m%dT%H%M%S%fZ") + rid, "name": f"patchwise.{tel['task']}",
|
| 115 |
+
"run_type": "llm", "start_time": start.isoformat(), "end_time": end.isoformat(), "session_name": s["project"],
|
| 116 |
+
"inputs": {"payload": _cut(tel.get("payload"))} if with_content else dict(withheld), "outputs": out,
|
| 117 |
+
"error": tel.get("error"),
|
| 118 |
+
"tags": [t for t in ("patchwise", tel["task"], tel.get("route") or "failed", "eval" if eval_id else None) if t],
|
| 119 |
+
"extra": {"metadata": {"task": tel["task"], "node": tel.get("node"), "prompt": tel.get("prompt"), "route": tel.get("route"),
|
| 120 |
+
"planned_route": tel.get("planned_route"), "provider": tel.get("provider"), "ls_model_name": tel.get("model"),
|
| 121 |
+
"sensitivity": tel.get("sensitivity"), "latency_ms": tel.get("latency_ms"), "baseline": tel.get("baseline"),
|
| 122 |
+
"fallback": tel.get("fallback"), "attempts": attempts, "patchwise_run_id": tel.get("run_id"), "eval_id": eval_id}}}
|
| 123 |
+
self.q.append(("run", run))
|
| 124 |
+
self._ensure_thread()
|
| 125 |
+
return rid
|
| 126 |
+
|
| 127 |
+
def feedback(self, run_id: str | None, key: str, score: float, comment: str = "") -> None:
|
| 128 |
+
if run_id and self.active():
|
| 129 |
+
self.q.append(("feedback", {"run_id": run_id, "key": key, "score": score, "comment": comment[:1000]}))
|
| 130 |
+
self._ensure_thread()
|
| 131 |
+
|
| 132 |
+
def _ensure_thread(self) -> None:
|
| 133 |
+
if self._thread and self._thread.is_alive():
|
| 134 |
+
return
|
| 135 |
+
self._thread = threading.Thread(target=self._loop, name="langsmith-export", daemon=True)
|
| 136 |
+
self._thread.start()
|
| 137 |
+
|
| 138 |
+
def _loop(self) -> None:
|
| 139 |
+
while not self._stop.wait(3.0):
|
| 140 |
+
try:
|
| 141 |
+
self.flush()
|
| 142 |
+
except Exception: # noqa: BLE001
|
| 143 |
+
log.exception("langsmith export")
|
| 144 |
+
|
| 145 |
+
def _post(self, path: str, body: dict) -> None:
|
| 146 |
+
s = self.settings()
|
| 147 |
+
r = self.svc.egress.service_request("langsmith", "POST", s["endpoint"] + path, allowed_base=s["endpoint"], json_body=body,
|
| 148 |
+
headers={"x-api-key": self.key()}, log_body={"path": path, "items": len(body.get("post", [])) or 1},
|
| 149 |
+
timeout=20)
|
| 150 |
+
if not 200 <= r.status_code < 300:
|
| 151 |
+
raise RuntimeError(f"LangSmith answered HTTP {r.status_code}: {r.text[:200]}")
|
| 152 |
+
|
| 153 |
+
def flush(self) -> int:
|
| 154 |
+
"""Send what is queued: the runs in one batch, then the feedback. Returns how many items went out."""
|
| 155 |
+
if not self.q:
|
| 156 |
+
return 0
|
| 157 |
+
if not self.active():
|
| 158 |
+
self.state["dropped"] += len(self.q)
|
| 159 |
+
self.q.clear()
|
| 160 |
+
return 0
|
| 161 |
+
items = [self.q.popleft() for _ in range(min(len(self.q), 200))]
|
| 162 |
+
runs = [b for k, b in items if k == "run"]
|
| 163 |
+
fbs = [b for k, b in items if k == "feedback"]
|
| 164 |
+
sent = 0
|
| 165 |
+
for tries in (1, 2):
|
| 166 |
+
try:
|
| 167 |
+
if runs:
|
| 168 |
+
self._post("/runs/batch", {"post": runs})
|
| 169 |
+
sent += len(runs)
|
| 170 |
+
runs = []
|
| 171 |
+
for fb in list(fbs):
|
| 172 |
+
self._post("/feedback", fb)
|
| 173 |
+
fbs.remove(fb)
|
| 174 |
+
sent += 1
|
| 175 |
+
self.state.update(last_ok_at=datetime.now(timezone.utc).isoformat(timespec="seconds"))
|
| 176 |
+
break
|
| 177 |
+
except Exception as e: # noqa: BLE001
|
| 178 |
+
self.state.update(last_error=f"{type(e).__name__}: {str(e)[:200]}", last_error_at=datetime.now(timezone.utc).isoformat(timespec="seconds"))
|
| 179 |
+
if tries == 2:
|
| 180 |
+
self.state["dropped"] += len(runs) + len(fbs)
|
| 181 |
+
else:
|
| 182 |
+
time.sleep(0.5)
|
| 183 |
+
self.state["sent"] += sent
|
| 184 |
+
return sent
|
| 185 |
+
|
| 186 |
+
def test(self, actor: str) -> dict:
|
| 187 |
+
"""Sends one small synthetic run (no client data) and says whether LangSmith took it."""
|
| 188 |
+
if not self.key():
|
| 189 |
+
return {"ok": False, "detail": "No LangSmith API key is set."}
|
| 190 |
+
was = self.settings()["enabled"]
|
| 191 |
+
if not was:
|
| 192 |
+
self.svc.db.kv_set(KV, {**(self.svc.db.kv_get(KV, None) or {}), "enabled": True})
|
| 193 |
+
try:
|
| 194 |
+
self.call({"task": "connection_test", "node": "settings", "sensitivity": "public", "route": "stub", "model": "none",
|
| 195 |
+
"latency_ms": 1, "payload": {"hello": "Patchwise connection test"}, "output": {"ok": True}}, eval_id="connection-test")
|
| 196 |
+
n = self.flush()
|
| 197 |
+
ok = n > 0
|
| 198 |
+
detail = f"LangSmith accepted a test run in project {self.settings()['project']}." if ok else (self.state["last_error"] or "Nothing was sent.")
|
| 199 |
+
finally:
|
| 200 |
+
if not was:
|
| 201 |
+
self.svc.db.kv_set(KV, {**(self.svc.db.kv_get(KV, None) or {}), "enabled": False})
|
| 202 |
+
self.svc.audit.append("settings.langsmith_test", actor=actor, summary="ok" if ok else "failed", payload={"ok": ok})
|
| 203 |
+
return {"ok": ok, "detail": detail}
|
coworker/platform/llm_evals.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluations of the AI models on fixed, synthetic datasets (coworker/evals/datasets/*.json).
|
| 2 |
+
|
| 3 |
+
Each case is scored on three things: the answer fits the task's schema; it passes the task's own rules (the same
|
| 4 |
+
llm.router.validate_task the app enforces: no invented numbers, a self-heal name from the page, a chat tool among the
|
| 5 |
+
plausible ones); and it matches the case's expectation (the right category, tool or element name; the facts kept).
|
| 6 |
+
The model is called directly (no routing, no fallback), so the score is the model's own. Policy still holds: the
|
| 7 |
+
external model is only evaluated on tasks that may go to it (FRONTIER_TASKS). Results are stored in llm_evals, every
|
| 8 |
+
call is a row in llm_calls (tagged with the evaluation) and, when LangSmith is on, a run with a `correct` score."""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import secrets
|
| 13 |
+
import threading
|
| 14 |
+
import time
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
from ..llm import schemas, usage
|
| 18 |
+
from ..llm.base import FRONTIER_TASKS, LLMRequest, Sensitivity
|
| 19 |
+
from ..llm.router import validate_task
|
| 20 |
+
from . import langsmith, llm_telemetry
|
| 21 |
+
from .rundb import now_iso
|
| 22 |
+
|
| 23 |
+
DATASETS = Path(__file__).resolve().parents[1] / "evals" / "datasets"
|
| 24 |
+
TARGETS = ("stub", "local", "external")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class EvalError(ValueError):
|
| 28 |
+
def __init__(self, code: str, msg: str, status: int = 400):
|
| 29 |
+
super().__init__(msg)
|
| 30 |
+
self.code, self.status = code, status
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def datasets() -> dict[str, dict]:
|
| 34 |
+
out = {}
|
| 35 |
+
for f in sorted(DATASETS.glob("*.json")):
|
| 36 |
+
d = json.loads(f.read_text(encoding="utf-8"))
|
| 37 |
+
out[d["task"]] = d
|
| 38 |
+
return out
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def catalog() -> list[dict]:
|
| 42 |
+
return [{"task": t, "about": d.get("about", ""), "cases": len(d["cases"]), "sensitivity": d["sensitivity"],
|
| 43 |
+
"external_allowed": t in FRONTIER_TASKS} for t, d in datasets().items()]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _provider(svc, target: str):
|
| 47 |
+
r = svc.router
|
| 48 |
+
if target == "stub":
|
| 49 |
+
return r.stub
|
| 50 |
+
if target == "local":
|
| 51 |
+
if not r._local_on():
|
| 52 |
+
raise EvalError("NOT_CONFIGURED", "the local model is not switched on or not reachable (Settings > AI models)")
|
| 53 |
+
return r.local
|
| 54 |
+
if not r.frontier_ready():
|
| 55 |
+
raise EvalError("NOT_CONFIGURED", "the external model is not switched on or not configured (Settings > AI models)")
|
| 56 |
+
return r.frontier
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def check(expect: dict, out: dict) -> list[dict]:
|
| 60 |
+
"""The case's expectations against the model's answer: one result per check."""
|
| 61 |
+
res = []
|
| 62 |
+
for field, want in (expect.get("equals") or {}).items():
|
| 63 |
+
res.append({"name": f"{field} is {want!r}", "ok": out.get(field) == want, "got": out.get(field)})
|
| 64 |
+
for field, allowed in (expect.get("in") or {}).items():
|
| 65 |
+
res.append({"name": f"{field} in {allowed}", "ok": out.get(field) in allowed, "got": out.get(field)})
|
| 66 |
+
for field, subs in (expect.get("contains_all") or {}).items():
|
| 67 |
+
text = str(out.get(field) or "").lower()
|
| 68 |
+
miss = [s for s in subs if s.lower() not in text]
|
| 69 |
+
res.append({"name": f"{field} keeps {subs}", "ok": not miss, "got": f"missing {miss}" if miss else "all kept"})
|
| 70 |
+
for field, subs in (expect.get("not_contains") or {}).items():
|
| 71 |
+
text = str(out.get(field) or "").lower()
|
| 72 |
+
bad = [s for s in subs if s.lower() in text]
|
| 73 |
+
res.append({"name": f"{field} avoids {subs}", "ok": not bad, "got": f"has {bad}" if bad else "none"})
|
| 74 |
+
for field, (lo, hi) in (expect.get("len_between") or {}).items():
|
| 75 |
+
n = len(str(out.get(field) or ""))
|
| 76 |
+
res.append({"name": f"{field} length {lo}-{hi}", "ok": lo <= n <= hi, "got": n})
|
| 77 |
+
return res
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _payload(task: str, p: dict) -> dict:
|
| 81 |
+
if task == "chat_intent":
|
| 82 |
+
from ..chat import intent as I
|
| 83 |
+
return {"tools": list(I.TOOLS), **p}
|
| 84 |
+
return p
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def start(svc, target: str, tasks: list[str] | None, actor: str, wait: bool = False) -> dict:
|
| 88 |
+
if target not in TARGETS:
|
| 89 |
+
raise EvalError("BAD_TARGET", f"target is one of {', '.join(TARGETS)}")
|
| 90 |
+
ds = datasets()
|
| 91 |
+
tasks = [t for t in (tasks or list(ds)) if t in ds]
|
| 92 |
+
if not tasks:
|
| 93 |
+
raise EvalError("NO_DATASET", f"no dataset for those tasks; there are {', '.join(ds)}")
|
| 94 |
+
prov = _provider(svc, target)
|
| 95 |
+
if svc.db.one("SELECT 1 AS x FROM llm_evals WHERE status='running'"):
|
| 96 |
+
raise EvalError("BUSY", "an evaluation is already running", 409)
|
| 97 |
+
eid = "ev_" + secrets.token_hex(5)
|
| 98 |
+
svc.db.insert("llm_evals", {"eval_id": eid, "target": target, "model": getattr(prov, "model", ""), "tasks": json.dumps(tasks),
|
| 99 |
+
"actor": actor, "status": "running", "started_at": now_iso()})
|
| 100 |
+
svc.audit.append("llm.eval_started", actor=actor, summary=f"{eid} {target} {tasks}", payload={"eval_id": eid, "target": target, "tasks": tasks})
|
| 101 |
+
t = threading.Thread(target=_run, args=(svc, eid, target, prov, tasks, ds), name=f"eval-{eid}", daemon=True)
|
| 102 |
+
t.start()
|
| 103 |
+
if wait:
|
| 104 |
+
t.join()
|
| 105 |
+
return get(svc, eid)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _run(svc, eid: str, target: str, prov, tasks: list[str], ds: dict) -> None:
|
| 109 |
+
results, per_task = [], {}
|
| 110 |
+
ls = langsmith.get(svc)
|
| 111 |
+
llm_telemetry._eval_ctx[threading.get_ident()] = eid
|
| 112 |
+
try:
|
| 113 |
+
for task in tasks:
|
| 114 |
+
d = ds[task]
|
| 115 |
+
schema = getattr(schemas, d["schema"])
|
| 116 |
+
sens = Sensitivity(d["sensitivity"])
|
| 117 |
+
rows = []
|
| 118 |
+
for case in d["cases"]:
|
| 119 |
+
row = {"task": task, "case": case["id"], "ok": False, "checks": [], "output": None, "error": None}
|
| 120 |
+
if target == "external" and task not in FRONTIER_TASKS:
|
| 121 |
+
row.update(skipped=True, error="local-only task: never sent to the external model")
|
| 122 |
+
rows.append(row)
|
| 123 |
+
continue
|
| 124 |
+
req = LLMRequest(task, sens, _payload(task, case["payload"]), schema, "eval")
|
| 125 |
+
usage.take()
|
| 126 |
+
t0 = time.perf_counter()
|
| 127 |
+
out = None
|
| 128 |
+
try:
|
| 129 |
+
o = prov.complete(req)
|
| 130 |
+
out = schema.model_validate(o.model_dump())
|
| 131 |
+
row["checks"].append({"name": "fits the schema", "ok": True})
|
| 132 |
+
try:
|
| 133 |
+
validate_task(req, out)
|
| 134 |
+
row["checks"].append({"name": "passes the task's rules", "ok": True})
|
| 135 |
+
except Exception as e: # noqa: BLE001
|
| 136 |
+
row["checks"].append({"name": "passes the task's rules", "ok": False, "got": str(e)[:200]})
|
| 137 |
+
row["output"] = out.model_dump()
|
| 138 |
+
row["checks"] += check(case.get("expect") or {}, row["output"])
|
| 139 |
+
except Exception as e: # noqa: BLE001 - a model that errors scores 0 on this case
|
| 140 |
+
row["error"] = f"{type(e).__name__}: {str(e)[:300]}"
|
| 141 |
+
row["checks"].append({"name": "fits the schema", "ok": False, "got": row["error"]})
|
| 142 |
+
row["latency_ms"] = round((time.perf_counter() - t0) * 1000)
|
| 143 |
+
row["tokens_in"], row["tokens_out"] = usage.take()
|
| 144 |
+
row["ok"] = bool(row["checks"]) and all(c["ok"] for c in row["checks"])
|
| 145 |
+
tel = {"task": task, "node": "eval", "prompt": task, "planned_route": prov.route.value, "route": prov.route.value if out is not None else None,
|
| 146 |
+
"provider": prov.name, "model": getattr(prov, "model", ""), "sensitivity": sens.value, "ok": out is not None, "baseline": False,
|
| 147 |
+
"error": row["error"], "latency_ms": row["latency_ms"], "tokens_in": row["tokens_in"], "tokens_out": row["tokens_out"],
|
| 148 |
+
"attempts": [{"route": prov.route.value, "model": getattr(prov, "model", ""), "ok": out is not None, "latency_ms": row["latency_ms"]}],
|
| 149 |
+
"payload": req.payload, "output": row["output"]}
|
| 150 |
+
llm_telemetry.record(svc.db, tel, eid)
|
| 151 |
+
rid = ls.call(tel, eval_id=eid)
|
| 152 |
+
ls.feedback(rid, "correct", 1.0 if row["ok"] else 0.0, "; ".join(f"{c['name']}: {'ok' if c['ok'] else c.get('got')}" for c in row["checks"]))
|
| 153 |
+
rows.append(row)
|
| 154 |
+
scored = [r for r in rows if not r.get("skipped")]
|
| 155 |
+
lat = sorted(r["latency_ms"] for r in scored)
|
| 156 |
+
per_task[task] = {"cases": len(rows), "scored": len(scored), "passed": sum(1 for r in scored if r["ok"]),
|
| 157 |
+
"skipped": len(rows) - len(scored), "score": round(sum(1 for r in scored if r["ok"]) / len(scored), 3) if scored else None,
|
| 158 |
+
"p50_ms": lat[len(lat) // 2] if lat else None, "tokens": sum((r.get("tokens_in") or 0) + (r.get("tokens_out") or 0) for r in scored)}
|
| 159 |
+
results += rows
|
| 160 |
+
scored = [r for r in results if not r.get("skipped")]
|
| 161 |
+
summ = {"score": round(sum(1 for r in scored if r["ok"]) / len(scored), 3) if scored else None, "cases": len(results),
|
| 162 |
+
"scored": len(scored), "passed": sum(1 for r in scored if r["ok"]), "by_task": per_task}
|
| 163 |
+
svc.db.update("llm_evals", "eval_id", eid, status="done", finished_at=now_iso(), summary=json.dumps(summ), results=json.dumps(results))
|
| 164 |
+
svc.audit.append("llm.eval_done", actor="system", summary=f"{eid} score {summ['score']}", payload={"eval_id": eid, "score": summ["score"]})
|
| 165 |
+
except Exception as e: # noqa: BLE001
|
| 166 |
+
svc.db.update("llm_evals", "eval_id", eid, status="failed", finished_at=now_iso(), error=f"{type(e).__name__}: {str(e)[:300]}",
|
| 167 |
+
results=json.dumps(results))
|
| 168 |
+
finally:
|
| 169 |
+
llm_telemetry._eval_ctx.pop(threading.get_ident(), None)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _j(v, default=None):
|
| 173 |
+
"""A JSON column as a value (the database may hand it back decoded already)."""
|
| 174 |
+
if v is None or v == "":
|
| 175 |
+
return default
|
| 176 |
+
return json.loads(v) if isinstance(v, str) else v
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _row(r: dict, full: bool) -> dict:
|
| 180 |
+
out = {k: v for k, v in r.items() if k not in ("summary", "results", "tasks")}
|
| 181 |
+
out["tasks"] = _j(r["tasks"], [])
|
| 182 |
+
out["summary"] = _j(r.get("summary"))
|
| 183 |
+
if full:
|
| 184 |
+
out["results"] = _j(r.get("results"), [])
|
| 185 |
+
return out
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def get(svc, eid: str) -> dict:
|
| 189 |
+
r = svc.db.one("SELECT * FROM llm_evals WHERE eval_id=?", (eid,))
|
| 190 |
+
if not r:
|
| 191 |
+
raise EvalError("NO_EVAL", f"no evaluation {eid}", 404)
|
| 192 |
+
return _row(r, True)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def history(svc, limit: int = 30) -> list[dict]:
|
| 196 |
+
return [_row(r, False) for r in svc.db.q("SELECT * FROM llm_evals ORDER BY started_at DESC LIMIT ?", (limit,))]
|
coworker/platform/llm_telemetry.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Monitoring of the AI models: every model call (from the LLM router) as one row in llm_calls, with the route the policy
|
| 2 |
+
planned, what answered, each attempt (route, model, latency, tokens, why it failed), and whether the deterministic
|
| 3 |
+
baseline had to stand in. Prompts and answers are NOT stored here. Summaries feed Settings > AI monitoring; the same
|
| 4 |
+
calls may also go to LangSmith (platform/langsmith.py), within its content policy."""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
from datetime import datetime, timedelta, timezone
|
| 9 |
+
|
| 10 |
+
from .rundb import now_iso
|
| 11 |
+
|
| 12 |
+
RETENTION_DAYS = 90
|
| 13 |
+
_eval_ctx: dict[int, str] = {} # thread id -> eval id: calls made by an evaluation are tagged with it
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def install(svc) -> None:
|
| 17 |
+
"""Point the router's sink at the database (and at LangSmith when it is switched on)."""
|
| 18 |
+
from . import langsmith
|
| 19 |
+
|
| 20 |
+
def sink(tel: dict) -> None:
|
| 21 |
+
import threading
|
| 22 |
+
eid = _eval_ctx.get(threading.get_ident())
|
| 23 |
+
record(svc.db, tel, eid)
|
| 24 |
+
langsmith.get(svc).call(tel, eval_id=eid)
|
| 25 |
+
|
| 26 |
+
svc.router.sink = sink
|
| 27 |
+
try: # an evaluation cut short by a restart must not block the next one; old calls go after 90 days
|
| 28 |
+
svc.db.x("UPDATE llm_evals SET status='failed', error='stopped by a restart' WHERE status='running'")
|
| 29 |
+
prune(svc.db)
|
| 30 |
+
except Exception: # noqa: BLE001 - a database without the tables yet (first start) is migrated later
|
| 31 |
+
pass
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def record(db, tel: dict, eval_id: str | None = None) -> int:
|
| 35 |
+
attempts = [{k: a.get(k) for k in ("route", "model", "ok", "kind", "latency_ms", "tokens_in", "tokens_out", "error")} for a in tel.get("attempts") or []]
|
| 36 |
+
return db.insert("llm_calls", {"ts": now_iso(), "run_id": tel.get("run_id"), "node": tel.get("node"), "task": tel["task"],
|
| 37 |
+
"prompt": tel.get("prompt"), "planned_route": tel.get("planned_route"), "route": tel.get("route"),
|
| 38 |
+
"provider": tel.get("provider"), "model": tel.get("model"), "sensitivity": tel.get("sensitivity"),
|
| 39 |
+
"ok": int(bool(tel.get("ok"))), "baseline": int(bool(tel.get("baseline"))), "fallback": tel.get("fallback"),
|
| 40 |
+
"error": tel.get("error"), "latency_ms": tel.get("latency_ms"), "tokens_in": tel.get("tokens_in"),
|
| 41 |
+
"tokens_out": tel.get("tokens_out"), "attempts": json.dumps(attempts), "eval_id": eval_id})
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _attempts(v) -> list:
|
| 45 |
+
return (json.loads(v) if isinstance(v, str) else v) or []
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def prune(db, days: int = RETENTION_DAYS) -> int:
|
| 49 |
+
cut = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat(timespec="seconds")
|
| 50 |
+
return db.x("DELETE FROM llm_calls WHERE ts < ?", (cut,))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _pct(vals: list[int], p: float) -> int | None:
|
| 54 |
+
if not vals:
|
| 55 |
+
return None
|
| 56 |
+
s = sorted(vals)
|
| 57 |
+
return s[min(len(s) - 1, int(round(p * (len(s) - 1))))]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _group(rows: list[dict]) -> dict:
|
| 61 |
+
lat = [r["latency_ms"] for r in rows if r["latency_ms"] is not None]
|
| 62 |
+
n = len(rows)
|
| 63 |
+
return {"calls": n, "failed": sum(1 for r in rows if not r["ok"]), "baseline": sum(1 for r in rows if r["baseline"]),
|
| 64 |
+
"fallbacks": sum(1 for r in rows if r["fallback"]),
|
| 65 |
+
"validation_failures": sum(1 for r in rows for a in _attempts(r["attempts"]) if a.get("kind") == "validation"),
|
| 66 |
+
"p50_ms": _pct(lat, 0.5), "p95_ms": _pct(lat, 0.95),
|
| 67 |
+
"tokens_in": sum(r["tokens_in"] or 0 for r in rows), "tokens_out": sum(r["tokens_out"] or 0 for r in rows),
|
| 68 |
+
"routes": {k: sum(1 for r in rows if (r["route"] or "failed") == k) for k in ("frontier", "local", "stub", "failed")},
|
| 69 |
+
"success_rate": round((n - sum(1 for r in rows if not r["ok"] or r["baseline"])) / n, 3) if n else None}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def summary(db, days: int = 7, include_evals: bool = False) -> dict:
|
| 73 |
+
"""Totals, per task, per model (route + model), per day, and the latest problems, over the last `days` days."""
|
| 74 |
+
since = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat(timespec="seconds")
|
| 75 |
+
rows = db.q("SELECT * FROM llm_calls WHERE ts >= ?" + ("" if include_evals else " AND eval_id IS NULL") + " ORDER BY id", (since,))
|
| 76 |
+
by = lambda key: {k: _group([r for r in rows if key(r) == k]) for k in sorted({key(r) for r in rows}, key=str)} # noqa: E731
|
| 77 |
+
days_out = []
|
| 78 |
+
start = (datetime.now(timezone.utc) - timedelta(days=days - 1)).date()
|
| 79 |
+
for i in range(days):
|
| 80 |
+
d = (start + timedelta(days=i)).isoformat()
|
| 81 |
+
day = [r for r in rows if r["ts"][:10] == d]
|
| 82 |
+
days_out.append({"day": d, "calls": len(day), "failed": sum(1 for r in day if not r["ok"] or r["baseline"]),
|
| 83 |
+
"p95_ms": _pct([r["latency_ms"] for r in day if r["latency_ms"] is not None], 0.95)})
|
| 84 |
+
problems = [{"ts": r["ts"], "task": r["task"], "node": r["node"], "run_id": r["run_id"], "route": r["route"], "model": r["model"],
|
| 85 |
+
"error": r["error"] or r["fallback"], "baseline": bool(r["baseline"])}
|
| 86 |
+
for r in reversed(rows) if (not r["ok"]) or r["baseline"] or r["fallback"]][:30]
|
| 87 |
+
return {"days": days, "since": since, "totals": _group(rows), "by_task": by(lambda r: r["task"]),
|
| 88 |
+
"by_model": by(lambda r: f"{r['route'] or 'none'} · {r['model'] or '?'}"), "by_day": days_out, "problems": problems}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def recent(db, limit: int = 100, task: str | None = None) -> list[dict]:
|
| 92 |
+
sql, args = "SELECT * FROM llm_calls", []
|
| 93 |
+
if task:
|
| 94 |
+
sql, args = sql + " WHERE task=?", [task]
|
| 95 |
+
rows = db.q(sql + " ORDER BY id DESC LIMIT ?", (*args, limit))
|
| 96 |
+
return [{**r, "ok": bool(r["ok"]), "baseline": bool(r["baseline"]), "attempts": _attempts(r["attempts"])} for r in rows]
|
coworker/platform/migrations/024_agent_fusion_delivery.sql
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- 024: a client can have Patchwise start the Fusion callback workflow itself (invokeAsync) instead of posting to a
|
| 2 |
+
-- relay. The Oracle client secret is in the vault, never here.
|
| 3 |
+
ALTER TABLE agent_clients ADD COLUMN delivery TEXT;
|
| 4 |
+
ALTER TABLE agent_clients ADD COLUMN fusion TEXT;
|
| 5 |
+
ALTER TABLE agent_callbacks ADD COLUMN job_id TEXT;
|
coworker/platform/migrations/025_llm_monitoring.sql
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- 025: monitoring of the AI models (every call: route, model, latency, tokens, attempts) and their evaluations.
|
| 2 |
+
-- No prompt or answer is stored here: a call's content stays where the run keeps it.
|
| 3 |
+
CREATE TABLE IF NOT EXISTS llm_calls (
|
| 4 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 5 |
+
ts TEXT NOT NULL,
|
| 6 |
+
run_id TEXT,
|
| 7 |
+
node TEXT,
|
| 8 |
+
task TEXT NOT NULL,
|
| 9 |
+
prompt TEXT,
|
| 10 |
+
planned_route TEXT,
|
| 11 |
+
route TEXT,
|
| 12 |
+
provider TEXT,
|
| 13 |
+
model TEXT,
|
| 14 |
+
sensitivity TEXT,
|
| 15 |
+
ok INTEGER NOT NULL,
|
| 16 |
+
baseline INTEGER NOT NULL DEFAULT 0,
|
| 17 |
+
fallback TEXT,
|
| 18 |
+
error TEXT,
|
| 19 |
+
latency_ms INTEGER,
|
| 20 |
+
tokens_in INTEGER,
|
| 21 |
+
tokens_out INTEGER,
|
| 22 |
+
attempts TEXT,
|
| 23 |
+
eval_id TEXT
|
| 24 |
+
);
|
| 25 |
+
CREATE INDEX IF NOT EXISTS llm_calls_ts ON llm_calls(ts);
|
| 26 |
+
CREATE INDEX IF NOT EXISTS llm_calls_task_ts ON llm_calls(task, ts);
|
| 27 |
+
-- one evaluation: a dataset run against one model; results per case
|
| 28 |
+
CREATE TABLE IF NOT EXISTS llm_evals (
|
| 29 |
+
eval_id TEXT PRIMARY KEY,
|
| 30 |
+
target TEXT NOT NULL,
|
| 31 |
+
model TEXT,
|
| 32 |
+
tasks TEXT NOT NULL,
|
| 33 |
+
actor TEXT,
|
| 34 |
+
status TEXT NOT NULL,
|
| 35 |
+
started_at TEXT NOT NULL,
|
| 36 |
+
finished_at TEXT,
|
| 37 |
+
summary TEXT,
|
| 38 |
+
results TEXT,
|
| 39 |
+
error TEXT
|
| 40 |
+
);
|
coworker/tests/test_agent_studio_fusion.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Delivery straight to Oracle Fusion (no relay): Patchwise signs in to the client's OCI IAM identity domain and starts
|
| 2 |
+
PATCH_TEST_CALLBACK_V3_7 with invokeAsync, with the parameters the workflow's READ_EVENT reads. The Oracle secret stays
|
| 3 |
+
in the vault; a 401 refreshes the token once; a failure is retried like any callback."""
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import base64
|
| 7 |
+
import json
|
| 8 |
+
import unittest
|
| 9 |
+
from urllib.parse import parse_qs
|
| 10 |
+
|
| 11 |
+
import httpx
|
| 12 |
+
|
| 13 |
+
from coworker.platform import agent_studio as A
|
| 14 |
+
from coworker.platform.agent_studio import AgentStudio, AgentStudioError
|
| 15 |
+
from coworker.tests.test_ai_scenarios import fusion_app
|
| 16 |
+
|
| 17 |
+
FUSION = {"base_url": "https://fa-test.oraclecloud.com", "token_url": "https://idcs-test.identity.oraclecloud.com/oauth2/v1/token",
|
| 18 |
+
"client_id": "pw_invoker", "scope": "urn:opc:resource:fa:instanceid=1urn:opc:resource:consumer::all"}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class FakeOracle:
|
| 22 |
+
def __init__(self):
|
| 23 |
+
self.calls, self.invoke_status, self.tokens = [], [202], 0
|
| 24 |
+
|
| 25 |
+
def __call__(self, kind, method, url, *, allowed_base, headers=None, json_body=None, content=None, log_body=None, timeout=30.0, log_url=None):
|
| 26 |
+
self.calls.append({"kind": kind, "url": url, "allowed_base": allowed_base, "headers": headers or {}, "json": json_body,
|
| 27 |
+
"form": parse_qs((content or b"").decode()), "log_body": log_body})
|
| 28 |
+
if kind == "fusion_token":
|
| 29 |
+
self.tokens += 1
|
| 30 |
+
return httpx.Response(200, json={"access_token": f"oci-token-{self.tokens}", "expires_in": 3600})
|
| 31 |
+
if kind == "fusion_invoke":
|
| 32 |
+
code = self.invoke_status.pop(0) if len(self.invoke_status) > 1 else self.invoke_status[0]
|
| 33 |
+
return httpx.Response(code, json={"jobId": "job-77"} if code < 300 else {"error": "no"})
|
| 34 |
+
raise AssertionError(f"unexpected egress {kind}")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class TestFusionDelivery(unittest.TestCase):
|
| 38 |
+
@classmethod
|
| 39 |
+
def setUpClass(cls):
|
| 40 |
+
cls.app, cls.c, cls.svc, cls.h, cls.pod_id = fusion_app()
|
| 41 |
+
r = cls.c.post("/api/agent-studio/clients", json={"name": "Fusion direct"}, headers=cls.h["admin"])
|
| 42 |
+
assert r.status_code == 201, r.text
|
| 43 |
+
cls.cid = r.json()["client_id"]
|
| 44 |
+
|
| 45 |
+
def setUp(self):
|
| 46 |
+
A._TOKENS.clear()
|
| 47 |
+
self.oracle = FakeOracle()
|
| 48 |
+
self._real = self.svc.egress.service_request
|
| 49 |
+
self.svc.egress.service_request = self.oracle
|
| 50 |
+
|
| 51 |
+
def tearDown(self):
|
| 52 |
+
self.svc.egress.service_request = self._real
|
| 53 |
+
|
| 54 |
+
def put(self, **fusion):
|
| 55 |
+
return self.c.put(f"/api/agent-studio/clients/{self.cid}/delivery", json={"mode": "fusion", "fusion": {**FUSION, **fusion}}, headers=self.h["admin"])
|
| 56 |
+
|
| 57 |
+
def test_a_settings_are_checked_and_the_secret_is_write_only(self):
|
| 58 |
+
r = self.put()
|
| 59 |
+
self.assertEqual(r.status_code, 400, r.text) # no secret yet
|
| 60 |
+
self.assertEqual(r.json()["code"], "BAD_DELIVERY")
|
| 61 |
+
r = self.put(base_url="http://fa-test.oraclecloud.com", client_secret="s3cret-value")
|
| 62 |
+
self.assertEqual(r.json()["code"], "BAD_URL") # https only
|
| 63 |
+
r = self.put(client_secret="s3cret-value")
|
| 64 |
+
self.assertEqual(r.status_code, 200, r.text)
|
| 65 |
+
out = r.json()
|
| 66 |
+
self.assertEqual((out["delivery"], out["fusion"]["workflow_code"], out["fusion"]["has_secret"]), ("fusion", "PATCH_TEST_CALLBACK_V3_7", True))
|
| 67 |
+
listed = json.dumps(self.c.get("/api/agent-studio/clients", headers=self.h["admin"]).json())
|
| 68 |
+
self.assertNotIn("s3cret-value", listed)
|
| 69 |
+
self.assertEqual(self.c.put(f"/api/agent-studio/clients/{self.cid}/delivery", json={"mode": "fusion", "fusion": FUSION},
|
| 70 |
+
headers=self.h["consultant"]).status_code, 403)
|
| 71 |
+
|
| 72 |
+
def test_b_test_signs_in_without_starting_a_workflow(self):
|
| 73 |
+
self.put(client_secret="s3cret-value")
|
| 74 |
+
r = self.c.post(f"/api/agent-studio/clients/{self.cid}/delivery/test", headers=self.h["admin"]).json()
|
| 75 |
+
self.assertTrue(r["ok"], r)
|
| 76 |
+
self.assertEqual([c["kind"] for c in self.oracle.calls], ["fusion_token"])
|
| 77 |
+
tok = self.oracle.calls[0]
|
| 78 |
+
self.assertEqual(tok["form"]["grant_type"], ["client_credentials"])
|
| 79 |
+
self.assertEqual(tok["form"]["scope"], [FUSION["scope"]])
|
| 80 |
+
self.assertEqual(base64.b64decode(tok["headers"]["Authorization"][6:]).decode(), "pw_invoker:s3cret-value")
|
| 81 |
+
self.assertNotIn("s3cret", json.dumps(tok["log_body"])) # the audit log never sees the secret
|
| 82 |
+
|
| 83 |
+
def test_c_an_event_starts_the_callback_workflow_with_what_read_event_reads(self):
|
| 84 |
+
self.put(client_secret="s3cret-value")
|
| 85 |
+
studio = AgentStudio(self.svc)
|
| 86 |
+
did = studio.queue(self.cid, None, "scripts_ready", {"correlation_id": "PT34-1", "scenarios": [{"id": "AP-1", "title": "Invoice"}]}, "cyc_abc123")
|
| 87 |
+
self.assertTrue(did) # no callback address needed
|
| 88 |
+
self.oracle.invoke_status = [401, 202] # an expired token: refreshed once
|
| 89 |
+
self.assertEqual(studio.deliver_due(), 1)
|
| 90 |
+
inv = [c for c in self.oracle.calls if c["kind"] == "fusion_invoke"]
|
| 91 |
+
self.assertEqual(inv[-1]["url"], "https://fa-test.oraclecloud.com/api/fusion-ai/orchestrator/agent/v2/PATCH_TEST_CALLBACK_V3_7/invokeAsync")
|
| 92 |
+
self.assertEqual(inv[-1]["allowed_base"], FUSION["base_url"])
|
| 93 |
+
self.assertEqual(inv[-1]["headers"]["Authorization"], "Bearer oci-token-2")
|
| 94 |
+
env = inv[-1]["json"]
|
| 95 |
+
p = env["parameters"]
|
| 96 |
+
self.assertEqual((p["event"], p["cycleId"], p["correlationId"], p["deliveryId"], p["verified"], p["source"], p["triggerType"]),
|
| 97 |
+
("scripts_ready", "cyc_abc123", "PT34-1", did, "sha256", "callback", "REST"))
|
| 98 |
+
self.assertEqual(json.loads(p["payloadJson"])["scenarios"][0]["id"], "AP-1")
|
| 99 |
+
self.assertEqual((env["invocationMode"], env["status"]), ("END_USER", "PUBLISHED"))
|
| 100 |
+
row = next(d for d in studio.deliveries() if d["delivery_id"] == did)
|
| 101 |
+
self.assertEqual((row["job_id"], row["status_code"]), ("job-77", 202))
|
| 102 |
+
|
| 103 |
+
def test_d_release_watch_goes_to_the_same_workflow_and_failures_are_retried(self):
|
| 104 |
+
self.put(client_secret="s3cret-value")
|
| 105 |
+
studio = AgentStudio(self.svc)
|
| 106 |
+
did = studio.queue(self.cid, None, "patch_update", {"release": "26D", "changes": [{"title": "x"}]})
|
| 107 |
+
self.oracle.invoke_status = [500]
|
| 108 |
+
self.assertEqual(studio.deliver_due(), 0)
|
| 109 |
+
row = next(d for d in studio.deliveries() if d["delivery_id"] == did)
|
| 110 |
+
self.assertEqual((row["attempts"], row["delivered_at"]), (1, None))
|
| 111 |
+
self.assertIn("HTTP 500", row["error"])
|
| 112 |
+
inv = [c for c in self.oracle.calls if c["kind"] == "fusion_invoke"][-1]
|
| 113 |
+
self.assertEqual(inv["json"]["parameters"]["source"], "release_watch")
|
| 114 |
+
|
| 115 |
+
def test_e_back_to_url_delivery(self):
|
| 116 |
+
self.put(client_secret="s3cret-value")
|
| 117 |
+
r = self.c.put(f"/api/agent-studio/clients/{self.cid}/delivery", json={"mode": "url"}, headers=self.h["admin"])
|
| 118 |
+
self.assertEqual(r.json()["delivery"], "url")
|
| 119 |
+
self.assertIsNone(AgentStudio(self.svc).queue(self.cid, None, "results", {}, "cyc_x")) # no address, nothing queued
|
| 120 |
+
with self.assertRaises(AgentStudioError):
|
| 121 |
+
AgentStudio(self.svc).test_delivery(self.cid, "t")
|
| 122 |
+
|
| 123 |
+
def test_large_payloads_are_cut_for_the_parameter(self):
|
| 124 |
+
env = A.fusion_envelope(A.FUSION_DEFAULTS, "callback", "dlv_1", {"event": "scripts_ready", "cycle_id": "c",
|
| 125 |
+
"scenarios": [{"id": f"S{i}", "title": "x" * 900} for i in range(200)]})
|
| 126 |
+
pj = json.loads(env["parameters"]["payloadJson"])
|
| 127 |
+
self.assertEqual((len(pj["scenarios"]), pj["scenarios_truncated"]), (50, 200))
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
if __name__ == "__main__":
|
| 131 |
+
unittest.main()
|
coworker/tests/test_llm_monitoring.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AI monitoring: every model call is a row with its route, model, latency, tokens and attempts (never its content);
|
| 2 |
+
evaluations score a model on fixed synthetic datasets; the optional LangSmith export never sends client data."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import unittest
|
| 6 |
+
|
| 7 |
+
import httpx
|
| 8 |
+
|
| 9 |
+
from coworker.llm.base import LLMRequest, ProviderError, Route, Sensitivity
|
| 10 |
+
from coworker.llm.schemas import ExecSummary, TriageHint
|
| 11 |
+
from coworker.platform import langsmith, llm_evals, llm_telemetry
|
| 12 |
+
from coworker.tests.test_ai_scenarios import fusion_app
|
| 13 |
+
|
| 14 |
+
COUNTS = {"total": 10, "executed": 10, "passed": 9, "failed": 1, "flaky": 0, "skipped": 0, "deferred": 0}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Broken:
|
| 18 |
+
name, route, model = "ollama", Route.LOCAL, "broken-model"
|
| 19 |
+
|
| 20 |
+
def available(self):
|
| 21 |
+
return True
|
| 22 |
+
|
| 23 |
+
def complete(self, req):
|
| 24 |
+
raise ProviderError("model unreachable")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class FakeLangSmith:
|
| 28 |
+
def __init__(self):
|
| 29 |
+
self.posts = []
|
| 30 |
+
|
| 31 |
+
def __call__(self, kind, method, url, *, allowed_base, headers=None, json_body=None, content=None, log_body=None, timeout=30.0, log_url=None):
|
| 32 |
+
assert kind == "langsmith" and headers["x-api-key"] == "ls-key-123456"
|
| 33 |
+
self.posts.append((url, json_body))
|
| 34 |
+
return httpx.Response(200, json={})
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class TestMonitoring(unittest.TestCase):
|
| 38 |
+
@classmethod
|
| 39 |
+
def setUpClass(cls):
|
| 40 |
+
cls.app, cls.c, cls.svc, cls.h, _ = fusion_app()
|
| 41 |
+
|
| 42 |
+
def test_a_a_call_is_recorded_without_its_content(self):
|
| 43 |
+
n0 = len(llm_telemetry.recent(self.svc.db, 500))
|
| 44 |
+
self.svc.router.call(LLMRequest("summary", Sensitivity.REDACTED, {"counts": COUNTS, "target": "mock"}, ExecSummary, "reporter", "run-m1"))
|
| 45 |
+
rows = llm_telemetry.recent(self.svc.db, 500)
|
| 46 |
+
self.assertEqual(len(rows), n0 + 1)
|
| 47 |
+
r = rows[0]
|
| 48 |
+
self.assertEqual((r["task"], r["route"], r["run_id"], r["ok"], r["planned_route"]), ("summary", "stub", "run-m1", True, "stub"))
|
| 49 |
+
self.assertIsNotNone(r["latency_ms"])
|
| 50 |
+
self.assertEqual(r["attempts"][0]["route"], "stub")
|
| 51 |
+
self.assertNotIn("payload", r)
|
| 52 |
+
self.assertNotIn("9", str({k: v for k, v in r.items() if k not in ("id", "ts", "latency_ms", "attempts")}))
|
| 53 |
+
|
| 54 |
+
def test_b_a_failing_model_is_recorded_with_why(self):
|
| 55 |
+
router = self.svc.router
|
| 56 |
+
real_local, real_on = router.local, router._local_on
|
| 57 |
+
router.local, router._local_on = Broken(), lambda: True
|
| 58 |
+
try:
|
| 59 |
+
out = router.call(LLMRequest("triage", Sensitivity.CLIENT, {"case_id": "X-1", "category": "timing", "confidence": 0.4, "evidence": [], "error": "e"},
|
| 60 |
+
TriageHint, "triage", "run-m2"))
|
| 61 |
+
finally:
|
| 62 |
+
router.local, router._local_on = real_local, real_on
|
| 63 |
+
self.assertEqual(out.route, Route.STUB)
|
| 64 |
+
r = llm_telemetry.recent(self.svc.db, 1)[0]
|
| 65 |
+
self.assertEqual((r["planned_route"], r["route"]), ("local", "stub"))
|
| 66 |
+
self.assertEqual(r["attempts"][0]["kind"], "provider")
|
| 67 |
+
self.assertIn("model unreachable", r["attempts"][0]["error"])
|
| 68 |
+
s = self.c.get("/api/ai/monitoring?days=1", headers=self.h["admin"]).json()
|
| 69 |
+
self.assertGreaterEqual(s["totals"]["fallbacks"], 1)
|
| 70 |
+
self.assertIn("triage", s["by_task"])
|
| 71 |
+
self.assertTrue(s["problems"])
|
| 72 |
+
|
| 73 |
+
def test_c_evaluations_score_every_dataset(self):
|
| 74 |
+
ev = llm_evals.start(self.svc, "stub", None, "admin", wait=True)
|
| 75 |
+
self.assertEqual(ev["status"], "done", ev.get("error"))
|
| 76 |
+
sm = ev["summary"]
|
| 77 |
+
self.assertEqual(set(sm["by_task"]), {"triage", "self_heal", "chat_intent", "summary", "chat_answer"})
|
| 78 |
+
self.assertEqual(sm["cases"], sum(d["cases"] for d in llm_evals.catalog()))
|
| 79 |
+
self.assertTrue(all(r["checks"] for r in ev["results"]))
|
| 80 |
+
tagged = self.svc.db.one("SELECT COUNT(*) AS n FROM llm_calls WHERE eval_id=?", (ev["eval_id"],))["n"]
|
| 81 |
+
self.assertEqual(tagged, sm["scored"])
|
| 82 |
+
# evaluation calls stay out of the production numbers
|
| 83 |
+
s = llm_telemetry.summary(self.svc.db, 1)
|
| 84 |
+
self.assertLess(s["totals"]["calls"], tagged + 10)
|
| 85 |
+
hist = self.c.get("/api/ai/evals", headers=self.h["admin"]).json()["items"]
|
| 86 |
+
self.assertEqual(hist[0]["eval_id"], ev["eval_id"])
|
| 87 |
+
|
| 88 |
+
def test_d_the_external_model_only_gets_tasks_that_may_go_to_it(self):
|
| 89 |
+
router = self.svc.router
|
| 90 |
+
real_f, real_ready = router.frontier, router.frontier_ready
|
| 91 |
+
router.frontier, router.frontier_ready = self.svc.stub, lambda: True # a stand-in for the external model
|
| 92 |
+
try:
|
| 93 |
+
ev = llm_evals.start(self.svc, "external", ["triage", "summary"], "admin", wait=True)
|
| 94 |
+
finally:
|
| 95 |
+
router.frontier, router.frontier_ready = real_f, real_ready
|
| 96 |
+
tri = [r for r in ev["results"] if r["task"] == "triage"]
|
| 97 |
+
self.assertTrue(tri and all(r.get("skipped") for r in tri))
|
| 98 |
+
self.assertTrue(all(not r.get("skipped") for r in ev["results"] if r["task"] == "summary"))
|
| 99 |
+
|
| 100 |
+
def test_e_langsmith_withholds_client_data_and_scores_evaluations(self):
|
| 101 |
+
ls = langsmith.get(self.svc)
|
| 102 |
+
fake = FakeLangSmith()
|
| 103 |
+
real = self.svc.egress.service_request
|
| 104 |
+
self.svc.egress.service_request = fake
|
| 105 |
+
try:
|
| 106 |
+
self.assertEqual(self.c.post("/api/ai/langsmith/key", json={"api_key": "ls-key-123456"}, headers=self.h["admin"]).status_code, 200)
|
| 107 |
+
self.c.put("/api/ai/langsmith", json={"enabled": True, "project": "pw-test"}, headers=self.h["admin"])
|
| 108 |
+
self.svc.router.call(LLMRequest("triage", Sensitivity.CLIENT, {"case_id": "SECRET-CASE", "category": "timing", "confidence": 0.4,
|
| 109 |
+
"evidence": ["Supplier Acme Corp"], "error": "e"}, TriageHint, "triage", "r"))
|
| 110 |
+
ls.flush()
|
| 111 |
+
run = fake.posts[-1][1]["post"][-1]
|
| 112 |
+
self.assertEqual(run["session_name"], "pw-test")
|
| 113 |
+
self.assertNotIn("SECRET-CASE", str(run))
|
| 114 |
+
self.assertNotIn("Acme", str(run))
|
| 115 |
+
self.assertIn("withheld", run["inputs"])
|
| 116 |
+
ev = llm_evals.start(self.svc, "stub", ["self_heal"], "admin", wait=True)
|
| 117 |
+
ls.flush()
|
| 118 |
+
urls = [u for u, _ in fake.posts]
|
| 119 |
+
self.assertTrue(any(u.endswith("/feedback") for u in urls))
|
| 120 |
+
eval_runs = [r for u, b in fake.posts if u.endswith("/runs/batch") for r in b["post"] if r["extra"]["metadata"]["eval_id"] == ev["eval_id"]]
|
| 121 |
+
self.assertTrue(eval_runs and "payload" in eval_runs[0]["inputs"]) # synthetic: sent with content
|
| 122 |
+
view = self.c.get("/api/ai/langsmith", headers=self.h["admin"]).json()
|
| 123 |
+
self.assertTrue(view["has_key"])
|
| 124 |
+
self.assertNotIn("ls-key-123456", str(view))
|
| 125 |
+
finally:
|
| 126 |
+
self.svc.egress.service_request = real
|
| 127 |
+
self.c.put("/api/ai/langsmith", json={"enabled": False}, headers=self.h["admin"])
|
| 128 |
+
|
| 129 |
+
def test_f_admin_only(self):
|
| 130 |
+
for path in ("/api/ai/monitoring", "/api/ai/calls", "/api/ai/evals", "/api/ai/langsmith"):
|
| 131 |
+
self.assertEqual(self.c.get(path, headers=self.h["consultant"]).status_code, 403, path)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
if __name__ == "__main__":
|
| 135 |
+
unittest.main()
|
docs/AGENT_STUDIO.md
CHANGED
|
@@ -125,6 +125,35 @@ The body is `{"code", "detail", "request_id"}`.
|
|
| 125 |
|
| 126 |
## 3. Callbacks (Patchwise → Fusion)
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
Callbacks are sent with `POST` to the callback address, as `Content-Type: application/json`, with these headers:
|
| 129 |
|
| 130 |
- `X-Patchwise-Event`: the event's name.
|
|
|
|
| 125 |
|
| 126 |
## 3. Callbacks (Patchwise → Fusion)
|
| 127 |
|
| 128 |
+
Each OAuth client chooses how its events reach Fusion (**Agent Studio → OAuth clients → Delivery**).
|
| 129 |
+
|
| 130 |
+
### Oracle Fusion directly (recommended; no relay)
|
| 131 |
+
|
| 132 |
+
Patchwise signs in to your OCI IAM identity domain with a confidential app (client credentials). The client secret is
|
| 133 |
+
write-only and kept in the vault; the token is held in memory only. Patchwise then starts the callback workflow:
|
| 134 |
+
`POST {Fusion address}/api/fusion-ai/orchestrator/agent/v2/{workflow code}/invokeAsync`, by default
|
| 135 |
+
`PATCH_TEST_CALLBACK_V3_7`.
|
| 136 |
+
|
| 137 |
+
The body is `{message, conversational, invocationMode, status, parameters}`. `parameters` holds what the workflow's
|
| 138 |
+
`READ_EVENT` reads:
|
| 139 |
+
|
| 140 |
+
- `event`, `cycleId`, `correlationId`, `deliveryId`;
|
| 141 |
+
- `payloadJson`: the body below as a string, with lists cut to 50 items when it would pass 60 KB;
|
| 142 |
+
- `verified: "sha256"`;
|
| 143 |
+
- `source`: `callback`, or `release_watch` for `patch_update`.
|
| 144 |
+
|
| 145 |
+
The settings are:
|
| 146 |
+
|
| 147 |
+
- the Fusion address, the token address, the client id and the client secret;
|
| 148 |
+
- the scope, only if your identity domain needs one;
|
| 149 |
+
- the workflow code, the invocation mode (`END_USER` or `ADMIN`) and the workflow status (`PUBLISHED` or `DRAFT`).
|
| 150 |
+
|
| 151 |
+
A 401 refreshes the token once. **Test sign-in** checks the app without starting a workflow. Fusion's `jobId` is
|
| 152 |
+
shown under **Callbacks**. The API is `PUT /api/agent-studio/clients/{id}/delivery` and
|
| 153 |
+
`POST /api/agent-studio/clients/{id}/delivery/test` (admin).
|
| 154 |
+
|
| 155 |
+
### Callback address (a relay or any receiver)
|
| 156 |
+
|
| 157 |
Callbacks are sent with `POST` to the callback address, as `Content-Type: application/json`, with these headers:
|
| 158 |
|
| 159 |
- `X-Patchwise-Event`: the event's name.
|
docs/AI_MONITORING.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AI monitoring, evaluations and LangSmith
|
| 2 |
+
|
| 3 |
+
Admins can see the page at **More → AI monitoring** (`/ai-monitoring`). It has three parts.
|
| 4 |
+
|
| 5 |
+
## How the models behave
|
| 6 |
+
|
| 7 |
+
Every model call the LLM router makes is one row in `llm_calls`. That covers runs, the assistant and evaluations.
|
| 8 |
+
|
| 9 |
+
**What each row holds**
|
| 10 |
+
|
| 11 |
+
- Task, node, run and prompt name.
|
| 12 |
+
- The route the privacy policy planned (`frontier`, `local` or `stub`) and what actually answered: route, provider and
|
| 13 |
+
model.
|
| 14 |
+
- Each attempt: route, model, latency, tokens, and why it failed. The failure kinds are `provider` (unreachable or an
|
| 15 |
+
error), `schema` (the answer did not fit) and `validation` (the answer broke the task's rule, such as an invented
|
| 16 |
+
number or an element name that is not on the page).
|
| 17 |
+
- Whether the deterministic baseline had to stand in, and the total latency and tokens.
|
| 18 |
+
|
| 19 |
+
**What is never stored:** prompts and answers. Rows older than 90 days are removed at startup.
|
| 20 |
+
|
| 21 |
+
**What the page shows:** calls, the share answered as planned (with the split between external model, local model and
|
| 22 |
+
built-in rules), rule checks failed, p50 and p95 latency, and tokens. It shows calls per day, tables by task and by
|
| 23 |
+
model, and the latest problems with a link to the run. Evaluation calls are left out of these numbers.
|
| 24 |
+
|
| 25 |
+
**API:** `GET /api/ai/monitoring?days=7` and `GET /api/ai/calls?limit=100&task=triage`.
|
| 26 |
+
|
| 27 |
+
## Evaluations
|
| 28 |
+
|
| 29 |
+
Datasets live in `coworker/evals/datasets/*.json`: synthetic cases drawn from real Patchwise work. Each case lists
|
| 30 |
+
its expectations.
|
| 31 |
+
|
| 32 |
+
| task | what is checked |
|
| 33 |
+
|---|---|
|
| 34 |
+
| `triage` | the failure category (ui_change, data, timing, real_defect) |
|
| 35 |
+
| `self_heal` | the new name of a renamed element, chosen from the page's own elements |
|
| 36 |
+
| `chat_intent` | the assistant's tool, among the plausible ones |
|
| 37 |
+
| `summary` | the summary keeps the key counts, invents no number and states no go/no-go |
|
| 38 |
+
| `chat_answer` | the rephrased answer keeps the facts and stays short and plain |
|
| 39 |
+
|
| 40 |
+
Each case is scored on three things:
|
| 41 |
+
|
| 42 |
+
1. The answer fits the task's schema.
|
| 43 |
+
2. It passes the task's rules, using the same `llm.router.validate_task` the app enforces.
|
| 44 |
+
3. It meets the case's expectations (`equals`, `in`, `contains_all`, `not_contains`, `len_between`).
|
| 45 |
+
|
| 46 |
+
The model is called directly, with no routing and no fallback, so the score is the model's own. The targets are:
|
| 47 |
+
|
| 48 |
+
- `local`: the Ollama model;
|
| 49 |
+
- `external`: the frontier model, only on tasks that may go to it, so local-only tasks are skipped;
|
| 50 |
+
- `stub`: the deterministic baseline, which gives a reference score to compare a model against.
|
| 51 |
+
|
| 52 |
+
The API is `GET /api/ai/evals/datasets`, `POST /api/ai/evals {"target": "local", "tasks": ["triage"]}`,
|
| 53 |
+
`GET /api/ai/evals` and `GET /api/ai/evals/{id}`. To add a case, add it to the dataset file; no code change is
|
| 54 |
+
needed.
|
| 55 |
+
|
| 56 |
+
## LangSmith (optional)
|
| 57 |
+
|
| 58 |
+
The export is off by default. Turn it on in the LangSmith card, or set `LANGSMITH_TRACING=true` with
|
| 59 |
+
`LANGSMITH_API_KEY` (and optionally `LANGSMITH_PROJECT` and `LANGSMITH_ENDPOINT`) as Space secrets. A key saved in the
|
| 60 |
+
app is write-only (vault `langsmith.api_key`).
|
| 61 |
+
|
| 62 |
+
- **Runs:** each model call becomes an `llm` run in the project. It carries the task, route, model, latency, tokens,
|
| 63 |
+
attempts and the Patchwise run id, and is tagged with the task and route.
|
| 64 |
+
- **Content policy:**
|
| 65 |
+
- Calls on **client** data (from the pod, results or chat) are sent as metadata only. Their prompt and answer are
|
| 66 |
+
replaced by a note.
|
| 67 |
+
- Calls on **public or redacted** data send their content only if "Also send prompts and answers" is on.
|
| 68 |
+
- **Evaluation** calls use synthetic data, so they are sent with content plus a `correct` feedback score (1 or 0),
|
| 69 |
+
with the failed checks as the comment.
|
| 70 |
+
- **Transport:** everything goes through the egress gate (https, LangSmith's host only), in batches every few
|
| 71 |
+
seconds. A failure is retried once and then dropped, so monitoring never blocks a run. **Send a test run** checks
|
| 72 |
+
the key.
|
web/src/App.tsx
CHANGED
|
@@ -32,6 +32,7 @@ const ScriptsPage = named(() => import('./pages/QueuesPages'), 'ScriptsPage');
|
|
| 32 |
const AccountPage = named(() => import('./pages/AccountPage'), 'AccountPage');
|
| 33 |
const IntegrationsPage = named(() => import('./pages/IntegrationsPage'), 'IntegrationsPage');
|
| 34 |
const AgentStudioPage = named(() => import('./pages/AgentStudioPage'), 'AgentStudioPage');
|
|
|
|
| 35 |
const ImportCasesPage = named(() => import('./pages/ImportCasesPage'), 'ImportCasesPage');
|
| 36 |
// the sign-in page carries the beUI animation library: only people who sign in download it
|
| 37 |
const LoginPage = named(() => import('./pages/LoginPage'), 'LoginPage');
|
|
@@ -101,6 +102,7 @@ export function AppRoutes() {
|
|
| 101 |
<Route path="/admin/users" element={<AdminOnly title="Users"><UsersPage /></AdminOnly>} />
|
| 102 |
<Route path="/integrations" element={<AdminOnly title="Integrations"><IntegrationsPage /></AdminOnly>} />
|
| 103 |
<Route path="/agent-studio" element={<AdminOnly title="Oracle AI Agent Studio"><AgentStudioPage /></AdminOnly>} />
|
|
|
|
| 104 |
{DevFixtures && DEV_FIXTURE_PATHS.includes('/dev/board-fixture') && <Route path="/dev/board-fixture" element={<Suspense fallback={null}><DevFixtures /></Suspense>} />}
|
| 105 |
{DevApprovalFixtures && DEV_FIXTURE_PATHS.includes('/dev/approval-fixture') && <Route path="/dev/approval-fixture" element={<Suspense fallback={null}><DevApprovalFixtures /></Suspense>} />}
|
| 106 |
<Route path="*" element={<NotFoundPage />} />
|
|
|
|
| 32 |
const AccountPage = named(() => import('./pages/AccountPage'), 'AccountPage');
|
| 33 |
const IntegrationsPage = named(() => import('./pages/IntegrationsPage'), 'IntegrationsPage');
|
| 34 |
const AgentStudioPage = named(() => import('./pages/AgentStudioPage'), 'AgentStudioPage');
|
| 35 |
+
const AiMonitoringPage = named(() => import('./pages/AiMonitoringPage'), 'AiMonitoringPage');
|
| 36 |
const ImportCasesPage = named(() => import('./pages/ImportCasesPage'), 'ImportCasesPage');
|
| 37 |
// the sign-in page carries the beUI animation library: only people who sign in download it
|
| 38 |
const LoginPage = named(() => import('./pages/LoginPage'), 'LoginPage');
|
|
|
|
| 102 |
<Route path="/admin/users" element={<AdminOnly title="Users"><UsersPage /></AdminOnly>} />
|
| 103 |
<Route path="/integrations" element={<AdminOnly title="Integrations"><IntegrationsPage /></AdminOnly>} />
|
| 104 |
<Route path="/agent-studio" element={<AdminOnly title="Oracle AI Agent Studio"><AgentStudioPage /></AdminOnly>} />
|
| 105 |
+
<Route path="/ai-monitoring" element={<AdminOnly title="AI monitoring"><AiMonitoringPage /></AdminOnly>} />
|
| 106 |
{DevFixtures && DEV_FIXTURE_PATHS.includes('/dev/board-fixture') && <Route path="/dev/board-fixture" element={<Suspense fallback={null}><DevFixtures /></Suspense>} />}
|
| 107 |
{DevApprovalFixtures && DEV_FIXTURE_PATHS.includes('/dev/approval-fixture') && <Route path="/dev/approval-fixture" element={<Suspense fallback={null}><DevApprovalFixtures /></Suspense>} />}
|
| 108 |
<Route path="*" element={<NotFoundPage />} />
|
web/src/api/openapi.json
CHANGED
|
@@ -783,6 +783,62 @@
|
|
| 783 |
"title": "DecisionIn",
|
| 784 |
"type": "object"
|
| 785 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 786 |
"FeatureIn": {
|
| 787 |
"additionalProperties": false,
|
| 788 |
"properties": {
|
|
@@ -813,6 +869,117 @@
|
|
| 813 |
"title": "ForgotIn",
|
| 814 |
"type": "object"
|
| 815 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 816 |
"HTTPValidationError": {
|
| 817 |
"properties": {
|
| 818 |
"detail": {
|
|
@@ -944,6 +1111,22 @@
|
|
| 944 |
"title": "IntegrationsView",
|
| 945 |
"type": "object"
|
| 946 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 947 |
"KeysIn": {
|
| 948 |
"properties": {
|
| 949 |
"keys": {
|
|
@@ -1101,6 +1284,60 @@
|
|
| 1101 |
"title": "LLMTestIn",
|
| 1102 |
"type": "object"
|
| 1103 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1104 |
"LastDelivery": {
|
| 1105 |
"properties": {
|
| 1106 |
"at": {
|
|
@@ -4743,9 +4980,31 @@
|
|
| 4743 |
]
|
| 4744 |
}
|
| 4745 |
},
|
| 4746 |
-
"/api/agent-studio/
|
| 4747 |
-
"
|
| 4748 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4749 |
"responses": {
|
| 4750 |
"200": {
|
| 4751 |
"content": {
|
|
@@ -4754,25 +5013,35 @@
|
|
| 4754 |
}
|
| 4755 |
},
|
| 4756 |
"description": "Successful Response"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4757 |
}
|
| 4758 |
},
|
| 4759 |
-
"summary": "
|
| 4760 |
"tags": [
|
| 4761 |
"agent-studio"
|
| 4762 |
]
|
| 4763 |
}
|
| 4764 |
},
|
| 4765 |
-
"/api/agent-studio/
|
| 4766 |
-
"
|
| 4767 |
-
"description": "
|
| 4768 |
-
"operationId": "
|
| 4769 |
"parameters": [
|
| 4770 |
{
|
| 4771 |
"in": "path",
|
| 4772 |
-
"name": "
|
| 4773 |
"required": true,
|
| 4774 |
"schema": {
|
| 4775 |
-
"title": "
|
| 4776 |
"type": "string"
|
| 4777 |
}
|
| 4778 |
}
|
|
@@ -4797,15 +5066,15 @@
|
|
| 4797 |
"description": "Validation Error"
|
| 4798 |
}
|
| 4799 |
},
|
| 4800 |
-
"summary": "
|
| 4801 |
"tags": [
|
| 4802 |
"agent-studio"
|
| 4803 |
]
|
| 4804 |
}
|
| 4805 |
},
|
| 4806 |
-
"/api/agent-studio/
|
| 4807 |
"get": {
|
| 4808 |
-
"operationId": "
|
| 4809 |
"responses": {
|
| 4810 |
"200": {
|
| 4811 |
"content": {
|
|
@@ -4816,15 +5085,27 @@
|
|
| 4816 |
"description": "Successful Response"
|
| 4817 |
}
|
| 4818 |
},
|
| 4819 |
-
"summary": "List
|
| 4820 |
"tags": [
|
| 4821 |
"agent-studio"
|
| 4822 |
]
|
| 4823 |
}
|
| 4824 |
},
|
| 4825 |
-
"/api/agent-studio/
|
| 4826 |
"get": {
|
| 4827 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4828 |
"responses": {
|
| 4829 |
"200": {
|
| 4830 |
"content": {
|
|
@@ -4833,11 +5114,59 @@
|
|
| 4833 |
}
|
| 4834 |
},
|
| 4835 |
"description": "Successful Response"
|
| 4836 |
-
}
|
| 4837 |
-
|
| 4838 |
-
|
| 4839 |
-
|
| 4840 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4841 |
]
|
| 4842 |
}
|
| 4843 |
},
|
|
@@ -5049,6 +5378,354 @@
|
|
| 5049 |
]
|
| 5050 |
}
|
| 5051 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5052 |
"/api/assistant/ask": {
|
| 5053 |
"post": {
|
| 5054 |
"description": "Ask Hermes one question. Pass the returned conversation_id to continue the same conversation.\nErrors: 409 HERMES_OFF, 503 HERMES_NOT_CONFIGURED, 502 HERMES_UNREACHABLE / HERMES_KEY_REJECTED / HERMES_ERROR,\n504 HERMES_TIMEOUT, 429 RATE_LIMITED, 404 NOT_FOUND (unknown or someone else's conversation).",
|
|
|
|
| 783 |
"title": "DecisionIn",
|
| 784 |
"type": "object"
|
| 785 |
},
|
| 786 |
+
"DeliveryIn": {
|
| 787 |
+
"properties": {
|
| 788 |
+
"fusion": {
|
| 789 |
+
"anyOf": [
|
| 790 |
+
{
|
| 791 |
+
"$ref": "#/components/schemas/FusionDeliveryIn"
|
| 792 |
+
},
|
| 793 |
+
{
|
| 794 |
+
"type": "null"
|
| 795 |
+
}
|
| 796 |
+
]
|
| 797 |
+
},
|
| 798 |
+
"mode": {
|
| 799 |
+
"enum": [
|
| 800 |
+
"url",
|
| 801 |
+
"fusion"
|
| 802 |
+
],
|
| 803 |
+
"title": "Mode",
|
| 804 |
+
"type": "string"
|
| 805 |
+
}
|
| 806 |
+
},
|
| 807 |
+
"required": [
|
| 808 |
+
"mode"
|
| 809 |
+
],
|
| 810 |
+
"title": "DeliveryIn",
|
| 811 |
+
"type": "object"
|
| 812 |
+
},
|
| 813 |
+
"EvalIn": {
|
| 814 |
+
"additionalProperties": false,
|
| 815 |
+
"properties": {
|
| 816 |
+
"target": {
|
| 817 |
+
"description": "stub, local or external",
|
| 818 |
+
"title": "Target",
|
| 819 |
+
"type": "string"
|
| 820 |
+
},
|
| 821 |
+
"tasks": {
|
| 822 |
+
"anyOf": [
|
| 823 |
+
{
|
| 824 |
+
"items": {
|
| 825 |
+
"type": "string"
|
| 826 |
+
},
|
| 827 |
+
"type": "array"
|
| 828 |
+
},
|
| 829 |
+
{
|
| 830 |
+
"type": "null"
|
| 831 |
+
}
|
| 832 |
+
],
|
| 833 |
+
"title": "Tasks"
|
| 834 |
+
}
|
| 835 |
+
},
|
| 836 |
+
"required": [
|
| 837 |
+
"target"
|
| 838 |
+
],
|
| 839 |
+
"title": "EvalIn",
|
| 840 |
+
"type": "object"
|
| 841 |
+
},
|
| 842 |
"FeatureIn": {
|
| 843 |
"additionalProperties": false,
|
| 844 |
"properties": {
|
|
|
|
| 869 |
"title": "ForgotIn",
|
| 870 |
"type": "object"
|
| 871 |
},
|
| 872 |
+
"FusionDeliveryIn": {
|
| 873 |
+
"properties": {
|
| 874 |
+
"base_url": {
|
| 875 |
+
"description": "https://<pod host>",
|
| 876 |
+
"maxLength": 300,
|
| 877 |
+
"minLength": 8,
|
| 878 |
+
"title": "Base Url",
|
| 879 |
+
"type": "string"
|
| 880 |
+
},
|
| 881 |
+
"client_id": {
|
| 882 |
+
"description": "the confidential app allowed to call invokeAsync",
|
| 883 |
+
"maxLength": 200,
|
| 884 |
+
"minLength": 1,
|
| 885 |
+
"title": "Client Id",
|
| 886 |
+
"type": "string"
|
| 887 |
+
},
|
| 888 |
+
"client_secret": {
|
| 889 |
+
"anyOf": [
|
| 890 |
+
{
|
| 891 |
+
"maxLength": 400,
|
| 892 |
+
"type": "string"
|
| 893 |
+
},
|
| 894 |
+
{
|
| 895 |
+
"type": "null"
|
| 896 |
+
}
|
| 897 |
+
],
|
| 898 |
+
"description": "write-only: kept in the vault",
|
| 899 |
+
"title": "Client Secret"
|
| 900 |
+
},
|
| 901 |
+
"conversational": {
|
| 902 |
+
"anyOf": [
|
| 903 |
+
{
|
| 904 |
+
"type": "boolean"
|
| 905 |
+
},
|
| 906 |
+
{
|
| 907 |
+
"type": "null"
|
| 908 |
+
}
|
| 909 |
+
],
|
| 910 |
+
"title": "Conversational"
|
| 911 |
+
},
|
| 912 |
+
"invocation_mode": {
|
| 913 |
+
"anyOf": [
|
| 914 |
+
{
|
| 915 |
+
"enum": [
|
| 916 |
+
"END_USER",
|
| 917 |
+
"ADMIN"
|
| 918 |
+
],
|
| 919 |
+
"type": "string"
|
| 920 |
+
},
|
| 921 |
+
{
|
| 922 |
+
"type": "null"
|
| 923 |
+
}
|
| 924 |
+
],
|
| 925 |
+
"title": "Invocation Mode"
|
| 926 |
+
},
|
| 927 |
+
"scope": {
|
| 928 |
+
"anyOf": [
|
| 929 |
+
{
|
| 930 |
+
"maxLength": 300,
|
| 931 |
+
"type": "string"
|
| 932 |
+
},
|
| 933 |
+
{
|
| 934 |
+
"type": "null"
|
| 935 |
+
}
|
| 936 |
+
],
|
| 937 |
+
"title": "Scope"
|
| 938 |
+
},
|
| 939 |
+
"token_url": {
|
| 940 |
+
"description": "the OCI IAM token address of the identity domain",
|
| 941 |
+
"maxLength": 400,
|
| 942 |
+
"minLength": 8,
|
| 943 |
+
"title": "Token Url",
|
| 944 |
+
"type": "string"
|
| 945 |
+
},
|
| 946 |
+
"workflow_code": {
|
| 947 |
+
"anyOf": [
|
| 948 |
+
{
|
| 949 |
+
"maxLength": 80,
|
| 950 |
+
"type": "string"
|
| 951 |
+
},
|
| 952 |
+
{
|
| 953 |
+
"type": "null"
|
| 954 |
+
}
|
| 955 |
+
],
|
| 956 |
+
"description": "default PATCH_TEST_CALLBACK_V3_7",
|
| 957 |
+
"title": "Workflow Code"
|
| 958 |
+
},
|
| 959 |
+
"workflow_status": {
|
| 960 |
+
"anyOf": [
|
| 961 |
+
{
|
| 962 |
+
"enum": [
|
| 963 |
+
"PUBLISHED",
|
| 964 |
+
"DRAFT"
|
| 965 |
+
],
|
| 966 |
+
"type": "string"
|
| 967 |
+
},
|
| 968 |
+
{
|
| 969 |
+
"type": "null"
|
| 970 |
+
}
|
| 971 |
+
],
|
| 972 |
+
"title": "Workflow Status"
|
| 973 |
+
}
|
| 974 |
+
},
|
| 975 |
+
"required": [
|
| 976 |
+
"base_url",
|
| 977 |
+
"token_url",
|
| 978 |
+
"client_id"
|
| 979 |
+
],
|
| 980 |
+
"title": "FusionDeliveryIn",
|
| 981 |
+
"type": "object"
|
| 982 |
+
},
|
| 983 |
"HTTPValidationError": {
|
| 984 |
"properties": {
|
| 985 |
"detail": {
|
|
|
|
| 1111 |
"title": "IntegrationsView",
|
| 1112 |
"type": "object"
|
| 1113 |
},
|
| 1114 |
+
"KeyIn": {
|
| 1115 |
+
"additionalProperties": false,
|
| 1116 |
+
"properties": {
|
| 1117 |
+
"api_key": {
|
| 1118 |
+
"maxLength": 400,
|
| 1119 |
+
"minLength": 8,
|
| 1120 |
+
"title": "Api Key",
|
| 1121 |
+
"type": "string"
|
| 1122 |
+
}
|
| 1123 |
+
},
|
| 1124 |
+
"required": [
|
| 1125 |
+
"api_key"
|
| 1126 |
+
],
|
| 1127 |
+
"title": "KeyIn",
|
| 1128 |
+
"type": "object"
|
| 1129 |
+
},
|
| 1130 |
"KeysIn": {
|
| 1131 |
"properties": {
|
| 1132 |
"keys": {
|
|
|
|
| 1284 |
"title": "LLMTestIn",
|
| 1285 |
"type": "object"
|
| 1286 |
},
|
| 1287 |
+
"LangSmithIn": {
|
| 1288 |
+
"additionalProperties": false,
|
| 1289 |
+
"properties": {
|
| 1290 |
+
"enabled": {
|
| 1291 |
+
"anyOf": [
|
| 1292 |
+
{
|
| 1293 |
+
"type": "boolean"
|
| 1294 |
+
},
|
| 1295 |
+
{
|
| 1296 |
+
"type": "null"
|
| 1297 |
+
}
|
| 1298 |
+
],
|
| 1299 |
+
"title": "Enabled"
|
| 1300 |
+
},
|
| 1301 |
+
"endpoint": {
|
| 1302 |
+
"anyOf": [
|
| 1303 |
+
{
|
| 1304 |
+
"maxLength": 300,
|
| 1305 |
+
"type": "string"
|
| 1306 |
+
},
|
| 1307 |
+
{
|
| 1308 |
+
"type": "null"
|
| 1309 |
+
}
|
| 1310 |
+
],
|
| 1311 |
+
"title": "Endpoint"
|
| 1312 |
+
},
|
| 1313 |
+
"project": {
|
| 1314 |
+
"anyOf": [
|
| 1315 |
+
{
|
| 1316 |
+
"maxLength": 120,
|
| 1317 |
+
"minLength": 1,
|
| 1318 |
+
"type": "string"
|
| 1319 |
+
},
|
| 1320 |
+
{
|
| 1321 |
+
"type": "null"
|
| 1322 |
+
}
|
| 1323 |
+
],
|
| 1324 |
+
"title": "Project"
|
| 1325 |
+
},
|
| 1326 |
+
"send_content": {
|
| 1327 |
+
"anyOf": [
|
| 1328 |
+
{
|
| 1329 |
+
"type": "boolean"
|
| 1330 |
+
},
|
| 1331 |
+
{
|
| 1332 |
+
"type": "null"
|
| 1333 |
+
}
|
| 1334 |
+
],
|
| 1335 |
+
"title": "Send Content"
|
| 1336 |
+
}
|
| 1337 |
+
},
|
| 1338 |
+
"title": "LangSmithIn",
|
| 1339 |
+
"type": "object"
|
| 1340 |
+
},
|
| 1341 |
"LastDelivery": {
|
| 1342 |
"properties": {
|
| 1343 |
"at": {
|
|
|
|
| 4980 |
]
|
| 4981 |
}
|
| 4982 |
},
|
| 4983 |
+
"/api/agent-studio/clients/{client_id}/delivery": {
|
| 4984 |
+
"put": {
|
| 4985 |
+
"description": "Where this client's events go: signed POSTs to its callback address, or straight to Oracle Fusion (invokeAsync).",
|
| 4986 |
+
"operationId": "set_delivery_api_agent_studio_clients__client_id__delivery_put",
|
| 4987 |
+
"parameters": [
|
| 4988 |
+
{
|
| 4989 |
+
"in": "path",
|
| 4990 |
+
"name": "client_id",
|
| 4991 |
+
"required": true,
|
| 4992 |
+
"schema": {
|
| 4993 |
+
"title": "Client Id",
|
| 4994 |
+
"type": "string"
|
| 4995 |
+
}
|
| 4996 |
+
}
|
| 4997 |
+
],
|
| 4998 |
+
"requestBody": {
|
| 4999 |
+
"content": {
|
| 5000 |
+
"application/json": {
|
| 5001 |
+
"schema": {
|
| 5002 |
+
"$ref": "#/components/schemas/DeliveryIn"
|
| 5003 |
+
}
|
| 5004 |
+
}
|
| 5005 |
+
},
|
| 5006 |
+
"required": true
|
| 5007 |
+
},
|
| 5008 |
"responses": {
|
| 5009 |
"200": {
|
| 5010 |
"content": {
|
|
|
|
| 5013 |
}
|
| 5014 |
},
|
| 5015 |
"description": "Successful Response"
|
| 5016 |
+
},
|
| 5017 |
+
"422": {
|
| 5018 |
+
"content": {
|
| 5019 |
+
"application/json": {
|
| 5020 |
+
"schema": {
|
| 5021 |
+
"$ref": "#/components/schemas/HTTPValidationError"
|
| 5022 |
+
}
|
| 5023 |
+
}
|
| 5024 |
+
},
|
| 5025 |
+
"description": "Validation Error"
|
| 5026 |
}
|
| 5027 |
},
|
| 5028 |
+
"summary": "Set Delivery",
|
| 5029 |
"tags": [
|
| 5030 |
"agent-studio"
|
| 5031 |
]
|
| 5032 |
}
|
| 5033 |
},
|
| 5034 |
+
"/api/agent-studio/clients/{client_id}/delivery/test": {
|
| 5035 |
+
"post": {
|
| 5036 |
+
"description": "Signs in to the Oracle identity domain with the saved app (no workflow is started).",
|
| 5037 |
+
"operationId": "test_delivery_api_agent_studio_clients__client_id__delivery_test_post",
|
| 5038 |
"parameters": [
|
| 5039 |
{
|
| 5040 |
"in": "path",
|
| 5041 |
+
"name": "client_id",
|
| 5042 |
"required": true,
|
| 5043 |
"schema": {
|
| 5044 |
+
"title": "Client Id",
|
| 5045 |
"type": "string"
|
| 5046 |
}
|
| 5047 |
}
|
|
|
|
| 5066 |
"description": "Validation Error"
|
| 5067 |
}
|
| 5068 |
},
|
| 5069 |
+
"summary": "Test Delivery",
|
| 5070 |
"tags": [
|
| 5071 |
"agent-studio"
|
| 5072 |
]
|
| 5073 |
}
|
| 5074 |
},
|
| 5075 |
+
"/api/agent-studio/cycles": {
|
| 5076 |
"get": {
|
| 5077 |
+
"operationId": "list_cycles_api_agent_studio_cycles_get",
|
| 5078 |
"responses": {
|
| 5079 |
"200": {
|
| 5080 |
"content": {
|
|
|
|
| 5085 |
"description": "Successful Response"
|
| 5086 |
}
|
| 5087 |
},
|
| 5088 |
+
"summary": "List Cycles",
|
| 5089 |
"tags": [
|
| 5090 |
"agent-studio"
|
| 5091 |
]
|
| 5092 |
}
|
| 5093 |
},
|
| 5094 |
+
"/api/agent-studio/cycles/{cycle_id}/package": {
|
| 5095 |
"get": {
|
| 5096 |
+
"description": "The test data package the Fusion side approved for this cycle.",
|
| 5097 |
+
"operationId": "cycle_package_api_agent_studio_cycles__cycle_id__package_get",
|
| 5098 |
+
"parameters": [
|
| 5099 |
+
{
|
| 5100 |
+
"in": "path",
|
| 5101 |
+
"name": "cycle_id",
|
| 5102 |
+
"required": true,
|
| 5103 |
+
"schema": {
|
| 5104 |
+
"title": "Cycle Id",
|
| 5105 |
+
"type": "string"
|
| 5106 |
+
}
|
| 5107 |
+
}
|
| 5108 |
+
],
|
| 5109 |
"responses": {
|
| 5110 |
"200": {
|
| 5111 |
"content": {
|
|
|
|
| 5114 |
}
|
| 5115 |
},
|
| 5116 |
"description": "Successful Response"
|
| 5117 |
+
},
|
| 5118 |
+
"422": {
|
| 5119 |
+
"content": {
|
| 5120 |
+
"application/json": {
|
| 5121 |
+
"schema": {
|
| 5122 |
+
"$ref": "#/components/schemas/HTTPValidationError"
|
| 5123 |
+
}
|
| 5124 |
+
}
|
| 5125 |
+
},
|
| 5126 |
+
"description": "Validation Error"
|
| 5127 |
+
}
|
| 5128 |
+
},
|
| 5129 |
+
"summary": "Cycle Package",
|
| 5130 |
+
"tags": [
|
| 5131 |
+
"agent-studio"
|
| 5132 |
+
]
|
| 5133 |
+
}
|
| 5134 |
+
},
|
| 5135 |
+
"/api/agent-studio/deliveries": {
|
| 5136 |
+
"get": {
|
| 5137 |
+
"operationId": "list_deliveries_api_agent_studio_deliveries_get",
|
| 5138 |
+
"responses": {
|
| 5139 |
+
"200": {
|
| 5140 |
+
"content": {
|
| 5141 |
+
"application/json": {
|
| 5142 |
+
"schema": {}
|
| 5143 |
+
}
|
| 5144 |
+
},
|
| 5145 |
+
"description": "Successful Response"
|
| 5146 |
+
}
|
| 5147 |
+
},
|
| 5148 |
+
"summary": "List Deliveries",
|
| 5149 |
+
"tags": [
|
| 5150 |
+
"agent-studio"
|
| 5151 |
+
]
|
| 5152 |
+
}
|
| 5153 |
+
},
|
| 5154 |
+
"/api/agent-studio/release-watch": {
|
| 5155 |
+
"get": {
|
| 5156 |
+
"operationId": "release_watch_api_agent_studio_release_watch_get",
|
| 5157 |
+
"responses": {
|
| 5158 |
+
"200": {
|
| 5159 |
+
"content": {
|
| 5160 |
+
"application/json": {
|
| 5161 |
+
"schema": {}
|
| 5162 |
+
}
|
| 5163 |
+
},
|
| 5164 |
+
"description": "Successful Response"
|
| 5165 |
+
}
|
| 5166 |
+
},
|
| 5167 |
+
"summary": "Release Watch",
|
| 5168 |
+
"tags": [
|
| 5169 |
+
"agent-studio"
|
| 5170 |
]
|
| 5171 |
}
|
| 5172 |
},
|
|
|
|
| 5378 |
]
|
| 5379 |
}
|
| 5380 |
},
|
| 5381 |
+
"/api/ai/calls": {
|
| 5382 |
+
"get": {
|
| 5383 |
+
"operationId": "calls_api_ai_calls_get",
|
| 5384 |
+
"parameters": [
|
| 5385 |
+
{
|
| 5386 |
+
"in": "query",
|
| 5387 |
+
"name": "limit",
|
| 5388 |
+
"required": false,
|
| 5389 |
+
"schema": {
|
| 5390 |
+
"default": 100,
|
| 5391 |
+
"maximum": 500,
|
| 5392 |
+
"minimum": 1,
|
| 5393 |
+
"title": "Limit",
|
| 5394 |
+
"type": "integer"
|
| 5395 |
+
}
|
| 5396 |
+
},
|
| 5397 |
+
{
|
| 5398 |
+
"in": "query",
|
| 5399 |
+
"name": "task",
|
| 5400 |
+
"required": false,
|
| 5401 |
+
"schema": {
|
| 5402 |
+
"anyOf": [
|
| 5403 |
+
{
|
| 5404 |
+
"type": "string"
|
| 5405 |
+
},
|
| 5406 |
+
{
|
| 5407 |
+
"type": "null"
|
| 5408 |
+
}
|
| 5409 |
+
],
|
| 5410 |
+
"title": "Task"
|
| 5411 |
+
}
|
| 5412 |
+
}
|
| 5413 |
+
],
|
| 5414 |
+
"responses": {
|
| 5415 |
+
"200": {
|
| 5416 |
+
"content": {
|
| 5417 |
+
"application/json": {
|
| 5418 |
+
"schema": {}
|
| 5419 |
+
}
|
| 5420 |
+
},
|
| 5421 |
+
"description": "Successful Response"
|
| 5422 |
+
},
|
| 5423 |
+
"422": {
|
| 5424 |
+
"content": {
|
| 5425 |
+
"application/json": {
|
| 5426 |
+
"schema": {
|
| 5427 |
+
"$ref": "#/components/schemas/HTTPValidationError"
|
| 5428 |
+
}
|
| 5429 |
+
}
|
| 5430 |
+
},
|
| 5431 |
+
"description": "Validation Error"
|
| 5432 |
+
}
|
| 5433 |
+
},
|
| 5434 |
+
"summary": "Calls",
|
| 5435 |
+
"tags": [
|
| 5436 |
+
"ai-monitoring"
|
| 5437 |
+
]
|
| 5438 |
+
}
|
| 5439 |
+
},
|
| 5440 |
+
"/api/ai/evals": {
|
| 5441 |
+
"get": {
|
| 5442 |
+
"operationId": "eval_history_api_ai_evals_get",
|
| 5443 |
+
"responses": {
|
| 5444 |
+
"200": {
|
| 5445 |
+
"content": {
|
| 5446 |
+
"application/json": {
|
| 5447 |
+
"schema": {}
|
| 5448 |
+
}
|
| 5449 |
+
},
|
| 5450 |
+
"description": "Successful Response"
|
| 5451 |
+
}
|
| 5452 |
+
},
|
| 5453 |
+
"summary": "Eval History",
|
| 5454 |
+
"tags": [
|
| 5455 |
+
"ai-monitoring"
|
| 5456 |
+
]
|
| 5457 |
+
},
|
| 5458 |
+
"post": {
|
| 5459 |
+
"operationId": "eval_start_api_ai_evals_post",
|
| 5460 |
+
"requestBody": {
|
| 5461 |
+
"content": {
|
| 5462 |
+
"application/json": {
|
| 5463 |
+
"schema": {
|
| 5464 |
+
"$ref": "#/components/schemas/EvalIn"
|
| 5465 |
+
}
|
| 5466 |
+
}
|
| 5467 |
+
},
|
| 5468 |
+
"required": true
|
| 5469 |
+
},
|
| 5470 |
+
"responses": {
|
| 5471 |
+
"202": {
|
| 5472 |
+
"content": {
|
| 5473 |
+
"application/json": {
|
| 5474 |
+
"schema": {}
|
| 5475 |
+
}
|
| 5476 |
+
},
|
| 5477 |
+
"description": "Successful Response"
|
| 5478 |
+
},
|
| 5479 |
+
"422": {
|
| 5480 |
+
"content": {
|
| 5481 |
+
"application/json": {
|
| 5482 |
+
"schema": {
|
| 5483 |
+
"$ref": "#/components/schemas/HTTPValidationError"
|
| 5484 |
+
}
|
| 5485 |
+
}
|
| 5486 |
+
},
|
| 5487 |
+
"description": "Validation Error"
|
| 5488 |
+
}
|
| 5489 |
+
},
|
| 5490 |
+
"summary": "Eval Start",
|
| 5491 |
+
"tags": [
|
| 5492 |
+
"ai-monitoring"
|
| 5493 |
+
]
|
| 5494 |
+
}
|
| 5495 |
+
},
|
| 5496 |
+
"/api/ai/evals/datasets": {
|
| 5497 |
+
"get": {
|
| 5498 |
+
"operationId": "eval_datasets_api_ai_evals_datasets_get",
|
| 5499 |
+
"responses": {
|
| 5500 |
+
"200": {
|
| 5501 |
+
"content": {
|
| 5502 |
+
"application/json": {
|
| 5503 |
+
"schema": {}
|
| 5504 |
+
}
|
| 5505 |
+
},
|
| 5506 |
+
"description": "Successful Response"
|
| 5507 |
+
}
|
| 5508 |
+
},
|
| 5509 |
+
"summary": "Eval Datasets",
|
| 5510 |
+
"tags": [
|
| 5511 |
+
"ai-monitoring"
|
| 5512 |
+
]
|
| 5513 |
+
}
|
| 5514 |
+
},
|
| 5515 |
+
"/api/ai/evals/{eval_id}": {
|
| 5516 |
+
"get": {
|
| 5517 |
+
"operationId": "eval_get_api_ai_evals__eval_id__get",
|
| 5518 |
+
"parameters": [
|
| 5519 |
+
{
|
| 5520 |
+
"in": "path",
|
| 5521 |
+
"name": "eval_id",
|
| 5522 |
+
"required": true,
|
| 5523 |
+
"schema": {
|
| 5524 |
+
"title": "Eval Id",
|
| 5525 |
+
"type": "string"
|
| 5526 |
+
}
|
| 5527 |
+
}
|
| 5528 |
+
],
|
| 5529 |
+
"responses": {
|
| 5530 |
+
"200": {
|
| 5531 |
+
"content": {
|
| 5532 |
+
"application/json": {
|
| 5533 |
+
"schema": {}
|
| 5534 |
+
}
|
| 5535 |
+
},
|
| 5536 |
+
"description": "Successful Response"
|
| 5537 |
+
},
|
| 5538 |
+
"422": {
|
| 5539 |
+
"content": {
|
| 5540 |
+
"application/json": {
|
| 5541 |
+
"schema": {
|
| 5542 |
+
"$ref": "#/components/schemas/HTTPValidationError"
|
| 5543 |
+
}
|
| 5544 |
+
}
|
| 5545 |
+
},
|
| 5546 |
+
"description": "Validation Error"
|
| 5547 |
+
}
|
| 5548 |
+
},
|
| 5549 |
+
"summary": "Eval Get",
|
| 5550 |
+
"tags": [
|
| 5551 |
+
"ai-monitoring"
|
| 5552 |
+
]
|
| 5553 |
+
}
|
| 5554 |
+
},
|
| 5555 |
+
"/api/ai/langsmith": {
|
| 5556 |
+
"get": {
|
| 5557 |
+
"operationId": "langsmith_view_api_ai_langsmith_get",
|
| 5558 |
+
"responses": {
|
| 5559 |
+
"200": {
|
| 5560 |
+
"content": {
|
| 5561 |
+
"application/json": {
|
| 5562 |
+
"schema": {}
|
| 5563 |
+
}
|
| 5564 |
+
},
|
| 5565 |
+
"description": "Successful Response"
|
| 5566 |
+
}
|
| 5567 |
+
},
|
| 5568 |
+
"summary": "Langsmith View",
|
| 5569 |
+
"tags": [
|
| 5570 |
+
"ai-monitoring"
|
| 5571 |
+
]
|
| 5572 |
+
},
|
| 5573 |
+
"put": {
|
| 5574 |
+
"operationId": "langsmith_save_api_ai_langsmith_put",
|
| 5575 |
+
"requestBody": {
|
| 5576 |
+
"content": {
|
| 5577 |
+
"application/json": {
|
| 5578 |
+
"schema": {
|
| 5579 |
+
"$ref": "#/components/schemas/LangSmithIn"
|
| 5580 |
+
}
|
| 5581 |
+
}
|
| 5582 |
+
},
|
| 5583 |
+
"required": true
|
| 5584 |
+
},
|
| 5585 |
+
"responses": {
|
| 5586 |
+
"200": {
|
| 5587 |
+
"content": {
|
| 5588 |
+
"application/json": {
|
| 5589 |
+
"schema": {}
|
| 5590 |
+
}
|
| 5591 |
+
},
|
| 5592 |
+
"description": "Successful Response"
|
| 5593 |
+
},
|
| 5594 |
+
"422": {
|
| 5595 |
+
"content": {
|
| 5596 |
+
"application/json": {
|
| 5597 |
+
"schema": {
|
| 5598 |
+
"$ref": "#/components/schemas/HTTPValidationError"
|
| 5599 |
+
}
|
| 5600 |
+
}
|
| 5601 |
+
},
|
| 5602 |
+
"description": "Validation Error"
|
| 5603 |
+
}
|
| 5604 |
+
},
|
| 5605 |
+
"summary": "Langsmith Save",
|
| 5606 |
+
"tags": [
|
| 5607 |
+
"ai-monitoring"
|
| 5608 |
+
]
|
| 5609 |
+
}
|
| 5610 |
+
},
|
| 5611 |
+
"/api/ai/langsmith/key": {
|
| 5612 |
+
"delete": {
|
| 5613 |
+
"operationId": "langsmith_key_delete_api_ai_langsmith_key_delete",
|
| 5614 |
+
"responses": {
|
| 5615 |
+
"200": {
|
| 5616 |
+
"content": {
|
| 5617 |
+
"application/json": {
|
| 5618 |
+
"schema": {}
|
| 5619 |
+
}
|
| 5620 |
+
},
|
| 5621 |
+
"description": "Successful Response"
|
| 5622 |
+
}
|
| 5623 |
+
},
|
| 5624 |
+
"summary": "Langsmith Key Delete",
|
| 5625 |
+
"tags": [
|
| 5626 |
+
"ai-monitoring"
|
| 5627 |
+
]
|
| 5628 |
+
},
|
| 5629 |
+
"post": {
|
| 5630 |
+
"operationId": "langsmith_key_api_ai_langsmith_key_post",
|
| 5631 |
+
"requestBody": {
|
| 5632 |
+
"content": {
|
| 5633 |
+
"application/json": {
|
| 5634 |
+
"schema": {
|
| 5635 |
+
"$ref": "#/components/schemas/KeyIn"
|
| 5636 |
+
}
|
| 5637 |
+
}
|
| 5638 |
+
},
|
| 5639 |
+
"required": true
|
| 5640 |
+
},
|
| 5641 |
+
"responses": {
|
| 5642 |
+
"200": {
|
| 5643 |
+
"content": {
|
| 5644 |
+
"application/json": {
|
| 5645 |
+
"schema": {}
|
| 5646 |
+
}
|
| 5647 |
+
},
|
| 5648 |
+
"description": "Successful Response"
|
| 5649 |
+
},
|
| 5650 |
+
"422": {
|
| 5651 |
+
"content": {
|
| 5652 |
+
"application/json": {
|
| 5653 |
+
"schema": {
|
| 5654 |
+
"$ref": "#/components/schemas/HTTPValidationError"
|
| 5655 |
+
}
|
| 5656 |
+
}
|
| 5657 |
+
},
|
| 5658 |
+
"description": "Validation Error"
|
| 5659 |
+
}
|
| 5660 |
+
},
|
| 5661 |
+
"summary": "Langsmith Key",
|
| 5662 |
+
"tags": [
|
| 5663 |
+
"ai-monitoring"
|
| 5664 |
+
]
|
| 5665 |
+
}
|
| 5666 |
+
},
|
| 5667 |
+
"/api/ai/langsmith/test": {
|
| 5668 |
+
"post": {
|
| 5669 |
+
"operationId": "langsmith_test_api_ai_langsmith_test_post",
|
| 5670 |
+
"responses": {
|
| 5671 |
+
"200": {
|
| 5672 |
+
"content": {
|
| 5673 |
+
"application/json": {
|
| 5674 |
+
"schema": {}
|
| 5675 |
+
}
|
| 5676 |
+
},
|
| 5677 |
+
"description": "Successful Response"
|
| 5678 |
+
}
|
| 5679 |
+
},
|
| 5680 |
+
"summary": "Langsmith Test",
|
| 5681 |
+
"tags": [
|
| 5682 |
+
"ai-monitoring"
|
| 5683 |
+
]
|
| 5684 |
+
}
|
| 5685 |
+
},
|
| 5686 |
+
"/api/ai/monitoring": {
|
| 5687 |
+
"get": {
|
| 5688 |
+
"operationId": "monitoring_api_ai_monitoring_get",
|
| 5689 |
+
"parameters": [
|
| 5690 |
+
{
|
| 5691 |
+
"in": "query",
|
| 5692 |
+
"name": "days",
|
| 5693 |
+
"required": false,
|
| 5694 |
+
"schema": {
|
| 5695 |
+
"default": 7,
|
| 5696 |
+
"maximum": 90,
|
| 5697 |
+
"minimum": 1,
|
| 5698 |
+
"title": "Days",
|
| 5699 |
+
"type": "integer"
|
| 5700 |
+
}
|
| 5701 |
+
}
|
| 5702 |
+
],
|
| 5703 |
+
"responses": {
|
| 5704 |
+
"200": {
|
| 5705 |
+
"content": {
|
| 5706 |
+
"application/json": {
|
| 5707 |
+
"schema": {}
|
| 5708 |
+
}
|
| 5709 |
+
},
|
| 5710 |
+
"description": "Successful Response"
|
| 5711 |
+
},
|
| 5712 |
+
"422": {
|
| 5713 |
+
"content": {
|
| 5714 |
+
"application/json": {
|
| 5715 |
+
"schema": {
|
| 5716 |
+
"$ref": "#/components/schemas/HTTPValidationError"
|
| 5717 |
+
}
|
| 5718 |
+
}
|
| 5719 |
+
},
|
| 5720 |
+
"description": "Validation Error"
|
| 5721 |
+
}
|
| 5722 |
+
},
|
| 5723 |
+
"summary": "Monitoring",
|
| 5724 |
+
"tags": [
|
| 5725 |
+
"ai-monitoring"
|
| 5726 |
+
]
|
| 5727 |
+
}
|
| 5728 |
+
},
|
| 5729 |
"/api/assistant/ask": {
|
| 5730 |
"post": {
|
| 5731 |
"description": "Ask Hermes one question. Pass the returned conversation_id to continue the same conversation.\nErrors: 409 HERMES_OFF, 503 HERMES_NOT_CONFIGURED, 502 HERMES_UNREACHABLE / HERMES_KEY_REJECTED / HERMES_ERROR,\n504 HERMES_TIMEOUT, 429 RATE_LIMITED, 404 NOT_FOUND (unknown or someone else's conversation).",
|
web/src/api/schema.d.ts
CHANGED
|
@@ -108,6 +108,46 @@ export interface paths {
|
|
| 108 |
patch: operations["update_client_api_agent_studio_clients__client_id__patch"];
|
| 109 |
trace?: never;
|
| 110 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
"/api/agent-studio/cycles": {
|
| 112 |
parameters: {
|
| 113 |
query?: never;
|
|
@@ -281,6 +321,145 @@ export interface paths {
|
|
| 281 |
patch?: never;
|
| 282 |
trace?: never;
|
| 283 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
"/api/assistant/ask": {
|
| 285 |
parameters: {
|
| 286 |
query?: never;
|
|
@@ -2715,6 +2894,25 @@ export interface components {
|
|
| 2715 |
/** Note */
|
| 2716 |
note?: string | null;
|
| 2717 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2718 |
/** FeatureIn */
|
| 2719 |
FeatureIn: {
|
| 2720 |
/** On */
|
|
@@ -2725,6 +2923,42 @@ export interface components {
|
|
| 2725 |
/** Email */
|
| 2726 |
email: string;
|
| 2727 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2728 |
/** HTTPValidationError */
|
| 2729 |
HTTPValidationError: {
|
| 2730 |
/** Detail */
|
|
@@ -2769,6 +3003,11 @@ export interface components {
|
|
| 2769 |
slack: components["schemas"]["IntegrationState"];
|
| 2770 |
teams: components["schemas"]["IntegrationState"];
|
| 2771 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2772 |
/** KeysIn */
|
| 2773 |
KeysIn: {
|
| 2774 |
/** Keys */
|
|
@@ -2812,6 +3051,17 @@ export interface components {
|
|
| 2812 |
*/
|
| 2813 |
target: "local" | "external";
|
| 2814 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2815 |
/** LastDelivery */
|
| 2816 |
LastDelivery: {
|
| 2817 |
/** At */
|
|
@@ -4118,6 +4368,72 @@ export interface operations {
|
|
| 4118 |
};
|
| 4119 |
};
|
| 4120 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4121 |
list_cycles_api_agent_studio_cycles_get: {
|
| 4122 |
parameters: {
|
| 4123 |
query?: never;
|
|
@@ -4383,6 +4699,299 @@ export interface operations {
|
|
| 4383 |
};
|
| 4384 |
};
|
| 4385 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4386 |
ask_api_assistant_ask_post: {
|
| 4387 |
parameters: {
|
| 4388 |
query?: never;
|
|
|
|
| 108 |
patch: operations["update_client_api_agent_studio_clients__client_id__patch"];
|
| 109 |
trace?: never;
|
| 110 |
};
|
| 111 |
+
"/api/agent-studio/clients/{client_id}/delivery": {
|
| 112 |
+
parameters: {
|
| 113 |
+
query?: never;
|
| 114 |
+
header?: never;
|
| 115 |
+
path?: never;
|
| 116 |
+
cookie?: never;
|
| 117 |
+
};
|
| 118 |
+
get?: never;
|
| 119 |
+
/**
|
| 120 |
+
* Set Delivery
|
| 121 |
+
* @description Where this client's events go: signed POSTs to its callback address, or straight to Oracle Fusion (invokeAsync).
|
| 122 |
+
*/
|
| 123 |
+
put: operations["set_delivery_api_agent_studio_clients__client_id__delivery_put"];
|
| 124 |
+
post?: never;
|
| 125 |
+
delete?: never;
|
| 126 |
+
options?: never;
|
| 127 |
+
head?: never;
|
| 128 |
+
patch?: never;
|
| 129 |
+
trace?: never;
|
| 130 |
+
};
|
| 131 |
+
"/api/agent-studio/clients/{client_id}/delivery/test": {
|
| 132 |
+
parameters: {
|
| 133 |
+
query?: never;
|
| 134 |
+
header?: never;
|
| 135 |
+
path?: never;
|
| 136 |
+
cookie?: never;
|
| 137 |
+
};
|
| 138 |
+
get?: never;
|
| 139 |
+
put?: never;
|
| 140 |
+
/**
|
| 141 |
+
* Test Delivery
|
| 142 |
+
* @description Signs in to the Oracle identity domain with the saved app (no workflow is started).
|
| 143 |
+
*/
|
| 144 |
+
post: operations["test_delivery_api_agent_studio_clients__client_id__delivery_test_post"];
|
| 145 |
+
delete?: never;
|
| 146 |
+
options?: never;
|
| 147 |
+
head?: never;
|
| 148 |
+
patch?: never;
|
| 149 |
+
trace?: never;
|
| 150 |
+
};
|
| 151 |
"/api/agent-studio/cycles": {
|
| 152 |
parameters: {
|
| 153 |
query?: never;
|
|
|
|
| 321 |
patch?: never;
|
| 322 |
trace?: never;
|
| 323 |
};
|
| 324 |
+
"/api/ai/calls": {
|
| 325 |
+
parameters: {
|
| 326 |
+
query?: never;
|
| 327 |
+
header?: never;
|
| 328 |
+
path?: never;
|
| 329 |
+
cookie?: never;
|
| 330 |
+
};
|
| 331 |
+
/** Calls */
|
| 332 |
+
get: operations["calls_api_ai_calls_get"];
|
| 333 |
+
put?: never;
|
| 334 |
+
post?: never;
|
| 335 |
+
delete?: never;
|
| 336 |
+
options?: never;
|
| 337 |
+
head?: never;
|
| 338 |
+
patch?: never;
|
| 339 |
+
trace?: never;
|
| 340 |
+
};
|
| 341 |
+
"/api/ai/evals": {
|
| 342 |
+
parameters: {
|
| 343 |
+
query?: never;
|
| 344 |
+
header?: never;
|
| 345 |
+
path?: never;
|
| 346 |
+
cookie?: never;
|
| 347 |
+
};
|
| 348 |
+
/** Eval History */
|
| 349 |
+
get: operations["eval_history_api_ai_evals_get"];
|
| 350 |
+
put?: never;
|
| 351 |
+
/** Eval Start */
|
| 352 |
+
post: operations["eval_start_api_ai_evals_post"];
|
| 353 |
+
delete?: never;
|
| 354 |
+
options?: never;
|
| 355 |
+
head?: never;
|
| 356 |
+
patch?: never;
|
| 357 |
+
trace?: never;
|
| 358 |
+
};
|
| 359 |
+
"/api/ai/evals/datasets": {
|
| 360 |
+
parameters: {
|
| 361 |
+
query?: never;
|
| 362 |
+
header?: never;
|
| 363 |
+
path?: never;
|
| 364 |
+
cookie?: never;
|
| 365 |
+
};
|
| 366 |
+
/** Eval Datasets */
|
| 367 |
+
get: operations["eval_datasets_api_ai_evals_datasets_get"];
|
| 368 |
+
put?: never;
|
| 369 |
+
post?: never;
|
| 370 |
+
delete?: never;
|
| 371 |
+
options?: never;
|
| 372 |
+
head?: never;
|
| 373 |
+
patch?: never;
|
| 374 |
+
trace?: never;
|
| 375 |
+
};
|
| 376 |
+
"/api/ai/evals/{eval_id}": {
|
| 377 |
+
parameters: {
|
| 378 |
+
query?: never;
|
| 379 |
+
header?: never;
|
| 380 |
+
path?: never;
|
| 381 |
+
cookie?: never;
|
| 382 |
+
};
|
| 383 |
+
/** Eval Get */
|
| 384 |
+
get: operations["eval_get_api_ai_evals__eval_id__get"];
|
| 385 |
+
put?: never;
|
| 386 |
+
post?: never;
|
| 387 |
+
delete?: never;
|
| 388 |
+
options?: never;
|
| 389 |
+
head?: never;
|
| 390 |
+
patch?: never;
|
| 391 |
+
trace?: never;
|
| 392 |
+
};
|
| 393 |
+
"/api/ai/langsmith": {
|
| 394 |
+
parameters: {
|
| 395 |
+
query?: never;
|
| 396 |
+
header?: never;
|
| 397 |
+
path?: never;
|
| 398 |
+
cookie?: never;
|
| 399 |
+
};
|
| 400 |
+
/** Langsmith View */
|
| 401 |
+
get: operations["langsmith_view_api_ai_langsmith_get"];
|
| 402 |
+
/** Langsmith Save */
|
| 403 |
+
put: operations["langsmith_save_api_ai_langsmith_put"];
|
| 404 |
+
post?: never;
|
| 405 |
+
delete?: never;
|
| 406 |
+
options?: never;
|
| 407 |
+
head?: never;
|
| 408 |
+
patch?: never;
|
| 409 |
+
trace?: never;
|
| 410 |
+
};
|
| 411 |
+
"/api/ai/langsmith/key": {
|
| 412 |
+
parameters: {
|
| 413 |
+
query?: never;
|
| 414 |
+
header?: never;
|
| 415 |
+
path?: never;
|
| 416 |
+
cookie?: never;
|
| 417 |
+
};
|
| 418 |
+
get?: never;
|
| 419 |
+
put?: never;
|
| 420 |
+
/** Langsmith Key */
|
| 421 |
+
post: operations["langsmith_key_api_ai_langsmith_key_post"];
|
| 422 |
+
/** Langsmith Key Delete */
|
| 423 |
+
delete: operations["langsmith_key_delete_api_ai_langsmith_key_delete"];
|
| 424 |
+
options?: never;
|
| 425 |
+
head?: never;
|
| 426 |
+
patch?: never;
|
| 427 |
+
trace?: never;
|
| 428 |
+
};
|
| 429 |
+
"/api/ai/langsmith/test": {
|
| 430 |
+
parameters: {
|
| 431 |
+
query?: never;
|
| 432 |
+
header?: never;
|
| 433 |
+
path?: never;
|
| 434 |
+
cookie?: never;
|
| 435 |
+
};
|
| 436 |
+
get?: never;
|
| 437 |
+
put?: never;
|
| 438 |
+
/** Langsmith Test */
|
| 439 |
+
post: operations["langsmith_test_api_ai_langsmith_test_post"];
|
| 440 |
+
delete?: never;
|
| 441 |
+
options?: never;
|
| 442 |
+
head?: never;
|
| 443 |
+
patch?: never;
|
| 444 |
+
trace?: never;
|
| 445 |
+
};
|
| 446 |
+
"/api/ai/monitoring": {
|
| 447 |
+
parameters: {
|
| 448 |
+
query?: never;
|
| 449 |
+
header?: never;
|
| 450 |
+
path?: never;
|
| 451 |
+
cookie?: never;
|
| 452 |
+
};
|
| 453 |
+
/** Monitoring */
|
| 454 |
+
get: operations["monitoring_api_ai_monitoring_get"];
|
| 455 |
+
put?: never;
|
| 456 |
+
post?: never;
|
| 457 |
+
delete?: never;
|
| 458 |
+
options?: never;
|
| 459 |
+
head?: never;
|
| 460 |
+
patch?: never;
|
| 461 |
+
trace?: never;
|
| 462 |
+
};
|
| 463 |
"/api/assistant/ask": {
|
| 464 |
parameters: {
|
| 465 |
query?: never;
|
|
|
|
| 2894 |
/** Note */
|
| 2895 |
note?: string | null;
|
| 2896 |
};
|
| 2897 |
+
/** DeliveryIn */
|
| 2898 |
+
DeliveryIn: {
|
| 2899 |
+
fusion?: components["schemas"]["FusionDeliveryIn"] | null;
|
| 2900 |
+
/**
|
| 2901 |
+
* Mode
|
| 2902 |
+
* @enum {string}
|
| 2903 |
+
*/
|
| 2904 |
+
mode: "url" | "fusion";
|
| 2905 |
+
};
|
| 2906 |
+
/** EvalIn */
|
| 2907 |
+
EvalIn: {
|
| 2908 |
+
/**
|
| 2909 |
+
* Target
|
| 2910 |
+
* @description stub, local or external
|
| 2911 |
+
*/
|
| 2912 |
+
target: string;
|
| 2913 |
+
/** Tasks */
|
| 2914 |
+
tasks?: string[] | null;
|
| 2915 |
+
};
|
| 2916 |
/** FeatureIn */
|
| 2917 |
FeatureIn: {
|
| 2918 |
/** On */
|
|
|
|
| 2923 |
/** Email */
|
| 2924 |
email: string;
|
| 2925 |
};
|
| 2926 |
+
/** FusionDeliveryIn */
|
| 2927 |
+
FusionDeliveryIn: {
|
| 2928 |
+
/**
|
| 2929 |
+
* Base Url
|
| 2930 |
+
* @description https://<pod host>
|
| 2931 |
+
*/
|
| 2932 |
+
base_url: string;
|
| 2933 |
+
/**
|
| 2934 |
+
* Client Id
|
| 2935 |
+
* @description the confidential app allowed to call invokeAsync
|
| 2936 |
+
*/
|
| 2937 |
+
client_id: string;
|
| 2938 |
+
/**
|
| 2939 |
+
* Client Secret
|
| 2940 |
+
* @description write-only: kept in the vault
|
| 2941 |
+
*/
|
| 2942 |
+
client_secret?: string | null;
|
| 2943 |
+
/** Conversational */
|
| 2944 |
+
conversational?: boolean | null;
|
| 2945 |
+
/** Invocation Mode */
|
| 2946 |
+
invocation_mode?: ("END_USER" | "ADMIN") | null;
|
| 2947 |
+
/** Scope */
|
| 2948 |
+
scope?: string | null;
|
| 2949 |
+
/**
|
| 2950 |
+
* Token Url
|
| 2951 |
+
* @description the OCI IAM token address of the identity domain
|
| 2952 |
+
*/
|
| 2953 |
+
token_url: string;
|
| 2954 |
+
/**
|
| 2955 |
+
* Workflow Code
|
| 2956 |
+
* @description default PATCH_TEST_CALLBACK_V3_7
|
| 2957 |
+
*/
|
| 2958 |
+
workflow_code?: string | null;
|
| 2959 |
+
/** Workflow Status */
|
| 2960 |
+
workflow_status?: ("PUBLISHED" | "DRAFT") | null;
|
| 2961 |
+
};
|
| 2962 |
/** HTTPValidationError */
|
| 2963 |
HTTPValidationError: {
|
| 2964 |
/** Detail */
|
|
|
|
| 3003 |
slack: components["schemas"]["IntegrationState"];
|
| 3004 |
teams: components["schemas"]["IntegrationState"];
|
| 3005 |
};
|
| 3006 |
+
/** KeyIn */
|
| 3007 |
+
KeyIn: {
|
| 3008 |
+
/** Api Key */
|
| 3009 |
+
api_key: string;
|
| 3010 |
+
};
|
| 3011 |
/** KeysIn */
|
| 3012 |
KeysIn: {
|
| 3013 |
/** Keys */
|
|
|
|
| 3051 |
*/
|
| 3052 |
target: "local" | "external";
|
| 3053 |
};
|
| 3054 |
+
/** LangSmithIn */
|
| 3055 |
+
LangSmithIn: {
|
| 3056 |
+
/** Enabled */
|
| 3057 |
+
enabled?: boolean | null;
|
| 3058 |
+
/** Endpoint */
|
| 3059 |
+
endpoint?: string | null;
|
| 3060 |
+
/** Project */
|
| 3061 |
+
project?: string | null;
|
| 3062 |
+
/** Send Content */
|
| 3063 |
+
send_content?: boolean | null;
|
| 3064 |
+
};
|
| 3065 |
/** LastDelivery */
|
| 3066 |
LastDelivery: {
|
| 3067 |
/** At */
|
|
|
|
| 4368 |
};
|
| 4369 |
};
|
| 4370 |
};
|
| 4371 |
+
set_delivery_api_agent_studio_clients__client_id__delivery_put: {
|
| 4372 |
+
parameters: {
|
| 4373 |
+
query?: never;
|
| 4374 |
+
header?: never;
|
| 4375 |
+
path: {
|
| 4376 |
+
client_id: string;
|
| 4377 |
+
};
|
| 4378 |
+
cookie?: never;
|
| 4379 |
+
};
|
| 4380 |
+
requestBody: {
|
| 4381 |
+
content: {
|
| 4382 |
+
"application/json": components["schemas"]["DeliveryIn"];
|
| 4383 |
+
};
|
| 4384 |
+
};
|
| 4385 |
+
responses: {
|
| 4386 |
+
/** @description Successful Response */
|
| 4387 |
+
200: {
|
| 4388 |
+
headers: {
|
| 4389 |
+
[name: string]: unknown;
|
| 4390 |
+
};
|
| 4391 |
+
content: {
|
| 4392 |
+
"application/json": unknown;
|
| 4393 |
+
};
|
| 4394 |
+
};
|
| 4395 |
+
/** @description Validation Error */
|
| 4396 |
+
422: {
|
| 4397 |
+
headers: {
|
| 4398 |
+
[name: string]: unknown;
|
| 4399 |
+
};
|
| 4400 |
+
content: {
|
| 4401 |
+
"application/json": components["schemas"]["HTTPValidationError"];
|
| 4402 |
+
};
|
| 4403 |
+
};
|
| 4404 |
+
};
|
| 4405 |
+
};
|
| 4406 |
+
test_delivery_api_agent_studio_clients__client_id__delivery_test_post: {
|
| 4407 |
+
parameters: {
|
| 4408 |
+
query?: never;
|
| 4409 |
+
header?: never;
|
| 4410 |
+
path: {
|
| 4411 |
+
client_id: string;
|
| 4412 |
+
};
|
| 4413 |
+
cookie?: never;
|
| 4414 |
+
};
|
| 4415 |
+
requestBody?: never;
|
| 4416 |
+
responses: {
|
| 4417 |
+
/** @description Successful Response */
|
| 4418 |
+
200: {
|
| 4419 |
+
headers: {
|
| 4420 |
+
[name: string]: unknown;
|
| 4421 |
+
};
|
| 4422 |
+
content: {
|
| 4423 |
+
"application/json": unknown;
|
| 4424 |
+
};
|
| 4425 |
+
};
|
| 4426 |
+
/** @description Validation Error */
|
| 4427 |
+
422: {
|
| 4428 |
+
headers: {
|
| 4429 |
+
[name: string]: unknown;
|
| 4430 |
+
};
|
| 4431 |
+
content: {
|
| 4432 |
+
"application/json": components["schemas"]["HTTPValidationError"];
|
| 4433 |
+
};
|
| 4434 |
+
};
|
| 4435 |
+
};
|
| 4436 |
+
};
|
| 4437 |
list_cycles_api_agent_studio_cycles_get: {
|
| 4438 |
parameters: {
|
| 4439 |
query?: never;
|
|
|
|
| 4699 |
};
|
| 4700 |
};
|
| 4701 |
};
|
| 4702 |
+
calls_api_ai_calls_get: {
|
| 4703 |
+
parameters: {
|
| 4704 |
+
query?: {
|
| 4705 |
+
limit?: number;
|
| 4706 |
+
task?: string | null;
|
| 4707 |
+
};
|
| 4708 |
+
header?: never;
|
| 4709 |
+
path?: never;
|
| 4710 |
+
cookie?: never;
|
| 4711 |
+
};
|
| 4712 |
+
requestBody?: never;
|
| 4713 |
+
responses: {
|
| 4714 |
+
/** @description Successful Response */
|
| 4715 |
+
200: {
|
| 4716 |
+
headers: {
|
| 4717 |
+
[name: string]: unknown;
|
| 4718 |
+
};
|
| 4719 |
+
content: {
|
| 4720 |
+
"application/json": unknown;
|
| 4721 |
+
};
|
| 4722 |
+
};
|
| 4723 |
+
/** @description Validation Error */
|
| 4724 |
+
422: {
|
| 4725 |
+
headers: {
|
| 4726 |
+
[name: string]: unknown;
|
| 4727 |
+
};
|
| 4728 |
+
content: {
|
| 4729 |
+
"application/json": components["schemas"]["HTTPValidationError"];
|
| 4730 |
+
};
|
| 4731 |
+
};
|
| 4732 |
+
};
|
| 4733 |
+
};
|
| 4734 |
+
eval_history_api_ai_evals_get: {
|
| 4735 |
+
parameters: {
|
| 4736 |
+
query?: never;
|
| 4737 |
+
header?: never;
|
| 4738 |
+
path?: never;
|
| 4739 |
+
cookie?: never;
|
| 4740 |
+
};
|
| 4741 |
+
requestBody?: never;
|
| 4742 |
+
responses: {
|
| 4743 |
+
/** @description Successful Response */
|
| 4744 |
+
200: {
|
| 4745 |
+
headers: {
|
| 4746 |
+
[name: string]: unknown;
|
| 4747 |
+
};
|
| 4748 |
+
content: {
|
| 4749 |
+
"application/json": unknown;
|
| 4750 |
+
};
|
| 4751 |
+
};
|
| 4752 |
+
};
|
| 4753 |
+
};
|
| 4754 |
+
eval_start_api_ai_evals_post: {
|
| 4755 |
+
parameters: {
|
| 4756 |
+
query?: never;
|
| 4757 |
+
header?: never;
|
| 4758 |
+
path?: never;
|
| 4759 |
+
cookie?: never;
|
| 4760 |
+
};
|
| 4761 |
+
requestBody: {
|
| 4762 |
+
content: {
|
| 4763 |
+
"application/json": components["schemas"]["EvalIn"];
|
| 4764 |
+
};
|
| 4765 |
+
};
|
| 4766 |
+
responses: {
|
| 4767 |
+
/** @description Successful Response */
|
| 4768 |
+
202: {
|
| 4769 |
+
headers: {
|
| 4770 |
+
[name: string]: unknown;
|
| 4771 |
+
};
|
| 4772 |
+
content: {
|
| 4773 |
+
"application/json": unknown;
|
| 4774 |
+
};
|
| 4775 |
+
};
|
| 4776 |
+
/** @description Validation Error */
|
| 4777 |
+
422: {
|
| 4778 |
+
headers: {
|
| 4779 |
+
[name: string]: unknown;
|
| 4780 |
+
};
|
| 4781 |
+
content: {
|
| 4782 |
+
"application/json": components["schemas"]["HTTPValidationError"];
|
| 4783 |
+
};
|
| 4784 |
+
};
|
| 4785 |
+
};
|
| 4786 |
+
};
|
| 4787 |
+
eval_datasets_api_ai_evals_datasets_get: {
|
| 4788 |
+
parameters: {
|
| 4789 |
+
query?: never;
|
| 4790 |
+
header?: never;
|
| 4791 |
+
path?: never;
|
| 4792 |
+
cookie?: never;
|
| 4793 |
+
};
|
| 4794 |
+
requestBody?: never;
|
| 4795 |
+
responses: {
|
| 4796 |
+
/** @description Successful Response */
|
| 4797 |
+
200: {
|
| 4798 |
+
headers: {
|
| 4799 |
+
[name: string]: unknown;
|
| 4800 |
+
};
|
| 4801 |
+
content: {
|
| 4802 |
+
"application/json": unknown;
|
| 4803 |
+
};
|
| 4804 |
+
};
|
| 4805 |
+
};
|
| 4806 |
+
};
|
| 4807 |
+
eval_get_api_ai_evals__eval_id__get: {
|
| 4808 |
+
parameters: {
|
| 4809 |
+
query?: never;
|
| 4810 |
+
header?: never;
|
| 4811 |
+
path: {
|
| 4812 |
+
eval_id: string;
|
| 4813 |
+
};
|
| 4814 |
+
cookie?: never;
|
| 4815 |
+
};
|
| 4816 |
+
requestBody?: never;
|
| 4817 |
+
responses: {
|
| 4818 |
+
/** @description Successful Response */
|
| 4819 |
+
200: {
|
| 4820 |
+
headers: {
|
| 4821 |
+
[name: string]: unknown;
|
| 4822 |
+
};
|
| 4823 |
+
content: {
|
| 4824 |
+
"application/json": unknown;
|
| 4825 |
+
};
|
| 4826 |
+
};
|
| 4827 |
+
/** @description Validation Error */
|
| 4828 |
+
422: {
|
| 4829 |
+
headers: {
|
| 4830 |
+
[name: string]: unknown;
|
| 4831 |
+
};
|
| 4832 |
+
content: {
|
| 4833 |
+
"application/json": components["schemas"]["HTTPValidationError"];
|
| 4834 |
+
};
|
| 4835 |
+
};
|
| 4836 |
+
};
|
| 4837 |
+
};
|
| 4838 |
+
langsmith_view_api_ai_langsmith_get: {
|
| 4839 |
+
parameters: {
|
| 4840 |
+
query?: never;
|
| 4841 |
+
header?: never;
|
| 4842 |
+
path?: never;
|
| 4843 |
+
cookie?: never;
|
| 4844 |
+
};
|
| 4845 |
+
requestBody?: never;
|
| 4846 |
+
responses: {
|
| 4847 |
+
/** @description Successful Response */
|
| 4848 |
+
200: {
|
| 4849 |
+
headers: {
|
| 4850 |
+
[name: string]: unknown;
|
| 4851 |
+
};
|
| 4852 |
+
content: {
|
| 4853 |
+
"application/json": unknown;
|
| 4854 |
+
};
|
| 4855 |
+
};
|
| 4856 |
+
};
|
| 4857 |
+
};
|
| 4858 |
+
langsmith_save_api_ai_langsmith_put: {
|
| 4859 |
+
parameters: {
|
| 4860 |
+
query?: never;
|
| 4861 |
+
header?: never;
|
| 4862 |
+
path?: never;
|
| 4863 |
+
cookie?: never;
|
| 4864 |
+
};
|
| 4865 |
+
requestBody: {
|
| 4866 |
+
content: {
|
| 4867 |
+
"application/json": components["schemas"]["LangSmithIn"];
|
| 4868 |
+
};
|
| 4869 |
+
};
|
| 4870 |
+
responses: {
|
| 4871 |
+
/** @description Successful Response */
|
| 4872 |
+
200: {
|
| 4873 |
+
headers: {
|
| 4874 |
+
[name: string]: unknown;
|
| 4875 |
+
};
|
| 4876 |
+
content: {
|
| 4877 |
+
"application/json": unknown;
|
| 4878 |
+
};
|
| 4879 |
+
};
|
| 4880 |
+
/** @description Validation Error */
|
| 4881 |
+
422: {
|
| 4882 |
+
headers: {
|
| 4883 |
+
[name: string]: unknown;
|
| 4884 |
+
};
|
| 4885 |
+
content: {
|
| 4886 |
+
"application/json": components["schemas"]["HTTPValidationError"];
|
| 4887 |
+
};
|
| 4888 |
+
};
|
| 4889 |
+
};
|
| 4890 |
+
};
|
| 4891 |
+
langsmith_key_api_ai_langsmith_key_post: {
|
| 4892 |
+
parameters: {
|
| 4893 |
+
query?: never;
|
| 4894 |
+
header?: never;
|
| 4895 |
+
path?: never;
|
| 4896 |
+
cookie?: never;
|
| 4897 |
+
};
|
| 4898 |
+
requestBody: {
|
| 4899 |
+
content: {
|
| 4900 |
+
"application/json": components["schemas"]["KeyIn"];
|
| 4901 |
+
};
|
| 4902 |
+
};
|
| 4903 |
+
responses: {
|
| 4904 |
+
/** @description Successful Response */
|
| 4905 |
+
200: {
|
| 4906 |
+
headers: {
|
| 4907 |
+
[name: string]: unknown;
|
| 4908 |
+
};
|
| 4909 |
+
content: {
|
| 4910 |
+
"application/json": unknown;
|
| 4911 |
+
};
|
| 4912 |
+
};
|
| 4913 |
+
/** @description Validation Error */
|
| 4914 |
+
422: {
|
| 4915 |
+
headers: {
|
| 4916 |
+
[name: string]: unknown;
|
| 4917 |
+
};
|
| 4918 |
+
content: {
|
| 4919 |
+
"application/json": components["schemas"]["HTTPValidationError"];
|
| 4920 |
+
};
|
| 4921 |
+
};
|
| 4922 |
+
};
|
| 4923 |
+
};
|
| 4924 |
+
langsmith_key_delete_api_ai_langsmith_key_delete: {
|
| 4925 |
+
parameters: {
|
| 4926 |
+
query?: never;
|
| 4927 |
+
header?: never;
|
| 4928 |
+
path?: never;
|
| 4929 |
+
cookie?: never;
|
| 4930 |
+
};
|
| 4931 |
+
requestBody?: never;
|
| 4932 |
+
responses: {
|
| 4933 |
+
/** @description Successful Response */
|
| 4934 |
+
200: {
|
| 4935 |
+
headers: {
|
| 4936 |
+
[name: string]: unknown;
|
| 4937 |
+
};
|
| 4938 |
+
content: {
|
| 4939 |
+
"application/json": unknown;
|
| 4940 |
+
};
|
| 4941 |
+
};
|
| 4942 |
+
};
|
| 4943 |
+
};
|
| 4944 |
+
langsmith_test_api_ai_langsmith_test_post: {
|
| 4945 |
+
parameters: {
|
| 4946 |
+
query?: never;
|
| 4947 |
+
header?: never;
|
| 4948 |
+
path?: never;
|
| 4949 |
+
cookie?: never;
|
| 4950 |
+
};
|
| 4951 |
+
requestBody?: never;
|
| 4952 |
+
responses: {
|
| 4953 |
+
/** @description Successful Response */
|
| 4954 |
+
200: {
|
| 4955 |
+
headers: {
|
| 4956 |
+
[name: string]: unknown;
|
| 4957 |
+
};
|
| 4958 |
+
content: {
|
| 4959 |
+
"application/json": unknown;
|
| 4960 |
+
};
|
| 4961 |
+
};
|
| 4962 |
+
};
|
| 4963 |
+
};
|
| 4964 |
+
monitoring_api_ai_monitoring_get: {
|
| 4965 |
+
parameters: {
|
| 4966 |
+
query?: {
|
| 4967 |
+
days?: number;
|
| 4968 |
+
};
|
| 4969 |
+
header?: never;
|
| 4970 |
+
path?: never;
|
| 4971 |
+
cookie?: never;
|
| 4972 |
+
};
|
| 4973 |
+
requestBody?: never;
|
| 4974 |
+
responses: {
|
| 4975 |
+
/** @description Successful Response */
|
| 4976 |
+
200: {
|
| 4977 |
+
headers: {
|
| 4978 |
+
[name: string]: unknown;
|
| 4979 |
+
};
|
| 4980 |
+
content: {
|
| 4981 |
+
"application/json": unknown;
|
| 4982 |
+
};
|
| 4983 |
+
};
|
| 4984 |
+
/** @description Validation Error */
|
| 4985 |
+
422: {
|
| 4986 |
+
headers: {
|
| 4987 |
+
[name: string]: unknown;
|
| 4988 |
+
};
|
| 4989 |
+
content: {
|
| 4990 |
+
"application/json": components["schemas"]["HTTPValidationError"];
|
| 4991 |
+
};
|
| 4992 |
+
};
|
| 4993 |
+
};
|
| 4994 |
+
};
|
| 4995 |
ask_api_assistant_ask_post: {
|
| 4996 |
parameters: {
|
| 4997 |
query?: never;
|
web/src/components/shell/AppSidebar.tsx
CHANGED
|
@@ -2,8 +2,7 @@ import '../../shell.css';
|
|
| 2 |
import { Menu, Tooltip, useMantineColorScheme } from '@mantine/core';
|
| 3 |
import {
|
| 4 |
IconAlertTriangle, IconBug, IconCheck, IconDeviceDesktop, IconFileReport, IconHandStop, IconHome, IconListCheck, IconLogout, IconMessageCircle, IconMoon,
|
| 5 |
-
IconPlayerPlay, IconPlug, IconRobot, IconServer, IconSettings, IconSun,
|
| 6 |
-
} from '@/icons';
|
| 7 |
import type { ReactNode } from 'react';
|
| 8 |
import { NavLink as RouterLink, useLocation } from 'react-router-dom';
|
| 9 |
import type { Schemas } from '../../api/client';
|
|
@@ -37,6 +36,8 @@ export const SETUP: NavItem[] = [
|
|
| 37 |
export const INTEGRATIONS: NavItem = { to: '/integrations', label: 'Integrations', icon: <IconPlug {...ICON} /> };
|
| 38 |
/** Oracle AI Agent Studio: the Fusion workflow that drives test cycles (OAuth clients, cycles, callbacks, release watch). */
|
| 39 |
export const AGENT_STUDIO: NavItem = { to: '/agent-studio', label: 'Agent Studio', icon: <IconRobot {...ICON} /> };
|
|
|
|
|
|
|
| 40 |
export const SETTINGS: NavItem = { to: '/admin', label: 'Settings', icon: <IconSettings {...ICON} />,
|
| 41 |
match: (p) => ['/admin', '/agents', '/heal', '/scripts', '/learner', '/audit'].some((x) => p === x || p.startsWith(`${x}/`)) };
|
| 42 |
|
|
@@ -130,6 +131,7 @@ export function AppSidebar({ onNavigate }: { onNavigate?: () => void }) {
|
|
| 130 |
<h6>Setup</h6>
|
| 131 |
{SETUP.map((it) => <NavLink key={it.to} item={it} onNavigate={onNavigate} />)}
|
| 132 |
{can('admin') && <NavLink item={AGENT_STUDIO} onNavigate={onNavigate} />}
|
|
|
|
| 133 |
{can('admin') && <NavLink item={INTEGRATIONS} onNavigate={onNavigate} />}
|
| 134 |
{can('admin') && <NavLink item={SETTINGS} onNavigate={onNavigate} />}
|
| 135 |
</nav>
|
|
|
|
| 2 |
import { Menu, Tooltip, useMantineColorScheme } from '@mantine/core';
|
| 3 |
import {
|
| 4 |
IconAlertTriangle, IconBug, IconCheck, IconDeviceDesktop, IconFileReport, IconHandStop, IconHome, IconListCheck, IconLogout, IconMessageCircle, IconMoon,
|
| 5 |
+
IconPlayerPlay, IconPlug, IconRobot, IconServer, IconSettings, IconSun, IconActivity } from '@/icons';
|
|
|
|
| 6 |
import type { ReactNode } from 'react';
|
| 7 |
import { NavLink as RouterLink, useLocation } from 'react-router-dom';
|
| 8 |
import type { Schemas } from '../../api/client';
|
|
|
|
| 36 |
export const INTEGRATIONS: NavItem = { to: '/integrations', label: 'Integrations', icon: <IconPlug {...ICON} /> };
|
| 37 |
/** Oracle AI Agent Studio: the Fusion workflow that drives test cycles (OAuth clients, cycles, callbacks, release watch). */
|
| 38 |
export const AGENT_STUDIO: NavItem = { to: '/agent-studio', label: 'Agent Studio', icon: <IconRobot {...ICON} /> };
|
| 39 |
+
/** How the AI models behave: calls, failures, latency, tokens, evaluations and the LangSmith export. */
|
| 40 |
+
export const AI_MONITORING: NavItem = { to: '/ai-monitoring', label: 'AI monitoring', icon: <IconActivity {...ICON} /> };
|
| 41 |
export const SETTINGS: NavItem = { to: '/admin', label: 'Settings', icon: <IconSettings {...ICON} />,
|
| 42 |
match: (p) => ['/admin', '/agents', '/heal', '/scripts', '/learner', '/audit'].some((x) => p === x || p.startsWith(`${x}/`)) };
|
| 43 |
|
|
|
|
| 131 |
<h6>Setup</h6>
|
| 132 |
{SETUP.map((it) => <NavLink key={it.to} item={it} onNavigate={onNavigate} />)}
|
| 133 |
{can('admin') && <NavLink item={AGENT_STUDIO} onNavigate={onNavigate} />}
|
| 134 |
+
{can('admin') && <NavLink item={AI_MONITORING} onNavigate={onNavigate} />}
|
| 135 |
{can('admin') && <NavLink item={INTEGRATIONS} onNavigate={onNavigate} />}
|
| 136 |
{can('admin') && <NavLink item={SETTINGS} onNavigate={onNavigate} />}
|
| 137 |
</nav>
|
web/src/components/shell/IconRail.tsx
CHANGED
|
@@ -5,7 +5,7 @@ import { NavLink as RouterLink, useLocation } from 'react-router-dom';
|
|
| 5 |
import { useBrand, useHealth, useKill, useRuns } from '../../api/hooks';
|
| 6 |
import { useAuth } from '../../auth/AuthContext';
|
| 7 |
import { useWaitsOnMe } from '../../waiting';
|
| 8 |
-
import { AccountMenu, AGENT_STUDIO, INTEGRATIONS, LIBRARY, MAIN, SETTINGS, SETUP, type NavItem } from './AppSidebar';
|
| 9 |
import { envKind, useChosenEnv } from './EnvSwitcher';
|
| 10 |
|
| 11 |
/** The name under each icon: short, and always part of the page's full name (so what is read out matches what is shown). */
|
|
@@ -41,7 +41,7 @@ export function IconRail() {
|
|
| 41 |
const env = useChosenEnv().pod;
|
| 42 |
const waiting = (runs.data?.items ?? []).filter(mine).length;
|
| 43 |
const name = brand.data?.product_name ?? 'Patchwise';
|
| 44 |
-
const items: NavItem[] = [...MAIN, ...LIBRARY, ...SETUP, ...(can('admin') ? [AGENT_STUDIO, INTEGRATIONS, SETTINGS] : [])];
|
| 45 |
return (
|
| 46 |
<div className="pw-rail">
|
| 47 |
<RouterLink to="/" className="pw-rail-brand" aria-label={`${name} home`} data-testid="brand">
|
|
|
|
| 5 |
import { useBrand, useHealth, useKill, useRuns } from '../../api/hooks';
|
| 6 |
import { useAuth } from '../../auth/AuthContext';
|
| 7 |
import { useWaitsOnMe } from '../../waiting';
|
| 8 |
+
import { AccountMenu, AGENT_STUDIO, AI_MONITORING, INTEGRATIONS, LIBRARY, MAIN, SETTINGS, SETUP, type NavItem } from './AppSidebar';
|
| 9 |
import { envKind, useChosenEnv } from './EnvSwitcher';
|
| 10 |
|
| 11 |
/** The name under each icon: short, and always part of the page's full name (so what is read out matches what is shown). */
|
|
|
|
| 41 |
const env = useChosenEnv().pod;
|
| 42 |
const waiting = (runs.data?.items ?? []).filter(mine).length;
|
| 43 |
const name = brand.data?.product_name ?? 'Patchwise';
|
| 44 |
+
const items: NavItem[] = [...MAIN, ...LIBRARY, ...SETUP, ...(can('admin') ? [AGENT_STUDIO, AI_MONITORING, INTEGRATIONS, SETTINGS] : [])];
|
| 45 |
return (
|
| 46 |
<div className="pw-rail">
|
| 47 |
<RouterLink to="/" className="pw-rail-brand" aria-label={`${name} home`} data-testid="brand">
|
web/src/components/shell/TopNav.tsx
CHANGED
|
@@ -6,7 +6,7 @@ import { useBrand, useKill, useRuns } from '../../api/hooks';
|
|
| 6 |
import { useAuth } from '../../auth/AuthContext';
|
| 7 |
import { NotificationBell } from '../../notify/NotificationBell';
|
| 8 |
import { useWaitsOnMe } from '../../waiting';
|
| 9 |
-
import { AccountMenu, AGENT_STUDIO, INTEGRATIONS, LIBRARY, MAIN, SETTINGS, SETUP, type NavItem } from './AppSidebar';
|
| 10 |
import { EnvSwitcher } from './EnvSwitcher';
|
| 11 |
import { useShell } from './prefs';
|
| 12 |
import { isMac } from './TopBar';
|
|
@@ -31,7 +31,7 @@ export function TopNav() {
|
|
| 31 |
const waiting = (runs.data?.items ?? []).filter(mine).length;
|
| 32 |
const name = brand.data?.product_name ?? 'Patchwise';
|
| 33 |
const main = [...MAIN.filter((i) => i.to !== '/assistant'), ...LIBRARY, ...MAIN.filter((i) => i.to === '/assistant')];
|
| 34 |
-
const more = [...SETUP, ...(can('admin') ? [AGENT_STUDIO, INTEGRATIONS, SETTINGS] : [])];
|
| 35 |
const moreActive = more.find((i) => isActive(i, loc.pathname));
|
| 36 |
return (
|
| 37 |
<header className="pw-nav" aria-label="Main navigation">
|
|
|
|
| 6 |
import { useAuth } from '../../auth/AuthContext';
|
| 7 |
import { NotificationBell } from '../../notify/NotificationBell';
|
| 8 |
import { useWaitsOnMe } from '../../waiting';
|
| 9 |
+
import { AccountMenu, AGENT_STUDIO, AI_MONITORING, INTEGRATIONS, LIBRARY, MAIN, SETTINGS, SETUP, type NavItem } from './AppSidebar';
|
| 10 |
import { EnvSwitcher } from './EnvSwitcher';
|
| 11 |
import { useShell } from './prefs';
|
| 12 |
import { isMac } from './TopBar';
|
|
|
|
| 31 |
const waiting = (runs.data?.items ?? []).filter(mine).length;
|
| 32 |
const name = brand.data?.product_name ?? 'Patchwise';
|
| 33 |
const main = [...MAIN.filter((i) => i.to !== '/assistant'), ...LIBRARY, ...MAIN.filter((i) => i.to === '/assistant')];
|
| 34 |
+
const more = [...SETUP, ...(can('admin') ? [AGENT_STUDIO, AI_MONITORING, INTEGRATIONS, SETTINGS] : [])];
|
| 35 |
const moreActive = more.find((i) => isActive(i, loc.pathname));
|
| 36 |
return (
|
| 37 |
<header className="pw-nav" aria-label="Main navigation">
|
web/src/pages/AgentStudioPage.tsx
CHANGED
|
@@ -7,10 +7,11 @@ import { getJson, sendJson } from '../api/client';
|
|
| 7 |
import { ErrorAlert, fmtTs, PageHeader } from '../components/common';
|
| 8 |
import './agent-studio.css';
|
| 9 |
|
| 10 |
-
interface
|
|
|
|
| 11 |
interface Created extends Client { client_secret: string; signing_key: string }
|
| 12 |
interface Cycle { cycle_id: string; run_id: string; areas: string[]; status: string | null; waiting_for: string | null; data_approved_by: string; scripts_approved_by: string | null; created_at: string; correlation_id: string | null }
|
| 13 |
-
interface Delivery { id: number; delivery_id: string; event: string; cycle_id: string | null; attempts: number; status_code: number | null; error: string | null; created_at: string; delivered_at: string | null }
|
| 14 |
interface Watch { checked_at?: string; checked?: { release: string; area: string; changes?: number; new?: number; error?: string }[]; updates?: number }
|
| 15 |
interface InboxItem { id: number; event: string; signature_ok: boolean; received_at: string; payload: Record<string, unknown> & { cycle_id?: string; scenarios?: { id: string; title: string; area: string; written_by: string }[]; verdict?: string; areas?: { area: string; verdict: string }[] } }
|
| 16 |
|
|
@@ -25,7 +26,7 @@ const FLOW: { n: number; text: string; who: 'fusion' | 'patchwise' | 'person' }[
|
|
| 25 |
{ n: 7, text: 'Patchwise tests and reports; Fusion emails the results', who: 'patchwise' },
|
| 26 |
];
|
| 27 |
|
| 28 |
-
const deliveryState = (d: Delivery) => (d.delivered_at ? { tone: 'green', words: `Delivered${d.attempts > 1 ? ` after ${d.attempts} tries` : ''}` }
|
| 29 |
: d.attempts >= 6 ? { tone: 'red', words: `Failed: ${d.error ?? ''}` } : d.attempts ? { tone: 'orange', words: `Retrying (${d.error ?? 'no answer'})` } : { tone: 'neutral', words: 'Queued' });
|
| 30 |
|
| 31 |
function Secret({ label, value }: { label: string; value: string }) {
|
|
@@ -46,6 +47,7 @@ function Clients() {
|
|
| 46 |
const [open, setOpen] = useState(false);
|
| 47 |
const [form, setForm] = useState({ name: '', callback_url: '', release_watch_url: '' });
|
| 48 |
const [made, setMade] = useState<Created | null>(null);
|
|
|
|
| 49 |
const create = useMutation({
|
| 50 |
mutationFn: () => sendJson<Created>('POST', '/api/agent-studio/clients', { name: form.name, callback_url: form.callback_url || null, release_watch_url: form.release_watch_url || null }),
|
| 51 |
onSuccess: (c) => { setMade(c); setOpen(false); void qc.invalidateQueries({ queryKey: ['as-clients'] }); },
|
|
@@ -66,9 +68,14 @@ function Clients() {
|
|
| 66 |
<Table.Tbody>{items.map((c) => (
|
| 67 |
<Table.Tr key={c.client_id}>
|
| 68 |
<Table.Td><b>{c.name}</b><div className="as-mono">{c.client_id}</div></Table.Td>
|
| 69 |
-
<Table.Td>
|
|
|
|
|
|
|
| 70 |
<Table.Td>{c.last_used_at ? fmtTs(c.last_used_at) : 'Never'}</Table.Td>
|
| 71 |
-
<Table.Td ta="right"><
|
|
|
|
|
|
|
|
|
|
| 72 |
</Table.Tr>
|
| 73 |
))}</Table.Tbody>
|
| 74 |
</Table>
|
|
@@ -82,6 +89,7 @@ function Clients() {
|
|
| 82 |
<Group justify="flex-end"><Button variant="default" onClick={() => setOpen(false)}>Cancel</Button><Button onClick={() => create.mutate()} loading={create.isPending} disabled={!form.name.trim()}>Create client</Button></Group>
|
| 83 |
</Stack>
|
| 84 |
</Modal>
|
|
|
|
| 85 |
<Modal opened={!!made} onClose={() => setMade(null)} title="Client created: copy these now" centered size="lg">
|
| 86 |
{made && (
|
| 87 |
<Stack>
|
|
@@ -97,6 +105,55 @@ function Clients() {
|
|
| 97 |
);
|
| 98 |
}
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
function Cycles() {
|
| 101 |
const q = useQuery({ queryKey: ['as-cycles'], queryFn: () => getJson<{ items: Cycle[] }>('/api/agent-studio/cycles'), refetchInterval: 10_000 });
|
| 102 |
const items = q.data?.items ?? [];
|
|
|
|
| 7 |
import { ErrorAlert, fmtTs, PageHeader } from '../components/common';
|
| 8 |
import './agent-studio.css';
|
| 9 |
|
| 10 |
+
interface FusionDelivery { base_url: string; token_url: string; client_id: string; scope: string; workflow_code: string; invocation_mode: string; workflow_status: string; has_secret: boolean }
|
| 11 |
+
interface Client { client_id: string; name: string; callback_url: string | null; release_watch_url: string | null; created_at: string; last_used_at: string | null; revoked_at: string | null; delivery?: 'url' | 'fusion'; fusion?: FusionDelivery | null }
|
| 12 |
interface Created extends Client { client_secret: string; signing_key: string }
|
| 13 |
interface Cycle { cycle_id: string; run_id: string; areas: string[]; status: string | null; waiting_for: string | null; data_approved_by: string; scripts_approved_by: string | null; created_at: string; correlation_id: string | null }
|
| 14 |
+
interface Delivery { id: number; delivery_id: string; event: string; cycle_id: string | null; attempts: number; status_code: number | null; error: string | null; created_at: string; delivered_at: string | null; job_id?: string | null }
|
| 15 |
interface Watch { checked_at?: string; checked?: { release: string; area: string; changes?: number; new?: number; error?: string }[]; updates?: number }
|
| 16 |
interface InboxItem { id: number; event: string; signature_ok: boolean; received_at: string; payload: Record<string, unknown> & { cycle_id?: string; scenarios?: { id: string; title: string; area: string; written_by: string }[]; verdict?: string; areas?: { area: string; verdict: string }[] } }
|
| 17 |
|
|
|
|
| 26 |
{ n: 7, text: 'Patchwise tests and reports; Fusion emails the results', who: 'patchwise' },
|
| 27 |
];
|
| 28 |
|
| 29 |
+
const deliveryState = (d: Delivery) => (d.delivered_at ? { tone: 'green', words: `Delivered${d.attempts > 1 ? ` after ${d.attempts} tries` : ''}${d.job_id ? ` (Fusion job ${d.job_id})` : ''}` }
|
| 30 |
: d.attempts >= 6 ? { tone: 'red', words: `Failed: ${d.error ?? ''}` } : d.attempts ? { tone: 'orange', words: `Retrying (${d.error ?? 'no answer'})` } : { tone: 'neutral', words: 'Queued' });
|
| 31 |
|
| 32 |
function Secret({ label, value }: { label: string; value: string }) {
|
|
|
|
| 47 |
const [open, setOpen] = useState(false);
|
| 48 |
const [form, setForm] = useState({ name: '', callback_url: '', release_watch_url: '' });
|
| 49 |
const [made, setMade] = useState<Created | null>(null);
|
| 50 |
+
const [editing, setEditing] = useState<Client | null>(null);
|
| 51 |
const create = useMutation({
|
| 52 |
mutationFn: () => sendJson<Created>('POST', '/api/agent-studio/clients', { name: form.name, callback_url: form.callback_url || null, release_watch_url: form.release_watch_url || null }),
|
| 53 |
onSuccess: (c) => { setMade(c); setOpen(false); void qc.invalidateQueries({ queryKey: ['as-clients'] }); },
|
|
|
|
| 68 |
<Table.Tbody>{items.map((c) => (
|
| 69 |
<Table.Tr key={c.client_id}>
|
| 70 |
<Table.Td><b>{c.name}</b><div className="as-mono">{c.client_id}</div></Table.Td>
|
| 71 |
+
<Table.Td>{c.delivery === 'fusion' && c.fusion
|
| 72 |
+
? <><Badge size="sm" variant="light" mb={4}>Oracle Fusion directly</Badge><div className="as-url">{c.fusion.workflow_code} on {c.fusion.base_url}</div></>
|
| 73 |
+
: <><div className="as-url">{c.callback_url ?? 'Not set'}</div>{c.release_watch_url && <div className="as-url as-dim">Release watch: {c.release_watch_url}</div>}</>}</Table.Td>
|
| 74 |
<Table.Td>{c.last_used_at ? fmtTs(c.last_used_at) : 'Never'}</Table.Td>
|
| 75 |
+
<Table.Td ta="right"><Group gap={6} justify="flex-end" wrap="nowrap">
|
| 76 |
+
<Button size="xs" variant="default" onClick={() => setEditing(c)}>Delivery</Button>
|
| 77 |
+
<Button size="xs" variant="default" color="red" onClick={() => revoke.mutate(c.client_id)}>Revoke</Button>
|
| 78 |
+
</Group></Table.Td>
|
| 79 |
</Table.Tr>
|
| 80 |
))}</Table.Tbody>
|
| 81 |
</Table>
|
|
|
|
| 89 |
<Group justify="flex-end"><Button variant="default" onClick={() => setOpen(false)}>Cancel</Button><Button onClick={() => create.mutate()} loading={create.isPending} disabled={!form.name.trim()}>Create client</Button></Group>
|
| 90 |
</Stack>
|
| 91 |
</Modal>
|
| 92 |
+
{editing && <DeliverySheet c={editing} onClose={() => setEditing(null)} />}
|
| 93 |
<Modal opened={!!made} onClose={() => setMade(null)} title="Client created: copy these now" centered size="lg">
|
| 94 |
{made && (
|
| 95 |
<Stack>
|
|
|
|
| 105 |
);
|
| 106 |
}
|
| 107 |
|
| 108 |
+
/** Where a client's events go: signed POSTs to its callback address (a relay), or straight to Oracle Fusion, where
|
| 109 |
+
* Patchwise signs in to the identity domain and starts the callback workflow (invokeAsync). The secret is write-only. */
|
| 110 |
+
function DeliverySheet({ c, onClose }: { c: Client; onClose: () => void }) {
|
| 111 |
+
const qc = useQueryClient();
|
| 112 |
+
const f = c.fusion;
|
| 113 |
+
const [mode, setMode] = useState<'url' | 'fusion'>(c.delivery === 'fusion' ? 'fusion' : 'url');
|
| 114 |
+
const [form, setForm] = useState({ base_url: f?.base_url ?? '', token_url: f?.token_url ?? '', client_id: f?.client_id ?? '', client_secret: '',
|
| 115 |
+
scope: f?.scope ?? '', workflow_code: f?.workflow_code ?? 'PATCH_TEST_CALLBACK_V3_7' });
|
| 116 |
+
const set = (k: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) => setForm({ ...form, [k]: e.currentTarget.value });
|
| 117 |
+
const save = useMutation({
|
| 118 |
+
mutationFn: () => sendJson<Client>('PUT', `/api/agent-studio/clients/${c.client_id}/delivery`,
|
| 119 |
+
mode === 'url' ? { mode } : { mode, fusion: { ...form, client_secret: form.client_secret || null, scope: form.scope || null } }),
|
| 120 |
+
onSuccess: () => void qc.invalidateQueries({ queryKey: ['as-clients'] }),
|
| 121 |
+
});
|
| 122 |
+
const test = useMutation({ mutationFn: () => sendJson<{ ok: boolean; detail: string }>('POST', `/api/agent-studio/clients/${c.client_id}/delivery/test`) });
|
| 123 |
+
return (
|
| 124 |
+
<Modal opened onClose={onClose} title={`Where ${c.name} gets its events`} centered size="lg">
|
| 125 |
+
<Stack>
|
| 126 |
+
<div className="as-view" role="group" aria-label="Delivery">
|
| 127 |
+
<Button variant={mode === 'url' ? 'filled' : 'default'} size="xs" onClick={() => setMode('url')} aria-pressed={mode === 'url'}>Callback address (relay)</Button>
|
| 128 |
+
<Button variant={mode === 'fusion' ? 'filled' : 'default'} size="xs" onClick={() => setMode('fusion')} aria-pressed={mode === 'fusion'}>Oracle Fusion directly</Button>
|
| 129 |
+
</div>
|
| 130 |
+
{mode === 'url' ? (
|
| 131 |
+
<Text size="sm" c="dimmed">Signed POSTs go to the client’s callback address{c.callback_url ? <> (<code>{c.callback_url}</code>)</> : ' (not set)'}, for example the PATCH_TEST_RELAY.</Text>
|
| 132 |
+
) : (
|
| 133 |
+
<>
|
| 134 |
+
<Text size="sm" c="dimmed">Patchwise signs in to your Oracle identity domain with a confidential app (client credentials) and starts the callback workflow with <code>invokeAsync</code>. No relay is needed.</Text>
|
| 135 |
+
<TextInput label="Fusion address" placeholder="https://<pod host>" required value={form.base_url} onChange={set('base_url')} />
|
| 136 |
+
<TextInput label="Token address (OCI IAM)" placeholder="https://idcs-….identity.oraclecloud.com/oauth2/v1/token" required value={form.token_url} onChange={set('token_url')} />
|
| 137 |
+
<Group grow>
|
| 138 |
+
<TextInput label="Client ID" required value={form.client_id} onChange={set('client_id')} />
|
| 139 |
+
<TextInput label="Client secret" type="password" autoComplete="new-password" placeholder={f?.has_secret ? 'Saved (leave empty to keep)' : ''} value={form.client_secret} onChange={set('client_secret')} />
|
| 140 |
+
</Group>
|
| 141 |
+
<TextInput label="Scope" description="Only if your identity domain asks for one." value={form.scope} onChange={set('scope')} />
|
| 142 |
+
<TextInput label="Callback workflow" value={form.workflow_code} onChange={set('workflow_code')} />
|
| 143 |
+
</>
|
| 144 |
+
)}
|
| 145 |
+
<ErrorAlert error={save.error || test.error} />
|
| 146 |
+
{test.data && <Text size="sm" c={test.data.ok ? 'teal' : 'red'} role="status">{test.data.detail}</Text>}
|
| 147 |
+
<Group justify="space-between">
|
| 148 |
+
{mode === 'fusion' && c.delivery === 'fusion' ? <Button variant="default" onClick={() => test.mutate()} loading={test.isPending}>Test sign-in</Button> : <span />}
|
| 149 |
+
<Group gap={8}><Button variant="default" onClick={onClose}>Close</Button><Button onClick={() => save.mutate()} loading={save.isPending}>Save</Button></Group>
|
| 150 |
+
</Group>
|
| 151 |
+
{save.isSuccess && <Text size="sm" c="teal" role="status">Saved.</Text>}
|
| 152 |
+
</Stack>
|
| 153 |
+
</Modal>
|
| 154 |
+
);
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
function Cycles() {
|
| 158 |
const q = useQuery({ queryKey: ['as-cycles'], queryFn: () => getJson<{ items: Cycle[] }>('/api/agent-studio/cycles'), refetchInterval: 10_000 });
|
| 159 |
const items = q.data?.items ?? [];
|
web/src/pages/AiMonitoringPage.tsx
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Badge, Button, Checkbox, Group, Modal, PasswordInput, SegmentedControl, Switch, Table, Text, TextInput } from '@mantine/core';
|
| 2 |
+
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
| 3 |
+
import { useState } from 'react';
|
| 4 |
+
import { Link } from 'react-router-dom';
|
| 5 |
+
import { getJson, sendJson } from '../api/client';
|
| 6 |
+
import { ErrorAlert, fmtTs, PageHeader } from '../components/common';
|
| 7 |
+
import './ai-monitoring.css';
|
| 8 |
+
|
| 9 |
+
interface Group_ { routes?: Record<string, number>; calls: number; failed: number; baseline: number; fallbacks: number; validation_failures: number; p50_ms: number | null; p95_ms: number | null; tokens_in: number; tokens_out: number; success_rate: number | null }
|
| 10 |
+
interface Summary { days: number; totals: Group_; by_task: Record<string, Group_>; by_model: Record<string, Group_>; by_day: { day: string; calls: number; failed: number; p95_ms: number | null }[];
|
| 11 |
+
problems: { ts: string; task: string; node: string | null; run_id: string | null; route: string | null; model: string | null; error: string | null; baseline: boolean }[] }
|
| 12 |
+
interface LangSmithView { enabled: boolean; project: string; endpoint: string; send_content: boolean; has_key: boolean; queued: number; sent: number; dropped: number; last_ok_at: string | null; last_error: string | null }
|
| 13 |
+
interface Dataset { task: string; about: string; cases: number; sensitivity: string; external_allowed: boolean }
|
| 14 |
+
interface EvalTask { cases: number; scored: number; passed: number; skipped: number; score: number | null; p50_ms: number | null; tokens: number }
|
| 15 |
+
interface EvalRow { eval_id: string; target: string; model: string | null; tasks: string[]; actor: string | null; status: string; started_at: string; finished_at: string | null; error: string | null;
|
| 16 |
+
summary: { score: number | null; cases: number; scored: number; passed: number; by_task: Record<string, EvalTask> } | null }
|
| 17 |
+
interface EvalCase { task: string; case: string; ok: boolean; skipped?: boolean; error: string | null; latency_ms?: number; checks: { name: string; ok: boolean; got?: unknown }[]; output: Record<string, unknown> | null }
|
| 18 |
+
|
| 19 |
+
const TASK_WORDS: Record<string, string> = { triage: 'Failure triage', self_heal: 'Self-heal', chat_intent: 'Assistant: pick a tool', chat_answer: 'Assistant: answer', summary: 'Report summary',
|
| 20 |
+
generate_tests: 'Write scenarios', write_steps: 'Write steps', web_research: 'Patch research', synthesize: 'Coverage', plan_data: 'Test data plan', build_script: 'Build script', pod_probe: 'Pod probe' };
|
| 21 |
+
const pct = (v: number | null | undefined) => (v == null ? '–' : `${Math.round(v * 100)}%`);
|
| 22 |
+
const ms = (v: number | null | undefined) => (v == null ? '–' : v >= 1000 ? `${(v / 1000).toFixed(1)} s` : `${v} ms`);
|
| 23 |
+
const num = (v: number) => v.toLocaleString();
|
| 24 |
+
const tone = (v: number | null | undefined) => (v == null ? undefined : v >= 0.9 ? 'green' : v >= 0.7 ? 'orange' : 'red');
|
| 25 |
+
|
| 26 |
+
/** Calls per day, answered by a model vs failed or stood in for by the baseline. Hover a day for its numbers. */
|
| 27 |
+
function DayBars({ days }: { days: Summary['by_day'] }) {
|
| 28 |
+
const max = Math.max(1, ...days.map((d) => d.calls));
|
| 29 |
+
return (
|
| 30 |
+
<figure className="aim-chart" aria-label="Model calls per day">
|
| 31 |
+
<div className="aim-legend"><span><i data-k="ok" />Answered as planned</span><span><i data-k="bad" />Failed or baseline used</span></div>
|
| 32 |
+
<div className="aim-bars" role="list">
|
| 33 |
+
{days.map((d) => {
|
| 34 |
+
const ok = d.calls - d.failed;
|
| 35 |
+
return (
|
| 36 |
+
<div key={d.day} className="aim-day" role="listitem" tabIndex={0}
|
| 37 |
+
aria-label={`${d.day}: ${d.calls} calls, ${d.failed} failed or baseline${d.p95_ms != null ? `, p95 ${ms(d.p95_ms)}` : ''}`}>
|
| 38 |
+
<span className="aim-tip" aria-hidden><b>{d.day}</b><br />{d.calls} calls · {d.failed} failed<br />p95 {ms(d.p95_ms)}</span>
|
| 39 |
+
<span className="aim-col" style={{ height: `${(d.calls / max) * 100}%` }} aria-hidden>
|
| 40 |
+
{d.failed > 0 && <i data-k="bad" style={{ flexGrow: d.failed }} />}
|
| 41 |
+
{ok > 0 && <i data-k="ok" style={{ flexGrow: ok }} />}
|
| 42 |
+
</span>
|
| 43 |
+
<span className="aim-x" aria-hidden>{d.day.slice(5)}</span>
|
| 44 |
+
</div>
|
| 45 |
+
);
|
| 46 |
+
})}
|
| 47 |
+
</div>
|
| 48 |
+
</figure>
|
| 49 |
+
);
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
function GroupTable({ rows, label, first }: { rows: Record<string, Group_>; label: string; first: string }) {
|
| 53 |
+
const keys = Object.keys(rows).sort((a, b) => rows[b].calls - rows[a].calls);
|
| 54 |
+
if (!keys.length) return <Text size="sm" c="dimmed">No model calls in this period.</Text>;
|
| 55 |
+
return (
|
| 56 |
+
<div className="aim-scroll">
|
| 57 |
+
<Table className="pw-table" aria-label={label}>
|
| 58 |
+
<Table.Thead><Table.Tr><Table.Th>{first}</Table.Th><Table.Th>Calls</Table.Th><Table.Th>As planned</Table.Th><Table.Th>Fell back</Table.Th><Table.Th>Rule checks failed</Table.Th><Table.Th>p50</Table.Th><Table.Th>p95</Table.Th><Table.Th>Tokens in / out</Table.Th></Table.Tr></Table.Thead>
|
| 59 |
+
<Table.Tbody>{keys.map((k) => {
|
| 60 |
+
const g = rows[k];
|
| 61 |
+
return (
|
| 62 |
+
<Table.Tr key={k}>
|
| 63 |
+
<Table.Td><b>{TASK_WORDS[k] ?? k}</b>{TASK_WORDS[k] && <div className="aim-code">{k}</div>}</Table.Td>
|
| 64 |
+
<Table.Td className="fpt-num">{num(g.calls)}</Table.Td>
|
| 65 |
+
<Table.Td><span className="aim-pill" data-tone={tone(g.success_rate)}>{pct(g.success_rate)}</span></Table.Td>
|
| 66 |
+
<Table.Td className="fpt-num">{g.fallbacks}</Table.Td>
|
| 67 |
+
<Table.Td className="fpt-num">{g.validation_failures}</Table.Td>
|
| 68 |
+
<Table.Td className="fpt-num">{ms(g.p50_ms)}</Table.Td>
|
| 69 |
+
<Table.Td className="fpt-num">{ms(g.p95_ms)}</Table.Td>
|
| 70 |
+
<Table.Td className="fpt-num">{num(g.tokens_in)} / {num(g.tokens_out)}</Table.Td>
|
| 71 |
+
</Table.Tr>
|
| 72 |
+
);
|
| 73 |
+
})}</Table.Tbody>
|
| 74 |
+
</Table>
|
| 75 |
+
</div>
|
| 76 |
+
);
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
function Monitoring() {
|
| 80 |
+
const [days, setDays] = useState('7');
|
| 81 |
+
const q = useQuery({ queryKey: ['ai-mon', days], queryFn: () => getJson<Summary>(`/api/ai/monitoring?days=${days}`), refetchInterval: 30_000 });
|
| 82 |
+
const s = q.data;
|
| 83 |
+
const t = s?.totals;
|
| 84 |
+
return (
|
| 85 |
+
<section className="pw-card aim-card" aria-labelledby="aim-mon-h">
|
| 86 |
+
<div className="aim-head">
|
| 87 |
+
<div><h2 id="aim-mon-h">How the models behave</h2><p>Every model call in runs and the assistant: what answered, how fast, and when the deterministic baseline had to stand in. Prompts and answers are not stored here.</p></div>
|
| 88 |
+
<SegmentedControl size="xs" value={days} onChange={setDays} data={[{ value: '1', label: '24 h' }, { value: '7', label: '7 days' }, { value: '30', label: '30 days' }]} aria-label="Period" />
|
| 89 |
+
</div>
|
| 90 |
+
<ErrorAlert error={q.error} />
|
| 91 |
+
{t && (
|
| 92 |
+
<div className="aim-kpis">
|
| 93 |
+
<div className="aim-kpi"><span>Model calls</span><b className="fpt-num">{num(t.calls)}</b></div>
|
| 94 |
+
<div className="aim-kpi"><span>Answered as planned</span><b data-tone={tone(t.success_rate)}>{pct(t.success_rate)}</b>
|
| 95 |
+
<small>{t.routes?.frontier ?? 0} external model · {t.routes?.local ?? 0} local model · {t.routes?.stub ?? 0} built-in rules{t.baseline ? ` · ${t.baseline} baseline` : ''}{t.failed ? ` · ${t.failed} failed` : ''}</small></div>
|
| 96 |
+
<div className="aim-kpi"><span>Rule checks failed</span><b className="fpt-num">{num(t.validation_failures)}</b><small>answers the app refused (invented numbers, unknown names)</small></div>
|
| 97 |
+
<div className="aim-kpi"><span>Latency p50 / p95</span><b>{ms(t.p50_ms)} <small>/ {ms(t.p95_ms)}</small></b></div>
|
| 98 |
+
<div className="aim-kpi"><span>Tokens in / out</span><b className="fpt-num">{num(t.tokens_in)} <small>/ {num(t.tokens_out)}</small></b></div>
|
| 99 |
+
</div>
|
| 100 |
+
)}
|
| 101 |
+
{s && <DayBars days={s.by_day} />}
|
| 102 |
+
{s && <><h3 className="aim-h3">By task</h3><GroupTable rows={s.by_task} label="Model calls by task" first="Task" /></>}
|
| 103 |
+
{s && <><h3 className="aim-h3">By model</h3><GroupTable rows={s.by_model} label="Model calls by model" first="Route · model" /></>}
|
| 104 |
+
{s && s.problems.length > 0 && (
|
| 105 |
+
<>
|
| 106 |
+
<h3 className="aim-h3">Latest problems</h3>
|
| 107 |
+
<ul className="aim-problems">
|
| 108 |
+
{s.problems.slice(0, 12).map((p, i) => (
|
| 109 |
+
<li key={i}><span className="aim-pill" data-tone={p.baseline ? 'orange' : 'red'}>{p.baseline ? 'Baseline used' : 'Failed'}</span>
|
| 110 |
+
<b>{TASK_WORDS[p.task] ?? p.task}</b> <span className="aim-dim">{fmtTs(p.ts)}{p.model ? ` · ${p.model}` : ''}</span>
|
| 111 |
+
{p.run_id && <Link to={`/runs/${p.run_id}`} className="aim-run">run</Link>}
|
| 112 |
+
{p.error && <div className="aim-err">{p.error}</div>}</li>
|
| 113 |
+
))}
|
| 114 |
+
</ul>
|
| 115 |
+
</>
|
| 116 |
+
)}
|
| 117 |
+
</section>
|
| 118 |
+
);
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
function EvalDetail({ id, onClose }: { id: string; onClose: () => void }) {
|
| 122 |
+
const q = useQuery({ queryKey: ['ai-eval', id], queryFn: () => getJson<EvalRow & { results: EvalCase[] }>(`/api/ai/evals/${id}`) });
|
| 123 |
+
const e = q.data;
|
| 124 |
+
const bad = (e?.results ?? []).filter((r) => !r.ok && !r.skipped);
|
| 125 |
+
return (
|
| 126 |
+
<Modal opened onClose={onClose} title={`Evaluation ${id}`} size="xl" centered>
|
| 127 |
+
<ErrorAlert error={q.error} />
|
| 128 |
+
{e && (
|
| 129 |
+
<>
|
| 130 |
+
<Text size="sm" mb="sm">{e.target} · {e.model ?? ''} · score <b>{pct(e.summary?.score)}</b> ({e.summary?.passed} of {e.summary?.scored} cases)</Text>
|
| 131 |
+
<div className="aim-scroll"><Table className="pw-table" mb="md">
|
| 132 |
+
<Table.Thead><Table.Tr><Table.Th>Task</Table.Th><Table.Th>Score</Table.Th><Table.Th>Passed</Table.Th><Table.Th>Skipped</Table.Th><Table.Th>p50</Table.Th><Table.Th>Tokens</Table.Th></Table.Tr></Table.Thead>
|
| 133 |
+
<Table.Tbody>{Object.entries(e.summary?.by_task ?? {}).map(([k, v]) => (
|
| 134 |
+
<Table.Tr key={k}><Table.Td>{TASK_WORDS[k] ?? k}</Table.Td><Table.Td><span className="aim-pill" data-tone={tone(v.score)}>{pct(v.score)}</span></Table.Td>
|
| 135 |
+
<Table.Td>{v.passed} / {v.scored}</Table.Td><Table.Td>{v.skipped ? `${v.skipped} (local-only)` : '–'}</Table.Td><Table.Td>{ms(v.p50_ms)}</Table.Td><Table.Td>{num(v.tokens)}</Table.Td></Table.Tr>
|
| 136 |
+
))}</Table.Tbody>
|
| 137 |
+
</Table></div>
|
| 138 |
+
<h3 className="aim-h3">Cases that did not pass ({bad.length})</h3>
|
| 139 |
+
{bad.length === 0 && <Text size="sm" c="dimmed">Every scored case passed.</Text>}
|
| 140 |
+
<ul className="aim-cases">
|
| 141 |
+
{bad.map((r) => (
|
| 142 |
+
<li key={`${r.task}-${r.case}`}><b>{r.case}</b> <span className="aim-dim">{TASK_WORDS[r.task] ?? r.task}</span>
|
| 143 |
+
<ul>{r.checks.filter((c) => !c.ok).map((c) => <li key={c.name}>{c.name}: <span className="aim-err">{String(c.got ?? 'no')}</span></li>)}</ul>
|
| 144 |
+
</li>
|
| 145 |
+
))}
|
| 146 |
+
</ul>
|
| 147 |
+
</>
|
| 148 |
+
)}
|
| 149 |
+
</Modal>
|
| 150 |
+
);
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
function Evals() {
|
| 154 |
+
const qc = useQueryClient();
|
| 155 |
+
const ds = useQuery({ queryKey: ['ai-ds'], queryFn: () => getJson<{ items: Dataset[] }>('/api/ai/evals/datasets') });
|
| 156 |
+
const hist = useQuery({ queryKey: ['ai-evals'], queryFn: () => getJson<{ items: EvalRow[] }>('/api/ai/evals'),
|
| 157 |
+
refetchInterval: (q) => ((q.state.data?.items ?? []).some((e) => e.status === 'running') ? 2000 : false) });
|
| 158 |
+
const [target, setTarget] = useState('local');
|
| 159 |
+
const [picked, setPicked] = useState<string[]>([]);
|
| 160 |
+
const [open, setOpen] = useState<string | null>(null);
|
| 161 |
+
const run = useMutation({ mutationFn: () => sendJson<EvalRow>('POST', '/api/ai/evals', { target, tasks: picked.length ? picked : null }),
|
| 162 |
+
onSuccess: () => void qc.invalidateQueries({ queryKey: ['ai-evals'] }) });
|
| 163 |
+
const items = hist.data?.items ?? [];
|
| 164 |
+
return (
|
| 165 |
+
<section className="pw-card aim-card" aria-labelledby="aim-ev-h">
|
| 166 |
+
<div className="aim-head">
|
| 167 |
+
<div><h2 id="aim-ev-h">Evaluations</h2><p>Score a model on fixed, synthetic cases from real Patchwise work: classify a failure, pick a renamed screen element, choose the assistant’s tool, summarise without inventing numbers. The external model only gets the tasks that may go to it.</p></div>
|
| 168 |
+
</div>
|
| 169 |
+
<div className="aim-ds">
|
| 170 |
+
{(ds.data?.items ?? []).map((d) => (
|
| 171 |
+
<Checkbox key={d.task} checked={picked.includes(d.task)} onChange={(e) => setPicked(e.currentTarget.checked ? [...picked, d.task] : picked.filter((x) => x !== d.task))}
|
| 172 |
+
label={<span><b>{TASK_WORDS[d.task] ?? d.task}</b> <span className="aim-dim">{d.cases} cases{d.external_allowed ? '' : ' · local only'}</span></span>} description={d.about} />
|
| 173 |
+
))}
|
| 174 |
+
</div>
|
| 175 |
+
<Group gap="sm" wrap="wrap">
|
| 176 |
+
<SegmentedControl value={target} onChange={setTarget} aria-label="Model to evaluate"
|
| 177 |
+
data={[{ value: 'local', label: 'Local model' }, { value: 'external', label: 'External model' }, { value: 'stub', label: 'Baseline (no model)' }]} />
|
| 178 |
+
<Button onClick={() => run.mutate()} loading={run.isPending} disabled={items.some((e) => e.status === 'running')}>Run evaluation{picked.length ? ` (${picked.length} tasks)` : ' (all tasks)'}</Button>
|
| 179 |
+
</Group>
|
| 180 |
+
<ErrorAlert error={run.error || hist.error} />
|
| 181 |
+
{items.length > 0 && (
|
| 182 |
+
<div className="aim-scroll"><Table className="pw-table" aria-label="Evaluations">
|
| 183 |
+
<Table.Thead><Table.Tr><Table.Th>Started</Table.Th><Table.Th>Model</Table.Th><Table.Th>Score</Table.Th><Table.Th>Cases</Table.Th><Table.Th>By</Table.Th><Table.Th /></Table.Tr></Table.Thead>
|
| 184 |
+
<Table.Tbody>{items.map((e) => (
|
| 185 |
+
<Table.Tr key={e.eval_id}>
|
| 186 |
+
<Table.Td>{fmtTs(e.started_at)}</Table.Td>
|
| 187 |
+
<Table.Td><b>{e.target === 'stub' ? 'Baseline' : e.target === 'local' ? 'Local' : 'External'}</b><div className="aim-code">{e.model}</div></Table.Td>
|
| 188 |
+
<Table.Td>{e.status === 'running' ? <Badge variant="light">Running…</Badge> : e.status === 'failed' ? <Badge color="red" variant="light" title={e.error ?? ''}>Failed</Badge>
|
| 189 |
+
: <span className="aim-pill" data-tone={tone(e.summary?.score)}>{pct(e.summary?.score)}</span>}</Table.Td>
|
| 190 |
+
<Table.Td className="fpt-num">{e.summary ? `${e.summary.passed} / ${e.summary.scored}` : '–'}</Table.Td>
|
| 191 |
+
<Table.Td>{e.actor}</Table.Td>
|
| 192 |
+
<Table.Td ta="right">{e.status === 'done' && <Button size="xs" variant="default" onClick={() => setOpen(e.eval_id)}>Details</Button>}</Table.Td>
|
| 193 |
+
</Table.Tr>
|
| 194 |
+
))}</Table.Tbody>
|
| 195 |
+
</Table></div>
|
| 196 |
+
)}
|
| 197 |
+
{open && <EvalDetail id={open} onClose={() => setOpen(null)} />}
|
| 198 |
+
</section>
|
| 199 |
+
);
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
function LangSmithCard() {
|
| 203 |
+
const qc = useQueryClient();
|
| 204 |
+
const q = useQuery({ queryKey: ['ai-ls'], queryFn: () => getJson<LangSmithView>('/api/ai/langsmith'), refetchInterval: 15_000 });
|
| 205 |
+
const v = q.data;
|
| 206 |
+
const [key, setKey] = useState('');
|
| 207 |
+
const [project, setProject] = useState<string | null>(null);
|
| 208 |
+
const refresh = () => void qc.invalidateQueries({ queryKey: ['ai-ls'] });
|
| 209 |
+
const save = useMutation({ mutationFn: (b: Partial<LangSmithView>) => sendJson('PUT', '/api/ai/langsmith', b), onSuccess: refresh });
|
| 210 |
+
const setK = useMutation({ mutationFn: () => sendJson('POST', '/api/ai/langsmith/key', { api_key: key }), onSuccess: () => { setKey(''); refresh(); } });
|
| 211 |
+
const test = useMutation({ mutationFn: () => sendJson<{ ok: boolean; detail: string }>('POST', '/api/ai/langsmith/test'), onSuccess: refresh });
|
| 212 |
+
return (
|
| 213 |
+
<section className="pw-card aim-card" aria-labelledby="aim-ls-h">
|
| 214 |
+
<div className="aim-head">
|
| 215 |
+
<div><h2 id="aim-ls-h">LangSmith</h2><p>Optional: send model calls and evaluation scores to LangSmith for traces, dashboards and alerts. Calls on client data go as numbers only (task, model, latency, tokens, outcome), never their content.</p></div>
|
| 216 |
+
{v && <Switch checked={v.enabled} onChange={(e) => save.mutate({ enabled: e.currentTarget.checked })} label={v.enabled ? 'On' : 'Off'} disabled={!v.has_key && !v.enabled} />}
|
| 217 |
+
</div>
|
| 218 |
+
<ErrorAlert error={q.error || save.error || setK.error || test.error} />
|
| 219 |
+
{v && (
|
| 220 |
+
<>
|
| 221 |
+
<div className="aim-ls">
|
| 222 |
+
<TextInput label="Project" value={project ?? v.project} onChange={(e) => setProject(e.currentTarget.value)} onBlur={() => project && project !== v.project && save.mutate({ project })} />
|
| 223 |
+
<PasswordInput label="API key" placeholder={v.has_key ? 'Saved (enter a new one to replace it)' : 'lsv2_…'} value={key} onChange={(e) => setKey(e.currentTarget.value)}
|
| 224 |
+
rightSectionWidth={80} rightSection={<Button size="compact-xs" onClick={() => setK.mutate()} disabled={key.length < 8} loading={setK.isPending}>Save key</Button>} />
|
| 225 |
+
</div>
|
| 226 |
+
<Switch checked={v.send_content} onChange={(e) => save.mutate({ send_content: e.currentTarget.checked })}
|
| 227 |
+
label="Also send prompts and answers of calls on public or redacted data (already cleared for the external model)" />
|
| 228 |
+
<Group gap="sm" wrap="wrap">
|
| 229 |
+
<Button variant="default" onClick={() => test.mutate()} loading={test.isPending} disabled={!v.has_key}>Send a test run</Button>
|
| 230 |
+
<Text size="sm" c="dimmed">{v.sent} sent · {v.queued} queued · {v.dropped} dropped{v.last_ok_at ? ` · last sent ${fmtTs(v.last_ok_at)}` : ''}</Text>
|
| 231 |
+
</Group>
|
| 232 |
+
{test.data && <Text size="sm" c={test.data.ok ? 'teal' : 'red'} role="status">{test.data.detail}</Text>}
|
| 233 |
+
{v.last_error && <Text size="sm" c="red">Last error: {v.last_error}</Text>}
|
| 234 |
+
</>
|
| 235 |
+
)}
|
| 236 |
+
</section>
|
| 237 |
+
);
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
/** Settings > AI monitoring: the models' behaviour, their evaluations, and the optional LangSmith export. Admin only. */
|
| 241 |
+
export function AiMonitoringPage() {
|
| 242 |
+
return (
|
| 243 |
+
<div className="pw-page aim-page">
|
| 244 |
+
<PageHeader crumbs={[{ label: "Settings", to: "/admin" }]} title="AI monitoring" />
|
| 245 |
+
<Monitoring />
|
| 246 |
+
<Evals />
|
| 247 |
+
<LangSmithCard />
|
| 248 |
+
</div>
|
| 249 |
+
);
|
| 250 |
+
}
|
web/src/pages/ai-monitoring.css
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* AI monitoring (AiMonitoringPage.tsx). Tokens only, so dark and light both follow the scheme. */
|
| 2 |
+
.aim-page { display: flex; flex-direction: column; gap: var(--sp-5); }
|
| 3 |
+
.aim-card { display: flex; flex-direction: column; gap: var(--sp-4); padding: var(--sp-5) var(--sp-6); border: 1px solid var(--sep); border-radius: var(--r-lg); background: var(--bg-elev); }
|
| 4 |
+
.aim-head { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: var(--sp-4); }
|
| 5 |
+
.aim-head h2 { margin: 0; font: 600 18px/24px var(--font-display); color: var(--label); }
|
| 6 |
+
.aim-head p { margin: 4px 0 0; max-width: 78ch; color: var(--label-2); font-size: var(--fs-sm); line-height: var(--lh-sm); }
|
| 7 |
+
.aim-h3 { margin: var(--sp-2) 0 0; font: 600 14px var(--font-display); color: var(--label); }
|
| 8 |
+
.aim-dim { color: var(--label-3); font-size: var(--fs-xs); }
|
| 9 |
+
.aim-code { font-family: var(--mono); font-size: 11px; color: var(--label-3); }
|
| 10 |
+
.aim-err { color: var(--red); font-size: var(--fs-xs); word-break: break-word; }
|
| 11 |
+
.aim-scroll { overflow-x: auto; }
|
| 12 |
+
.aim-pill { display: inline-block; padding: 2px 9px; border-radius: 999px; background: var(--fill-2); color: var(--label-2); font: 700 12px/18px var(--font); }
|
| 13 |
+
.aim-pill[data-tone='green'] { background: var(--green-soft); color: var(--green); }
|
| 14 |
+
.aim-pill[data-tone='orange'] { background: var(--orange-soft); color: var(--orange); }
|
| 15 |
+
.aim-pill[data-tone='red'] { background: var(--red-soft); color: var(--red); }
|
| 16 |
+
|
| 17 |
+
.aim-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: var(--sp-3); }
|
| 18 |
+
.aim-kpi { display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; border-radius: 14px; border: 1px solid var(--sep); background: var(--bg); }
|
| 19 |
+
.aim-kpi > span { font-size: 12px; color: var(--label-2); }
|
| 20 |
+
.aim-kpi b { font: 700 24px/30px var(--font-display); color: var(--label); }
|
| 21 |
+
.aim-kpi b small { font-size: 14px; color: var(--label-3); font-weight: 600; }
|
| 22 |
+
.aim-kpi b[data-tone='green'] { color: var(--green); }
|
| 23 |
+
.aim-kpi b[data-tone='orange'] { color: var(--orange); }
|
| 24 |
+
.aim-kpi b[data-tone='red'] { color: var(--red); }
|
| 25 |
+
.aim-kpi > small { font-size: 12px; color: var(--label-3); }
|
| 26 |
+
|
| 27 |
+
/* calls per day: stacked columns, 2px surface gap between segments, rounded data end */
|
| 28 |
+
.aim-chart { margin: 0; display: flex; flex-direction: column; gap: 8px; }
|
| 29 |
+
.aim-legend { display: flex; flex-wrap: wrap; gap: 14px; font-size: 12px; color: var(--label-2); }
|
| 30 |
+
.aim-legend span { display: inline-flex; align-items: center; gap: 6px; }
|
| 31 |
+
.aim-legend i { width: 10px; height: 10px; border-radius: 3px; }
|
| 32 |
+
.aim-legend i[data-k='ok'], .aim-col i[data-k='ok'] { background: var(--green); }
|
| 33 |
+
.aim-legend i[data-k='bad'], .aim-col i[data-k='bad'] { background: var(--red); }
|
| 34 |
+
.aim-bars { display: flex; align-items: flex-end; gap: 6px; height: 150px; padding-bottom: 20px; border-bottom: 1px solid var(--sep); position: relative; }
|
| 35 |
+
.aim-day { position: relative; flex: 1 1 0; min-width: 6px; height: 100%; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; outline: none; }
|
| 36 |
+
.aim-col { width: 100%; max-width: 36px; min-height: 0; display: flex; flex-direction: column; gap: 2px; }
|
| 37 |
+
.aim-col i { display: block; min-height: 2px; }
|
| 38 |
+
.aim-col i:first-child { border-radius: 4px 4px 0 0; }
|
| 39 |
+
.aim-x { position: absolute; bottom: -18px; font-size: 10px; color: var(--label-3); white-space: nowrap; }
|
| 40 |
+
.aim-day:nth-child(even) .aim-x { visibility: hidden; }
|
| 41 |
+
.aim-bars:has(.aim-day:nth-child(-n+10):last-child) .aim-x { visibility: visible; }
|
| 42 |
+
.aim-tip { position: absolute; bottom: calc(100% + 4px); left: 50%; transform: translateX(-50%); z-index: 2; padding: 6px 9px; border-radius: 8px; background: var(--menu-bg, var(--bg-elev));
|
| 43 |
+
box-shadow: var(--menu-shadow, 0 6px 20px rgba(0, 0, 0, 0.25)); color: var(--label); font-size: 12px; line-height: 16px; white-space: nowrap; pointer-events: none; opacity: 0; transition: opacity var(--d1); }
|
| 44 |
+
.aim-day:hover .aim-tip, .aim-day:focus-visible .aim-tip { opacity: 1; }
|
| 45 |
+
.aim-day:focus-visible .aim-col { outline: 2px solid var(--focus); outline-offset: 2px; }
|
| 46 |
+
|
| 47 |
+
.aim-problems, .aim-cases { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 8px; font-size: var(--fs-sm); }
|
| 48 |
+
.aim-problems > li, .aim-cases > li { padding: 10px 12px; border-radius: 10px; background: var(--fill); }
|
| 49 |
+
.aim-problems .aim-pill { margin-right: 8px; }
|
| 50 |
+
.aim-run { margin-left: 8px; font-size: 12px; }
|
| 51 |
+
.aim-cases ul { margin: 4px 0 0; padding-left: 18px; }
|
| 52 |
+
|
| 53 |
+
.aim-ds { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: var(--sp-3); }
|
| 54 |
+
.aim-ls { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: var(--sp-3); }
|
| 55 |
+
@media (max-width: 640px) { .aim-card { padding: var(--sp-4); } }
|