okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-022-refusals: environmental refusals repair or warn instead of blocking (audit items 1-4, 6, 8-10, 12-15)bcf88b738

main
7.7 KiB155 linesraw
1"""Check my harness: send one simple prompt and one tool call to the running server the way an app configured by
2`strata connect` would, and say in plain words whether each worked.
3
4The check uses the harness's own wire format (chat completions, responses, or messages) with the address, key and model name its
5config carries, so it proves the settings `strata connect` prints reach a server that answers correctly. It does not start the app
6itself. The prompt's answer text is checked (it must contain the expected word) and the tool call's arguments are checked (the
7city must be named), not just the HTTP status.
8"""
9
10from __future__ import annotations
11
12import json
13import time
14import urllib.error
15import urllib.request
16from dataclasses import dataclass
17
18from strata_control import loopback
19
20#: harness id -> the endpoint family it speaks (the others use chat completions)
21WIRE = {"codex": "responses", "claude-code": "messages"}
22
23PROMPT = "Reply with exactly one word: pong"
24TOOL_PROMPT = "What is the weather in Paris? Use the get_weather tool."
25TOOL_SCHEMA = {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
26
27
28@dataclass
29class Check:
30    name: str            # "prompt" | "tool call"
31    ok: bool
32    detail: str          # plain words
33    seconds: float = 0.0
34
35
36def _post(url: str, key: str, body: dict, headers: dict | None = None, timeout: float = 240.0) -> dict:
37    h = {"Content-Type": "application/json", "Accept": "application/json", **(headers or {})}
38    if key:
39        h["Authorization"] = "Bearer " + key
40        h["x-api-key"] = key
41    req = urllib.request.Request(url, data=json.dumps(body).encode("utf-8"), headers=h, method="POST")
42    with loopback.urlopen(req, timeout=timeout) as r:
43        return json.loads(r.read().decode("utf-8", "replace"))
44
45
46def wire_for(harness_id: str) -> str:
47    return WIRE.get(harness_id, "chat")
48
49
50def _prompt_request(wire: str, base: str, model: str) -> tuple[str, dict]:
51    if wire == "responses":
52        return base + "/v1/responses", {"model": model, "input": PROMPT, "max_output_tokens": 256}
53    if wire == "messages":
54        return base + "/v1/messages", {"model": model, "max_tokens": 256, "messages": [{"role": "user", "content": PROMPT}]}
55    return base + "/v1/chat/completions", {"model": model, "max_tokens": 256, "messages": [{"role": "user", "content": PROMPT}]}
56
57
58def _tool_request(wire: str, base: str, model: str) -> tuple[str, dict]:
59    if wire == "responses":
60        return base + "/v1/responses", {"model": model, "input": TOOL_PROMPT, "max_output_tokens": 1536, "tool_choice": "auto",
61                                        "tools": [{"type": "function", "name": "get_weather", "description": "Weather of a city",
62                                                   "parameters": TOOL_SCHEMA}]}
63    if wire == "messages":
64        return base + "/v1/messages", {"model": model, "max_tokens": 1536, "messages": [{"role": "user", "content": TOOL_PROMPT}],
65                                       "tools": [{"name": "get_weather", "description": "Weather of a city", "input_schema": TOOL_SCHEMA}]}
66    return base + "/v1/chat/completions", {"model": model, "max_tokens": 1536, "messages": [{"role": "user", "content": TOOL_PROMPT}],
67                                           "tools": [{"type": "function", "function": {"name": "get_weather", "description": "Weather of a city",
68                                                                                      "parameters": TOOL_SCHEMA}}]}
69
70
71def answer_text(wire: str, data: dict) -> str:
72    if wire == "responses":
73        parts = []
74        for item in data.get("output") or []:
75            if not isinstance(item, dict) or item.get("type") not in (None, "message"):
76                continue                                   # reasoning items are not the answer
77            for c in item.get("content") or []:
78                if isinstance(c, dict) and c.get("type") in (None, "output_text", "text") and c.get("text"):
79                    parts.append(c["text"])
80        if parts:
81            return "".join(parts)
82        return data["output_text"] if isinstance(data.get("output_text"), str) else ""
83    if wire == "messages":
84        return "".join(b.get("text", "") for b in data.get("content") or [] if isinstance(b, dict) and b.get("type") == "text")
85    try:
86        return data["choices"][0]["message"].get("content") or ""
87    except (KeyError, IndexError, TypeError, AttributeError):
88        return ""
89
90
91def tool_calls(wire: str, data: dict) -> list[tuple[str, dict]]:
92    out: list[tuple[str, dict]] = []
93    try:
94        if wire == "responses":
95            for item in data.get("output") or []:
96                if item.get("type") == "function_call":
97                    out.append((item.get("name", ""), json.loads(item.get("arguments") or "{}")))
98        elif wire == "messages":
99            for b in data.get("content") or []:
100                if isinstance(b, dict) and b.get("type") == "tool_use":
101                    out.append((b.get("name", ""), b.get("input") or {}))
102        else:
103            for tc in data["choices"][0]["message"].get("tool_calls") or []:
104                fn = tc.get("function") or {}
105                out.append((fn.get("name", ""), json.loads(fn.get("arguments") or "{}")))
106    except (KeyError, IndexError, TypeError, ValueError, AttributeError):
107        return out
108    return out
109
110
111def run_checks(harness_id: str, url: str, key: str, model: str, *, timeout: float = 240.0, poster=None) -> list[Check]:
112    """The two checks for one harness. `poster` is replaceable for tests."""
113    poster = poster or _post
114    base = url.rstrip("/")
115    wire = wire_for(harness_id)
116    checks: list[Check] = []
117    t0 = time.monotonic()
118    try:
119        u, body = _prompt_request(wire, base, model)
120        data = poster(u, key, body, None, timeout)
121        text = answer_text(wire, data).strip()
122        ok = "pong" in text.lower()
123        checks.append(Check("prompt", ok, f"It answered: {text[:60]!r}." if ok else
124                            (f"It answered {text[:60]!r}, not the word asked for." if text else "The server replied but with no text."),
125                            time.monotonic() - t0))
126    except Exception as e:                                   # noqa: BLE001
127        checks.append(Check("prompt", False, _why(e), time.monotonic() - t0))
128    t1 = time.monotonic()
129    try:
130        u, body = _tool_request(wire, base, model)
131        data = poster(u, key, body, None, timeout)
132        calls = tool_calls(wire, data)
133        hit = next(((n, a) for n, a in calls if n == "get_weather" and "paris" in json.dumps(a).lower()), None)
134        if hit:
135            checks.append(Check("tool call", True, f"It called {hit[0]} with {json.dumps(hit[1])}.", time.monotonic() - t1))
136        elif calls:
137            checks.append(Check("tool call", False, f"It called {calls[0][0]} with {json.dumps(calls[0][1])[:60]}, not the city asked for.",
138                                time.monotonic() - t1))
139        else:
140            checks.append(Check("tool call", False, "The model answered in words and did not call the tool.", time.monotonic() - t1))
141    except Exception as e:                                   # noqa: BLE001
142        checks.append(Check("tool call", False, _why(e), time.monotonic() - t1))
143    return checks
144
145
146def _why(e: Exception) -> str:
147    if isinstance(e, urllib.error.HTTPError):
148        if e.code in (401, 403):
149            return "The server refused the key. Check the API key in the config."
150        if e.code == 404:
151            return "The server does not have that address. Check the server address and the app's endpoint type."
152        return f"The server answered with an error (HTTP {e.code})."
153    if isinstance(e, urllib.error.URLError):
154        return "The server could not be reached. Is it running (strata launch --status)?"
155    return f"The check could not finish: {type(e).__name__}."