okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bcf88b738
main
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 : 30name :str # "prompt" | "tool call" 31ok :bool 32detail :str # plain words 33seconds :float = 0.0 34 35 36def _post (url :str ,key :str ,body :dict ,headers :dict | None = None ,timeout :float = 240.0 )-> dict : 37h = {"Content-Type" :"application/json" ,"Accept" :"application/json" ,** (headers or {})} 38if key : 39h ["Authorization" ]= "Bearer " + key 40h ["x-api-key" ]= key 41req = urllib .request .Request (url ,data = json .dumps (body ).encode ("utf-8" ),headers = h ,method = "POST" ) 42with loopback .urlopen (req ,timeout = timeout )as r : 43return json .loads (r .read ().decode ("utf-8" ,"replace" )) 44 45 46def wire_for (harness_id :str )-> str : 47return WIRE .get (harness_id ,"chat" ) 48 49 50def _prompt_request (wire :str ,base :str ,model :str )-> tuple [str ,dict ]: 51if wire == "responses" : 52return base + "/v1/responses" , {"model" :model ,"input" :PROMPT ,"max_output_tokens" :256 } 53if wire == "messages" : 54return base + "/v1/messages" , {"model" :model ,"max_tokens" :256 ,"messages" : [{"role" :"user" ,"content" :PROMPT }]} 55return 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 ]: 59if wire == "responses" : 60return 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 }]} 63if wire == "messages" : 64return 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 }]} 66return 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 : 72if wire == "responses" : 73parts = [] 74for item in data .get ("output" )or []: 75if not isinstance (item ,dict )or item .get ("type" )not in (None ,"message" ): 76continue # reasoning items are not the answer 77for c in item .get ("content" )or []: 78if isinstance (c ,dict )and c .get ("type" )in (None ,"output_text" ,"text" )and c .get ("text" ): 79parts .append (c ["text" ]) 80if parts : 81return "" .join (parts ) 82return data ["output_text" ]if isinstance (data .get ("output_text" ),str )else "" 83if wire == "messages" : 84return "" .join (b .get ("text" ,"" )for b in data .get ("content" )or []if isinstance (b ,dict )and b .get ("type" )== "text" ) 85try : 86return data ["choices" ][0 ]["message" ].get ("content" )or "" 87except (KeyError ,IndexError ,TypeError ,AttributeError ): 88return "" 89 90 91def tool_calls (wire :str ,data :dict )-> list [tuple [str ,dict ]]: 92out :list [tuple [str ,dict ]]= [] 93try : 94if wire == "responses" : 95for item in data .get ("output" )or []: 96if item .get ("type" )== "function_call" : 97out .append ((item .get ("name" ,"" ),json .loads (item .get ("arguments" )or "{}" ))) 98elif wire == "messages" : 99for b in data .get ("content" )or []: 100if isinstance (b ,dict )and b .get ("type" )== "tool_use" : 101out .append ((b .get ("name" ,"" ),b .get ("input" )or {})) 102else : 103for tc in data ["choices" ][0 ]["message" ].get ("tool_calls" )or []: 104fn = tc .get ("function" )or {} 105out .append ((fn .get ("name" ,"" ),json .loads (fn .get ("arguments" )or "{}" ))) 106except (KeyError ,IndexError ,TypeError ,ValueError ,AttributeError ): 107return out 108return 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.""" 113poster = poster or _post 114base = url .rstrip ("/" ) 115wire = wire_for (harness_id ) 116checks :list [Check ]= [] 117t0 = time .monotonic () 118try : 119u ,body = _prompt_request (wire ,base ,model ) 120data = poster (u ,key ,body ,None ,timeout ) 121text = answer_text (wire ,data ).strip () 122ok = "pong" in text .lower () 123checks .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." ), 125time .monotonic ()- t0 )) 126except Exception as e :# noqa: BLE001 127checks .append (Check ("prompt" ,False ,_why (e ),time .monotonic ()- t0 )) 128t1 = time .monotonic () 129try : 130u ,body = _tool_request (wire ,base ,model ) 131data = poster (u ,key ,body ,None ,timeout ) 132calls = tool_calls (wire ,data ) 133hit = next (((n ,a )for n ,a in calls if n == "get_weather" and "paris" in json .dumps (a ).lower ()),None ) 134if hit : 135checks .append (Check ("tool call" ,True ,f"It called { hit [ 0 ] } with { json . dumps ( hit [ 1 ]) } ." ,time .monotonic ()- t1 )) 136elif calls : 137checks .append (Check ("tool call" ,False ,f"It called { calls [ 0 ][ 0 ] } with { json . dumps ( calls [ 0 ][ 1 ])[: 60 ] } , not the city asked for." , 138time .monotonic ()- t1 )) 139else : 140checks .append (Check ("tool call" ,False ,"The model answered in words and did not call the tool." ,time .monotonic ()- t1 )) 141except Exception as e :# noqa: BLE001 142checks .append (Check ("tool call" ,False ,_why (e ),time .monotonic ()- t1 )) 143return checks 144 145 146def _why (e :Exception )-> str : 147if isinstance (e ,urllib .error .HTTPError ): 148if e .code in (401 ,403 ): 149return "The server refused the key. Check the API key in the config." 150if e .code == 404 : 151return "The server does not have that address. Check the server address and the app's endpoint type." 152return f"The server answered with an error (HTTP { e . code } )." 153if isinstance (e ,urllib .error .URLError ): 154return "The server could not be reached. Is it running (strata launch --status)?" 155return f"The check could not finish: { type ( e ). __name__ } ."