0.2.1: native Ollama dialect on both modes; Home Assistant proven end-to-end
/{mode}/api/{tags,chat,generate,version,show,ps} beside the OpenAI surface.
forge path is a raw proxy (forge is Ollama); the cloud fallback is translated
both ways — NDJSON frames byte-compatible with Ollama's, tool calls round-trip
with synthesised ids, format mapped, think→reasoning_effort (forced to none
with tools: OpenAI rejects the combination on gpt-5.4-mini). Tags never wait
on a model load (HA's list() has a 5 s timeout). local-strict still 503s in
Ollama's error shape; the OpenAI dialect is untouched.
Home Assistant (Lounge, 2026.9.2) configured through its REST config flow and
proven with a real conversation. HA's VLAN cannot reach the k8s ingress, so
it uses forgeway.dmz.lounge.falkvinge.net through the entrance HAProxy
(RFC1918-fenced vhost); the .services. alias needs a pfSense rule from Rick.
22/22 in-cluster checks on both sites. scripts/ha_setup_ollama.py is
idempotent and ends with a real answer; local-smoke-ollama.sh uses the exact
client HA pins.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
1bec7c784c
commit
c37e54c5c2
@@ -30,3 +30,19 @@ echo "10 readiness, forge UNAVAILABLE ....... HTTP $(j $BAD/healthz/ready)"
|
||||
echo "11 streaming through forge ............ HTTP $(j -XPOST $GOOD/local-strict/v1/chat/completions -H 'Content-Type: application/json' -d '{"messages":[{"role":"user","content":"count to three"}],"max_tokens":200,"stream":true}') sse_chunks=$(grep -c '^data:' /tmp/b)"
|
||||
echo "12 bare /v1 guard (expect 404) ........ HTTP $(j $GOOD/v1/models)"
|
||||
echo "13 unknown mode guard (expect 404) .... HTTP $(j $GOOD/local-wishful/v1/models)"
|
||||
|
||||
# ---- native Ollama dialect (what Home Assistant's integration speaks) -------
|
||||
OCHAT='{"model":"gpt-oss:120b","messages":[{"role":"user","content":"Answer with the single word: PONG"}],"stream":false,"think":false,"keep_alive":"5m","options":{"num_ctx":8192}}'
|
||||
OSTREAM='{"model":"gpt-oss:120b","messages":[{"role":"user","content":"Answer with the single word: PONG"}],"stream":true,"think":false}'
|
||||
ocontent() { sed -n 's/.*"message": *{[^}]*"content": *"\([^"]*\)".*/\1/p' /tmp/b | head -1 | cut -c1-40; }
|
||||
ndjson_summary() { printf 'frames=%s content_frames=%s last_done=%s' "$(wc -l < /tmp/b)" "$(grep -c '"content": *"[^"]' /tmp/b)" "$(tail -1 /tmp/b | grep -o '"done": *true' | head -1)"; }
|
||||
|
||||
echo "14 ollama /api/tags (forge up) ........ HTTP $(j $GOOD/local-strict/api/tags) $(grep -o '"model":"[^"]*"' /tmp/b | head -1)"
|
||||
echo "15 ollama /api/chat non-stream (forge) HTTP $(j -XPOST $GOOD/local-strict/api/chat -H 'Content-Type: application/json' -d "$OCHAT") backend=$(backend) content=[$(ocontent)] $(grep -o '"done_reason":"[^"]*"' /tmp/b | head -1)"
|
||||
echo "16 ollama /api/chat STREAM (forge) .... HTTP $(j -XPOST $GOOD/local-optimistic/api/chat -H 'Content-Type: application/json' -d "$OSTREAM") $(ndjson_summary) ctype=$(grep -i '^content-type' /tmp/h | tr -d '\r' | awk '{print $2}')"
|
||||
echo "17 ollama /api/version + /api/generate HTTP $(j $GOOD/local-strict/api/version) $(cut -c1-30 /tmp/b) | generate HTTP $(j -XPOST $GOOD/local-strict/api/generate -H 'Content-Type: application/json' -d '{"model":"gpt-oss:120b","prompt":"Answer with the single word: PONG","stream":false,"think":false}') $(grep -o '"response":"[^"]*"' /tmp/b | head -1)"
|
||||
echo "18 ollama STRICT chat, forge UNAVAIL .. HTTP $(j -XPOST $BAD/local-strict/api/chat -H 'Content-Type: application/json' -d "$OCHAT") $(cut -c1-90 /tmp/b)"
|
||||
echo "19 ollama OPTIMISTIC chat, UNAVAIL .... HTTP $(j -XPOST $BAD/local-optimistic/api/chat -H 'Content-Type: application/json' -d "$OCHAT") backend=$(backend) content=[$(ocontent)] $(grep -o '"done_reason":"[^"]*"' /tmp/b | head -1)"
|
||||
echo "20 ollama OPTIMISTIC STREAM, UNAVAIL .. HTTP $(j -XPOST $BAD/local-optimistic/api/chat -H 'Content-Type: application/json' -d "$OSTREAM") backend=$(backend) $(ndjson_summary)"
|
||||
echo "21 ollama /api/tags, forge UNAVAIL .... HTTP $(j $BAD/local-optimistic/api/tags) (listing, not liveness)"
|
||||
echo "22 ollama /api/pull guard (expect 400) HTTP $(j -XPOST $GOOD/local-strict/api/pull -H 'Content-Type: application/json' -d '{"model":"llama3"}')"
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Configure Home Assistant's Ollama integration against forgeway and PROVE it
|
||||
with a real conversation, entirely through HA's own REST API.
|
||||
|
||||
ha_setup_ollama.py <ha_base_url> <forgeway_url> [--name NAME] [--assist]
|
||||
|
||||
The long-lived token is read from `pass hassio/lounge-token` inside this process
|
||||
and only ever travels as an Authorization header. Idempotent: an existing entry
|
||||
for the same URL, and an existing conversation subentry of the same name, are
|
||||
reused rather than duplicated.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
|
||||
class HA:
|
||||
def __init__(self, base: str):
|
||||
self.base = base.rstrip("/")
|
||||
self.token = subprocess.run(["pass", "hassio/lounge-token"], capture_output=True, text=True, check=True).stdout.strip()
|
||||
|
||||
def call(self, method: str, path: str, body: dict | None = None) -> tuple[int, dict | list | str]:
|
||||
req = urllib.request.Request(
|
||||
f"{self.base}{path}",
|
||||
data=json.dumps(body).encode() if body is not None else None,
|
||||
headers={"Authorization": f"Bearer {self.token}", "Content-Type": "application/json"},
|
||||
method=method,
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=120) as r:
|
||||
raw = r.read().decode()
|
||||
try:
|
||||
return r.status, json.loads(raw)
|
||||
except ValueError:
|
||||
return r.status, raw
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read().decode("utf-8", "replace")
|
||||
try:
|
||||
return e.code, json.loads(raw)
|
||||
except ValueError:
|
||||
return e.code, raw
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("ha_base")
|
||||
ap.add_argument("forgeway_url")
|
||||
ap.add_argument("--name", default="forgeway optimistic")
|
||||
ap.add_argument("--assist", action="store_true", help="also grant the Assist API (device control)")
|
||||
ap.add_argument("--question", default="In one short sentence, what is Home Assistant?")
|
||||
args = ap.parse_args()
|
||||
ha = HA(args.ha_base)
|
||||
|
||||
# ---- 1. parent entry: the server URL ---------------------------------
|
||||
st, entries = ha.call("GET", "/api/config/config_entries/entry")
|
||||
existing = [e for e in entries if e["domain"] == "ollama" and e.get("title") == args.forgeway_url]
|
||||
if existing:
|
||||
entry = existing[0]
|
||||
print(f"[entry] reusing existing Ollama entry {entry['entry_id'][:8]} state={entry['state']}")
|
||||
else:
|
||||
st, flow = ha.call("POST", "/api/config/config_entries/flow", {"handler": "ollama"})
|
||||
if st != 200 or flow.get("type") != "form":
|
||||
print(f"[entry] could not start config flow: {st} {flow}")
|
||||
return 1
|
||||
st, res = ha.call("POST", f"/api/config/config_entries/flow/{flow['flow_id']}", {"url": args.forgeway_url})
|
||||
if res.get("type") != "create_entry":
|
||||
# HA validated the URL by calling /api/tags with a 5 s timeout; errors land here
|
||||
print(f"[entry] config flow did not create an entry: {st} {json.dumps(res)[:400]}")
|
||||
return 1
|
||||
entry = res["result"]
|
||||
print(f"[entry] created Ollama entry {entry['entry_id'][:8]} for {args.forgeway_url}")
|
||||
|
||||
# ---- 2. conversation subentry: model + options -----------------------
|
||||
entry_id = entry["entry_id"]
|
||||
st, full = ha.call("GET", "/api/config/config_entries/entry")
|
||||
entry = next(e for e in full if e["entry_id"] == entry_id)
|
||||
subs = entry.get("subentries") or []
|
||||
sub = next((s for s in subs if s.get("subentry_type") == "conversation" and s.get("title") == args.name), None)
|
||||
if sub:
|
||||
print(f"[subentry] reusing conversation subentry '{args.name}'")
|
||||
else:
|
||||
st, flow = ha.call("POST", "/api/config/config_entries/subentries/flow", {"handler": [entry_id, "conversation"]})
|
||||
if st != 200 or flow.get("type") != "form":
|
||||
print(f"[subentry] could not start subentry flow: {st} {json.dumps(flow)[:300]}")
|
||||
return 1
|
||||
models = [o["value"] for f in flow.get("data_schema", []) if f.get("name") == "model"
|
||||
for o in (f.get("selector", {}).get("select", {}).get("options") or []) if isinstance(o, dict)]
|
||||
print(f"[subentry] HA listed models from forgeway: {[m for m in models if 'gpt-oss' in m] or models[:3]}")
|
||||
data = {
|
||||
"name": args.name,
|
||||
"model": "gpt-oss:120b",
|
||||
"num_ctx": 8192,
|
||||
"max_history": 20,
|
||||
"keep_alive": -1,
|
||||
"think": False,
|
||||
}
|
||||
if args.assist:
|
||||
data["llm_hass_api"] = ["assist"]
|
||||
st, res = ha.call("POST", f"/api/config/config_entries/subentries/flow/{flow['flow_id']}", data)
|
||||
if res.get("type") != "create_entry":
|
||||
print(f"[subentry] flow did not create an entry: {st} {json.dumps(res)[:400]}")
|
||||
return 1
|
||||
print(f"[subentry] created conversation subentry '{args.name}' (model gpt-oss:120b, think=False, assist={args.assist})")
|
||||
|
||||
# ---- 3. find the conversation entity ---------------------------------
|
||||
entity_id = None
|
||||
for _ in range(30):
|
||||
st, states = ha.call("GET", "/api/states")
|
||||
for s in states:
|
||||
if s["entity_id"].startswith("conversation.") and s["attributes"].get("friendly_name") == args.name:
|
||||
entity_id = s["entity_id"]
|
||||
if entity_id:
|
||||
break
|
||||
time.sleep(2)
|
||||
if not entity_id:
|
||||
print("[entity] conversation entity did not appear")
|
||||
return 1
|
||||
print(f"[entity] {entity_id}")
|
||||
|
||||
# ---- 4. PROVE: a real conversation through HA ------------------------
|
||||
started = time.perf_counter()
|
||||
st, res = ha.call("POST", "/api/conversation/process", {"text": args.question, "agent_id": entity_id, "language": "en"})
|
||||
took = time.perf_counter() - started
|
||||
speech = (((res.get("response") or {}).get("speech") or {}).get("plain") or {}).get("speech") if isinstance(res, dict) else None
|
||||
rtype = (res.get("response") or {}).get("response_type") if isinstance(res, dict) else None
|
||||
print(f"[conversation] HTTP {st} response_type={rtype} took={took:.1f}s")
|
||||
print(f"[conversation] Q: {args.question}")
|
||||
print(f"[conversation] A: {speech!r}")
|
||||
return 0 if st == 200 and speech and rtype != "error" else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+98
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env bash
|
||||
# Local smoke for the native-Ollama dialect. Two instances: one at the real
|
||||
# forge, one at a dead upstream (the fallback / 503 paths). Uses the exact
|
||||
# client Home Assistant pins (ollama==0.6.2) for the calls HA makes, and curl
|
||||
# for raw frame shapes. Never touches Ollama on forge.
|
||||
set -uo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"; PY="$ROOT/.venv/bin/python"
|
||||
GOOD=http://127.0.0.1:18080; BAD=http://127.0.0.1:18081
|
||||
|
||||
start() { FORGEWAY_NAME=forgeway FORGEWAY_SITE="$1" FORGEWAY_UPSTREAMS="$3" FORGEWAY_DISCOVERY_TIMEOUT=3 \
|
||||
"$PY" -m uvicorn app.main:app --host 127.0.0.1 --port "$2" --no-access-log >"/tmp/forgeway-$1.log" 2>&1 & echo $!; }
|
||||
cd "$ROOT"
|
||||
P1=$(start ollama-good 18080 "http://forge.dmz.falkvinge.net:11434"); P2=$(start ollama-bad 18081 "http://127.0.0.1:1")
|
||||
trap 'kill $P1 $P2 2>/dev/null' EXIT; sleep 4
|
||||
|
||||
hdr() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
|
||||
CHAT='{"model":"gpt-oss:120b","messages":[{"role":"user","content":"Reply with exactly: PONG"}],"stream":false,"think":false,"keep_alive":"5m","options":{"num_ctx":8192}}'
|
||||
|
||||
hdr "1 HA-pinned client (ollama==0.6.2): list() + chat(stream=True) exactly as HA calls them, forge up"
|
||||
"$PY" - <<'PY'
|
||||
import asyncio, ollama
|
||||
async def main():
|
||||
c = ollama.AsyncClient(host="http://127.0.0.1:18080/local-optimistic")
|
||||
print(" list():", [m.model for m in (await c.list()).models])
|
||||
content = thinking = ""; done = None; n = 0
|
||||
async for part in await c.chat(model="gpt-oss:120b", messages=[{"role":"user","content":"Reply with exactly: PONG"}],
|
||||
stream=True, keep_alive=-1, options={"num_ctx": 8192}, think=False):
|
||||
n += 1; content += part.message.content or ""; thinking += part.message.thinking or ""
|
||||
if part.done: done = part.done_reason
|
||||
print(f" chat(stream=True): chunks={n} content={content!r} thinking_chars={len(thinking)} done_reason={done}")
|
||||
asyncio.run(main())
|
||||
PY
|
||||
|
||||
hdr "2 raw shapes, forge up: /api/chat non-stream, /api/tags, /api/version, /api/ps, /api/show"
|
||||
curl -s -m 120 -D /tmp/h -X POST $GOOD/local-strict/api/chat -H 'Content-Type: application/json' -d "$CHAT" | python3 -c "
|
||||
import sys,json; d=json.load(sys.stdin); m=d['message']
|
||||
print(' chat:', 'content=%r'%m.get('content'), 'thinking=%s' % ('yes' if m.get('thinking') else 'no'), 'done=%s'%d['done'], 'done_reason=%s'%d.get('done_reason'), 'keys_ok=%s' % all(k in d for k in ('model','created_at','message','done','done_reason','total_duration','eval_count')))"
|
||||
echo " backend: $(grep -i x-forgeway-backend /tmp/h | tr -d '\r')"
|
||||
echo " tags: $(curl -s -m 10 $GOOD/local-strict/api/tags | python3 -c 'import sys,json; d=json.load(sys.stdin); print([ (m["model"], m.get("details",{}).get("family")) for m in d["models"]])')"
|
||||
echo " version: $(curl -s -m 10 $GOOD/local-strict/api/version)"
|
||||
echo " ps: $(curl -s -m 10 -o /dev/null -w '%{http_code}' $GOOD/local-strict/api/ps) show: $(curl -s -m 10 -o /dev/null -w '%{http_code}' -X POST $GOOD/local-strict/api/show -d '{"model":"x"}') pull(400 expected): $(curl -s -m 10 -o /dev/null -w '%{http_code}' -X POST $GOOD/local-strict/api/pull -d '{"model":"llama3"}')"
|
||||
|
||||
hdr "3 raw streaming through forge: framing = NDJSON, last frame done=true"
|
||||
curl -s -N -m 120 -D /tmp/h -X POST $GOOD/local-optimistic/api/chat -H 'Content-Type: application/json' -d "${CHAT/\"stream\":false/\"stream\":true}" > /tmp/s.ndjson
|
||||
echo " content-type: $(grep -i '^content-type' /tmp/h | tr -d '\r' | awk '{print $2}') frames=$(wc -l < /tmp/s.ndjson) last=$(tail -1 /tmp/s.ndjson | python3 -c 'import sys,json; d=json.load(sys.stdin); print("done=%s reason=%s"%(d["done"],d.get("done_reason")))')"
|
||||
|
||||
hdr "4 generate through forge (non-stream)"
|
||||
curl -s -m 120 -X POST $GOOD/local-strict/api/generate -H 'Content-Type: application/json' -d '{"model":"gpt-oss:120b","prompt":"Reply with exactly: PONG","stream":false,"think":false}' | python3 -c "import sys,json; d=json.load(sys.stdin); print(' response=%r done=%s reason=%s' % (d.get('response'), d.get('done'), d.get('done_reason')))"
|
||||
|
||||
hdr "5 DEAD UPSTREAM, strict: /api/chat must be a clean Ollama-shaped 503"
|
||||
echo " HTTP $(curl -s -m 30 -o /tmp/b -w '%{http_code}' -X POST $BAD/local-strict/api/chat -H 'Content-Type: application/json' -d "$CHAT") body=$(cut -c1-150 /tmp/b)"
|
||||
echo " tags still 200 (listing, not liveness): $(curl -s -m 10 -o /dev/null -w '%{http_code}' $BAD/local-strict/api/tags)"
|
||||
|
||||
hdr "6 DEAD UPSTREAM, optimistic: cloud fallback translated to Ollama shape (non-stream)"
|
||||
curl -s -m 120 -D /tmp/h -X POST $BAD/local-optimistic/api/chat -H 'Content-Type: application/json' -d "$CHAT" | python3 -c "
|
||||
import sys,json; d=json.load(sys.stdin); m=d['message']
|
||||
print(' content=%r done=%s done_reason=%s eval_count=%s created_at=%s' % (m.get('content'), d['done'], d.get('done_reason'), d.get('eval_count'), d['created_at'][:19]))"
|
||||
echo " backend: $(grep -i x-forgeway-backend /tmp/h | tr -d '\r')"
|
||||
|
||||
hdr "7 DEAD UPSTREAM, optimistic: cloud fallback STREAMED as NDJSON, read with the HA-pinned client"
|
||||
"$PY" - <<'PY'
|
||||
import asyncio, ollama
|
||||
async def main():
|
||||
c = ollama.AsyncClient(host="http://127.0.0.1:18081/local-optimistic")
|
||||
content = ""; done = None; n = 0
|
||||
async for part in await c.chat(model="gpt-oss:120b", messages=[{"role":"user","content":"Reply with exactly: PONG"}], stream=True, think=False):
|
||||
n += 1; content += part.message.content or ""
|
||||
if part.done: done = part.done_reason
|
||||
print(f" chunks={n} content={content!r} done_reason={done}")
|
||||
asyncio.run(main())
|
||||
PY
|
||||
|
||||
hdr "8 DEAD UPSTREAM, optimistic: tool call round-trip through the cloud (HA Assist-API shape)"
|
||||
"$PY" - <<'PY'
|
||||
import asyncio, ollama
|
||||
async def main():
|
||||
c = ollama.AsyncClient(host="http://127.0.0.1:18081/local-optimistic")
|
||||
tools=[{"type":"function","function":{"name":"HassTurnOn","description":"Turn on a device","parameters":{"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}}}]
|
||||
msgs=[{"role":"user","content":"Turn on the kitchen light. Use the tool."}]
|
||||
calls=[]
|
||||
async for part in await c.chat(model="gpt-oss:120b", messages=msgs, tools=tools, stream=True, think=False):
|
||||
if part.message.tool_calls: calls += [(t.function.name, dict(t.function.arguments)) for t in part.message.tool_calls]
|
||||
print(" tool_calls:", calls)
|
||||
# second round: feed the tool result back (ids are synthesised by the router)
|
||||
msgs += [{"role":"assistant","content":"","tool_calls":[{"function":{"name":"HassTurnOn","arguments":{"name":"kitchen light"}}}]},
|
||||
{"role":"tool","content":'{"data":{"success":true},"error":null}'}]
|
||||
r = await c.chat(model="gpt-oss:120b", messages=msgs, tools=tools, stream=False, think=False)
|
||||
print(" after tool result:", repr((r.message.content or "")[:80]), "done_reason=", r.done_reason)
|
||||
asyncio.run(main())
|
||||
PY
|
||||
|
||||
hdr "9 DEAD UPSTREAM, optimistic: generate via cloud (stream), and format=json"
|
||||
curl -s -N -m 120 -X POST $BAD/local-optimistic/api/generate -H 'Content-Type: application/json' -d '{"model":"gpt-oss:120b","prompt":"Reply with exactly: PONG","stream":true}' > /tmp/g.ndjson
|
||||
echo " generate stream frames=$(wc -l < /tmp/g.ndjson) text=$(python3 -c 'import json; print(repr("".join(json.loads(l).get("response","") for l in open("/tmp/g.ndjson"))))') last=$(tail -1 /tmp/g.ndjson | cut -c1-90)"
|
||||
echo " format=json: $(curl -s -m 120 -X POST $BAD/local-optimistic/api/chat -H 'Content-Type: application/json' -d '{"model":"x","messages":[{"role":"user","content":"Return JSON with key a = 1"}],"stream":false,"format":"json"}' | python3 -c 'import sys,json; print(repr(json.load(sys.stdin)["message"]["content"][:60]))')"
|
||||
|
||||
hdr "10 OpenAI dialect untouched (regression): /v1/models + strict chat"
|
||||
echo " models: $(curl -s -m 10 -o /dev/null -w '%{http_code}' $GOOD/local-strict/v1/models) chat: $(curl -s -m 120 -o /tmp/b -w '%{http_code}' -X POST $GOOD/local-strict/v1/chat/completions -H 'Content-Type: application/json' -d '{"messages":[{"role":"user","content":"Reply with exactly: PONG"}],"max_tokens":300}') $(python3 -c 'import json; print(repr(json.load(open("/tmp/b"))["choices"][0]["message"]["content"][:20]))')"
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Probe gpt-5.4-mini's reasoning_effort / stream_options / tool-call contract.
|
||||
|
||||
Needed to translate Ollama's `think` flag and streaming shape onto the cloud
|
||||
fallback. Reads the key from the environment and never prints it.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
KEY = os.environ.get("OPENAI_API_KEY", "")
|
||||
MODEL = os.environ.get("FORGEWAY_CLOUD_MODEL", "gpt-5.4-mini")
|
||||
if not KEY:
|
||||
sys.exit("OPENAI_API_KEY not present in the environment")
|
||||
|
||||
BASE = {"model": MODEL, "messages": [{"role": "user", "content": "say PONG"}], "max_completion_tokens": 64}
|
||||
CASES = {
|
||||
"reasoning_effort=none": {"reasoning_effort": "none"},
|
||||
"reasoning_effort=low": {"reasoning_effort": "low"},
|
||||
"reasoning_effort=medium": {"reasoning_effort": "medium"},
|
||||
"reasoning_effort=high": {"reasoning_effort": "high"},
|
||||
"stream+include_usage": {"stream": True, "stream_options": {"include_usage": True}},
|
||||
"response_format=json_object": {"response_format": {"type": "json_object"},
|
||||
"messages": [{"role": "user", "content": "Return JSON {\"a\":1}"}]},
|
||||
"tools": {"tools": [{"type": "function", "function": {"name": "get_weather",
|
||||
"description": "Weather for a city", "parameters": {"type": "object",
|
||||
"properties": {"city": {"type": "string"}}, "required": ["city"]}}}],
|
||||
"messages": [{"role": "user", "content": "What is the weather in Berlin? Use the tool."}]},
|
||||
}
|
||||
|
||||
for label, extra in CASES.items():
|
||||
body = {**BASE, **extra}
|
||||
req = urllib.request.Request(
|
||||
"https://api.openai.com/v1/chat/completions",
|
||||
data=json.dumps(body).encode(),
|
||||
headers={"Content-Type": "application/json", "Authorization": f"Bearer {KEY}"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=90) as resp:
|
||||
raw = resp.read().decode()
|
||||
if body.get("stream"):
|
||||
lines = [l for l in raw.splitlines() if l.startswith("data: ")]
|
||||
last = json.loads(lines[-2][6:]) if len(lines) >= 2 and lines[-1].strip() == "data: [DONE]" else json.loads(lines[-1][6:])
|
||||
print(f"{label:30s} -> {resp.status} sse_lines={len(lines)} last_has_usage={'usage' in last and last['usage'] is not None} last_choices={len(last.get('choices', []))}")
|
||||
else:
|
||||
d = json.loads(raw)
|
||||
msg = d["choices"][0]["message"]
|
||||
print(f"{label:30s} -> {resp.status} finish={d['choices'][0]['finish_reason']} content={msg.get('content')!r:.40} tool_calls={json.dumps(msg.get('tool_calls'))[:120] if msg.get('tool_calls') else None}")
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = exc.read().decode("utf-8", "replace")
|
||||
try:
|
||||
detail = json.loads(detail)["error"]["message"]
|
||||
except Exception:
|
||||
detail = detail[:160]
|
||||
print(f"{label:30s} -> {exc.code} {detail}")
|
||||
Reference in New Issue
Block a user