Finish ai-stack steps 1–5: model_turn usage, fast/reasoning, type:prompt load, openai/ollama split, and agent-zero-llm gold. Fix compiled-skill Marqdo syntax so llm_free await no longer falls through to plan+HTTP. Co-authored-by: Cursor <cursoragent@cursor.com>
2.8 KiB
2.8 KiB
title: ext/ai/llm/openai description: >- OpenAI-compatible chat completions transport (HTTP + SSE). Used by ext/ai/llm; authors should prefer llm.ask / llm.stream. import net:lib/net.mq.md import json:lib/json.mq.md import table:lib/table.mq.md import sys:lib/sys.mq.md
usage_from
+ `data`
Extract {prompt_tokens,completion_tokens,total_tokens} from an OpenAI-shaped response map.
u = > json.get value=data key="usage"
upt = > json.get value=ukey="prompt_tokens" ct = > json.get value=ukey="completion_tokens" tt = > json.get value=ukey="total_tokens"- not
ptpt = 0 -
**_ = 1**
- not
ctct = 0 -
**_ = 1**
- not
tttt = pt + ct -
**_ = 1**
pt = 0 ct = 0 tt = 0
usage =
| prompt_tokens | completion_tokens | total_tokens |
|---|---|---|
pt |
ct |
tt |
usage
chat_completions
+ `base_url`
+ `api_key`
+ `model`
+ `prompt`
+ `stream`=False
+ `echo`=False
+ `suffix`=/chat/completions
+ `bearer`="Bearer "
POST /chat/completions (or stream SSE). Non-stream → {text,usage,finish}; stream → {events,finish}.
url = base_url + suffix
auth = bearer + api_key
headers = > table.put in=None at="Authorization" value=auth
messages =
| @ | role | content |
|---|---|---|
| 1 | user | prompt |
req =
| model | messages |
|---|---|
model |
messages |
streamreq = > table.put in=reqat="stream" value=True body = > json.stringify value=reqresp = > net.http_post_sse url=urlbody=bodyheaders=headersecho=echo- status == 200
pack = > json.parse text={"finish":"stop"}
pack = > json.set map=
packkey="events" value=events pack -
> print text=ext/ai/llm/openai: HTTP error (stream)
> print text=[status](resp)
> sys.exit code=1
body = > json.stringify value=req
resp = > net.http_post url=url body=body headers=headers
- status == 200
data = > json.parse text=body
text = content
usage = > usage_from data=
datafr = > json.get value=1 key="finish_reason" 1. notfrfr = "stop" 2. * _ = 1 pack = > json.parse text={"finish":"stop"} pack = > json.set map=packkey="text" value=textpack = > json.set map=packkey="usage" value=usagepack = > json.set map=packkey="finish" value=frpack -
> print text=ext/ai/llm/openai: HTTP error
> print text=[status](resp)
> print text=[body](resp)
> sys.exit code=1