Parse choices[0].message.tool_calls into the ask Result; empty list when absent. Offline gold covers tool_calls_from. Co-authored-by: Cursor <cursoragent@cursor.com>
3.5 KiB
3.5 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
tool_calls_from
+ `data`
Extract OpenAI-shaped choices[0].message.tool_calls as a list (or empty list).
choices = > json.get value=data key="choices"
- not
choicesempty = > json.parse text=[] empty -
c0 = 1
msg = > json.get value=c0 key="message"
- not
msgempty = > json.parse text=[] empty -
**tc = > json.get value=`msg` key="tool_calls"**
1. `tc`
*tc*
2. *
**empty = > json.parse text=[]**
*empty*
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,tool_calls}; 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
msg = message
text = > json.get value=
msgkey="content" 1. nottexttext = "" 2. * _ = 1 usage = > usage_from data=datafr = > json.get value=1 key="finish_reason" 1. notfrfr = "stop" 2. * _ = 1 tc = > tool_calls_from data=datapack = > 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 = > json.set map=packkey="tool_calls" value=tcpack -
> print text=ext/ai/llm/openai: HTTP error
> print text=[status](resp)
> print text=[body](resp)
> sys.exit code=1