diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8b20a26..92d70f0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,7 +28,7 @@ Features reach the core only through the ports in `internal/feature`, one per st | The model is asked | `OnTurn` (a note on the message, images) and `Tools` (a `ToolGroup`) | | Time arrives | `At`: a one-shot timer | -and the host's services: `Env`, `Info`, `Media`, `Deliver`, `Groups`, `Redact` and `Go`. Hooks run in `features.go` order. An `OnMessage` hook for an unaddressed message runs on the reader goroutine, so it must not block or call the network. +and the host's services: `Env`, `Info`, `Media`, `CallAPI`, `Deliver`, `Groups`, `Redact` and `Go`. Hooks run in `features.go` order. An `OnMessage` hook for an unaddressed message runs on the reader goroutine, so it must not block or call the network. If a feature can't be built on these, that's a design finding. Either a port becomes more generic, and stays tied to its stage, or the feature takes on more of the work. A feature-shaped field in the core is never the answer: delete any feature and the core doesn't change. diff --git a/TECHNICAL.md b/TECHNICAL.md index c7180c9..b94fa9c 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -24,7 +24,7 @@ What the bot does with no features registered. - **Answer.** Typing is shown until the reply is ready, then stopped with `sendTyping` and `stop`, so a reaction or a turn that sends nothing doesn't leave "typing…" up until Signal's own timeout. The prompt is built ([below](#the-prompt)) and sent to the model. On failure the "model error" line is logged, the chat gets "Sorry, I couldn't get an answer just now." (or, when the model was still calling tools after its last round with nothing to say, `model.ErrTooManyRounds`, "That took more lookups than I can do for one reply. Try asking for one thing at a time."), and history is unchanged. The network renders the reply's Markdown, then sends it without a leading @ and the bot's own name (an echo of how it was addressed), with @Name, and in a group the bot's own @name elsewhere (as in the intro's `I respond to @{name}`), linked to real mentions, as one message capped at 8,000 characters, the rest cut with " […truncated]" and a warning. A reply is never split: past 2,000 bytes, signal-cli 0.14.10 sends the body cut there with the whole text as a long-text attachment (`applyMessage` in `ManagerImpl`), as Signal's apps do, shown as one message with Read more. - **Markdown on Signal.** Signal shows text styles, not Markdown, so `internal/signal/markdown.go` turns a reply into plain text and signal-cli's `textStyle` ranges (`start:length:STYLE`, UTF-16 units of each message sent): `**bold**` and `__bold__` are BOLD, `*italic*` and `_italic_` ITALIC, `~~strike~~` STRIKETHROUGH, `` `code` `` and fenced code blocks (fences and language dropped) MONOSPACE, `||spoiler||` SPOILER; `# Heading` (1–6 `#`) is its text in bold, and `[text](url)` is "text (url)", or the url alone when they are the same. Markers open and close only at word boundaries (`2*3*4`, `snake_case_name` and `a * b` stay as they are), an unmatched one stays literal, nothing in code is converted, and lists, tables and quotes stay as written. Conversion comes first, so stripping and mentions work on the plain text. - **Nothing to answer.** A message with no text (only a photo or sticker) is answered only if an `OnTurn` hook adds something to it. -- **The model.** A chat completions API in OpenAI's format at `MODEL_API_URL` (OpenRouter's by default, `internal/model`), with `MODEL_API_KEY` as a bearer token if set, over a keep-alive client that requires TLS 1.3 for `https://`. Requests to OpenRouter (host `openrouter.ai`) set `provider.data_collection: deny` and `usage.include` for the real cost, plus the `MODEL_REASONING` effort as `reasoning.effort`; requests elsewhere carry only `reasoning_effort`. Either effort is left out when `MODEL_REASONING` is `none`. The tokens are logged with each reply, and the cost when the API reports it. A network error, 429 or 5xx gets one retry; an error body is reduced to its message ("status N: message"). The tool loop takes at most 5 requests and 3 minutes per reply, and 4 pictures; if a request after a tool made pictures fails, the pictures are the reply, without words, since they may have cost money to make. `Host.GenerateImage` posts to OpenRouter's `/images` (`model.Client.Image`: `output_format` png, `n` 1, `provider.data_collection: deny`, up to 150s and 24 MB); the core keeps the key, so a feature makes pictures without seeing it, and the cost the endpoint reports is added to the reply whose tool asked, through a tally in the tool loop's ctx, so `DAILY_BUDGET` counts it. `Info.MakesImage` says whether the API can (only OpenRouter's). +- **The model.** A chat completions API in OpenAI's format at `MODEL_API_URL` (OpenRouter's by default, `internal/model`), with `MODEL_API_KEY` as a bearer token if set, over a keep-alive client that requires TLS 1.3 for `https://`. Requests to OpenRouter (host `openrouter.ai`) set `provider.data_collection: deny` and `usage.include` for the real cost, plus the `MODEL_REASONING` effort as `reasoning.effort`; requests elsewhere carry only `reasoning_effort`. Either effort is left out when `MODEL_REASONING` is `none`. The tokens are logged with each reply, and the cost when the API reports it. A network error, 429 or 5xx gets one retry; an error body is reduced to its message ("status N: message"). The tool loop takes at most 5 requests and 3 minutes per reply, and 4 pictures; if a request after a tool made pictures fails, the pictures are the reply, without words, since they may have cost money to make. `Host.CallAPI(ctx, path, body)` lets a tool post to another endpoint of the same API (`model.Client.Call`): the core adds the key, so a feature never sees it, and on OpenRouter `provider.data_collection: deny` (merged into any provider settings the body has); it waits up to 150s for at most 32 MB, retries as other requests do, refuses `/chat/completions` and any path that isn't a plain endpoint, and adds the `usage.cost` the response reports to the reply whose tool called it, through a tally in the tool loop's ctx, so `DAILY_BUDGET` counts it. Outside a tool's Run there is no reply to count it toward, so it refuses. `Info.Provider` is `openrouter` on OpenRouter's API, else empty. - **Edits and deletes.** The network honours deletes and edits exactly as its network's official client would; the core forgets what it is told. The rules, one each: - **Who counts (Signal).** The author's delete or edit, or a group admin's delete of anyone's message. What Signal's app refuses never reaches the bot: signal-cli drops everything from a blocked person or group, group messages from non-members, and admin deletes from non-admins. Signal's time window (the sender's window plus a day) needs no check while history lasts at most 24 hours; a longer history must add it. - **The allowlist never decides it.** `SIGNAL_DM_USER_IDS` says only who the bot answers, as message requests do in the app (which still applies an unaccepted sender's deletes); it is not a block. So someone removed from it still has their deletes and edits honoured. @@ -123,9 +123,10 @@ The core's lifecycle has three stages. Each port is one stage; nothing else is a **Services the host offers:** - `IntroLine(line)`, `IntroLineDM(line)`: a paragraph for the bot's introduction, placed where `INTRO` has `{more}`; with `IntroLineDM`, only in the introduction a DM gets (`Info.IntroDM`, and the prompt's rule in a DM), not a group's (`Info.Intro`). The core pads each with a blank line and never leaves two blank lines in a row. `/schedule` uses it, DM only, for `Type "/schedule" for schedules and reminders.`, since schedules are made only in a DM. +- `CallAPI(ctx, path, body)`: from a tool's Run, post a JSON body to another endpoint of the model's API, such as OpenRouter's `/images`, and get the response; the core keeps the key and the data-collection request, and counts the cost toward the reply (see the model, above). - `Env(key, def)`: a feature's own setting. The docs guardrail finds each name passed to it. - `Store(name)`: the feature's saved state, opened while it registers: one JSON document, `.json` in the state directory (`STATE_DIRECTORY`'s first directory, or the working directory when it isn't set), with `Load(v)` (found is false when nothing is saved yet; a file that can't be read is an error, so the feature can stop the bot rather than overwrite it) and `Save(v)` (written to a temporary file, synced and renamed over the old one, at most 4 MiB, its newline included). The first `Store` call checks that the directory can be listed and written, and fails with how to fix it otherwise (for Docker's `/data`, `chown 65532`; elsewhere, the unit's `StateDirectory`), so a bot whose features save nothing needs no state directory. A name is lowercase letters, digits, `-` and `_`, up to 32, and may be opened once; `budget` is the core's (`budget.json`, written the same way). Features save files only this way (a guardrail below). -- `Info()`: the bot's name, its version, the model ("" with no model), whether it takes images and can call tools, and the names of the tools, as in `{tools}` (none when it can't call tools). All but the name and the tools are known when features register; images and tool calling may turn off later ([Capabilities](#the-core)). +- `Info()`: the bot's name, its version, the model ("" with no model), the API's provider (`openrouter` or ""), whether it takes images and can call tools, and the names of the tools, as in `{tools}` (none when it can't call tools). All but the name and the tools are known when features register; images and tool calling may turn off later ([Capabilities](#the-core)). - `Media(ctx, msg, i)`: the bytes of a message's image or sticker (15s). The core fills in each sticker's `Label` (its emoji and pack title) when it loads the message. - `Deliver(msg)`: act on a message as if its sender had just posted it in its chat, through the chat's mailbox. Inside the message's slot: - it waits up to 10s for the bot to be connected, else it is dropped with a warning; @@ -214,7 +215,7 @@ In `features.go` order, which is the order hooks run in and of the tools line an | `files` | `OnTurn` returning `Files`, `Info`, `Media` | | `links` | `OnTurn` returning `Note` and `Files`, `Info` | | `charts` | `OfferTools` with `Keywords` | -| `imagegen` | `OfferTools` with `Keywords`, `GenerateImage`, `Info` | +| `imagegen` | `OfferTools` with `Keywords`, `CallAPI`, `Info` | | `mcp` | `OfferTools` (one group per server), `Command` returning `ToolChoice`, `Info`, `Redact`, `Go` | | `schedule` | `Command`, `ListCommands`, `IntroLineDM`, `At`, `Deliver`, `Tell`, `Groups`, `Info`, `Store` | @@ -225,7 +226,7 @@ In `features.go` order, which is the order hooks run in and of the tools line an - **`files`** handles each `Media` with `File` set, fetched with `getAttachment`, by its content, extension and declared type. A PDF (`%PDF-`) goes to the model as a `File` when `Info.PDFs`, which the model client sends as a `file` part; on OpenRouter, for a model whose list entry lacks `file`, the request also names the `file-parser` plugin with the `mistral-ocr` engine, named rather than left to OpenRouter's default so what is billed is predictable. Audio goes as an `input_audio` part (format from its type, such as `aac` for Signal's voice notes) when `Info.Audio`. Text (valid UTF-8, no NUL, by type or extension) and docx, xlsx and pptx (text extracted with `archive/zip` and `encoding/xml`; a file is refused before its directory is built if its end record declares over 20,000 entries, each part is read to at most 10 MB and all parts to 32 MB together, past which the text read so far stands, cut, so a deck heavy with shapes is read as far as it goes, and its note says "only the first part of its text is shown, as the file is too big to read whole"; a sheet is headed with its name from `xl/workbook.xml` and its relationships (`Sheet "Budget":`, made one line and cut to 40 characters), else `Sheet N:`; and elements nested past 256 deep, which the decoder keeps a stack of, stop the read) are shown inline in a Markdown fence longer than any backticks in them, capped at 50,000 characters. A file's note says "attached; its text follows" when its text is shown; anything else is noted as one that "can't be read", or one that "couldn't be fetched" or "is no longer available". Each outcome is a value (`outcome`) that builds the whole note, and what history keeps, in one place. Each file is logged by kind and size with what the model got (how many characters of text, a PDF or audio attached, or why not), never its name or declared type; an Office file past the cap is logged as "first 50000 chars of text", since extraction stops there and the document's length is unknown; an Office file that can't be read is logged by the kind of error only (`not a zip`, `missing part`, `bad xml`, `no text`, `too many parts`, `too deep`, `too much xml`, `unreadable`), since the XML decoder's messages quote the document. The core sends at most 16 MB of files with one message, in order (`maxFileBytes`): each goes as base64 in a JSON request, copied a few times on the way, so several large files stay inside the bot's memory; any left out are noted for the model. Names come from the sender, so they are made safe and quoted. History keeps only the notes: for a file the model was shown, `[file "name" was shown to you; it isn't kept, so to see it again they must reply to the message with it and mention you]`. OpenRouter's `annotations` on a reply (such as a parsed PDF) are sent back with it in later tool rounds, so the PDF isn't parsed again within the reply. Each request of a reply is logged at debug level, `request 2: tokens in/out 8120/40, $0.0013, annotations returned: no, sent back: yes, server tools used: no`, with no content (`server tools used` says whether a server tool, such as OpenRouter's web search, ran for that request, seen from a `url_citation` annotation or a use counted in its `server_tool_use`, as a server tool runs on the provider's side and gets no tool line), so the journal shows whether that holds: a later round's cost should be its tokens only, not another ~$0.002 a page. - **`links`** fetches the http and https URLs in the addressed message, then in its quote unless the quote is the bot's own (the model's words), at most 5 a turn (sentence punctuation and unbalanced brackets trimmed, fragments dropped, a URL ending at white space or any Unicode separator, control or format character, any with a user name or password skipped), so only URLs a person sent are ever requested, never one the model or a page names. Only ports 80 and 443 are fetched, on redirects too, so the bot can't be pointed at another service on a host. A link that looks private or one-time isn't requested, and neither is a redirect to one: a query parameter named (lowercased, without - or _) token, accesstoken, authtoken, key, apikey, secret, password, passwd, pwd, sig, signature, otp, sessionid or jwt, or ending in signature or token; or a whole path segment that is unsubscribe, confirm, verify, verification, reset, magic, activate, delete, remove, approve, webhook, webhooks or trigger. Words common in ordinary links (code, session, hash, hooks) and pages harmless to open signed out, as the bot always is (login, logout, oauth), are left out, to avoid skipping ordinary pages. A GET that spends someone's reset, confirmation or unsubscribe link, or sets off a webhook, is the bot carrying out an action for whoever posted it, so these are noted for the model instead. Distinct links past the fifth get one note to the model, not history (which keeps the message, URLs and all), `[1 more link not opened: the bot reads at most 5 a message; send it on its own to have it read]`, and one log line counting them. Each chat can have 20 links fetched an hour, counted in memory by time only, never URL, and forgotten after an hour idle; past that a link's note says `not fetched: this chat has had its 20 links for the hour; links can be read again in about N minutes`, the time until the oldest of them is an hour old, and the log `link not fetched: this chat reached its 20 links an hour`. Its own HTTP client: no proxy; TLS 1.2 or later; 15s in all; at most 3 redirects, each to http or https; the user agent `signalbot (+https://github.com/robdevops/signalbot)`, which names the bot, never the person. HTML is read as a stream of tokens (`html.Tokenizer`), never built into a tree, each text token cut to what the cap can still use, and reading stops at twice the text cap, so a huge page takes little memory. When a redirect changed the URL, the note names where it ended up (`[page , redirected to `), cut to 200 characters and without any user name or password, since the redirecting server chose it. Its dialer's `Control` refuses any address that isn't public, after DNS and for every connection attempt and redirect: unmapped first, it must be global unicast and outside private, shared, loopback, link-local (169.254.169.254 included), documentation, benchmarking, multicast and reserved ranges and the IPv6 ranges that can carry IPv4 (IPv4-compatible and -translated, NAT64, 6to4, Teredo). A page is read to 5 MB (a PDF to 12 MB) and converted to UTF-8 from its declared charset. HTML becomes its title and its text, a line per block, with scripts, navigation, headers, footers, asides and forms left out: the text of its first `article` or `main` element (nested ones included) if that has 200 characters or more, so menus and sidebars of plain `div`s don't crowd out the content, else the whole page's; plain text and JSON are shown as they are; both in a fence, capped at 15,000 characters. A PDF goes to the model as a `File`, like an attached one. Anything else is noted as one that "can't be read", and an error status, a timeout or a refused address as one that "couldn't be fetched", with the reason; a status is said in plain words with its number (401 or 403 "the site refused the request (403); it may need signing in or block bots", 404 or 410 "the page wasn't found (404)", 429 "the site is limiting requests (429); try again later", 5xx "the site had an error (503)", else "the site answered with status N"), the same in the log. Each outcome is a value (`outcome`) that builds the whole note, and what history keeps, in one place. Each link gets one log line: its time, size, its kind (from a fixed list, never the server's own media type) and what came of it (how many characters of text and whether from an `article`, a `main` or the whole page; a PDF attached; no readable text; or why it failed or wasn't fetched), never the URL, title or text. History keeps "[page was shown to you; it isn't kept, so to see it again they must reply to the message with it and mention you]" (`feature.NotKept`, the same ending files and images use). The package's own tests let the dialer reach loopback through an unexported variable; nothing outside it can. - **`charts`** offers `make_chart` and `make_pie_chart` when a message asks for a chart (chart, graph, plot, visualise/visualize, pie, donut and their forms) or for what a line chart shows (projection, forward estimate, trending, forecast and their forms). `make_chart` draws line charts of up to 6 series on one Y axis, set by a top-level `y_axis` (an axis given as just its title, `"y_axis": "…"` or `"axes": {"label": "…"}`, is taken as meant), and refuses a right axis, saying to use change mode for series on different scales. A second axis is only on request: `make_dual_axis_chart`, the same chart with a left and a right Y axis, is a tool group of its own (no `Names`, so the intro is unchanged), offered only when a message asks for one (second, secondary, dual, two, right-hand… axis or axes), and for the replies that follow. Each axis has its own mode (values as given, the default, or % change from each series' first point, for comparing series on different scales such as two stocks), unit, title and optional inversion, and in value mode `show_change`, on unless the model sets it false, which labels each line's last value with its % change from its first point, computed by the bot (nothing from a start of 0 or less). It is on by default because models leave optional settings unset (off by default, it never appeared); the model turns it off where a % change means nothing, such as temperatures, rates or values already in %; a single series is an area, green if it ends up and red if down, with its high, low and current value marked, the change on a line of its own beneath the value; its subtitle is drawn in the line's colour, led by the change with an arrow (`▼ 15.2%`), and the caption is the title with that change in place of the subtitle. An axis sent as a string holding its JSON is decoded as the axis, not taken for a title. `make_pie_chart` draws 2–12 shares of a total as a ring (its description still says donut), largest first, the legend giving each amount and the centre the total, both shortened (K, M, B, T) by the bot; a unit or suffix over 4 characters (such as a word) is dropped rather than cut. Both take an optional `source` (where the data came from, trimmed and capped at 80 characters), written as "Source: …" small and muted at the bottom left and cut with "…" to the chart's width, in a band below the date labels and the legend, whose row gaps shrink to stay above it (and if that is not enough, the smallest slices' labels go back to one line, cut before their amount); it is not in the caption. Charts are 1280×800 PNGs on white (at most 256 colours: anti-aliased shades are grouped and the theme's colours kept exact, for about a third the size), or with `DARKMODE` on (or `true`, `yes`, `1`, `dark`; off is also `false`, `no`, `0`, `light`) in a dark theme (near-black navy, light text, a lighter palette); a range of times (`18:00-6:00`, `18-6`, `6pm-6am`) is dark from its start up to its end, local time (`TZ`), wrapping midnight when the end is earlier, decided as each chart is drawn, and any other value is off with a warning at startup. A reply with a chart is the chart alone, captioned with its title (and subtitle, if both fit on one line) in place of the model's text; history notes it by caption. Arguments sent as a string holding their JSON, whole or for one field (such as `axes` or one series' `points`), are taken as meant, as smaller models often send them; any other mistake is named back to the model, with how to fix it, so it can correct its call. -- **`imagegen`** offers `make_image` when a message asks for a picture (draw, sketch, doodle, paint, illustrate, art, diagram, image, picture, pic, photo, photorealistic, logo, icon, poster, banner, graphic, meme, avatar, pfp, sticker, selfie, cartoon, comic, portrait, wallpaper, render, watercolour, anime, clip art, infographic, mock-up, cutaway, cross-section, schematic, exploded view, blueprint, flowchart, org chart, gantt, mind map, visualise and their forms), if `Info.MakesImage` and `IMAGE_MODEL` isn't off. The model writes the full prompt, an aspect ratio of seven (1:1 by default), a title for the file name, and a `kind`: `technical` (a diagram, cutaway, schematic, infographic, labelled or educational picture) or `artistic`. For `technical` it also lists up to 12 `requirements`, the facts the picture must get right, worked out before it writes the prompt, and the prompt the image model gets is a fixed brief (a teaching picture that must be accurate, in the style asked for, else a clean technical look) then the model's prompt, the requirements as must-haves, and rules for text (only the words given, labels, title or caption, spelled exactly, short and legible; no invented numbers; arrows exactly as described); an `artistic` prompt goes unchanged; the picture comes from `GenerateImage` with `IMAGE_MODEL` (default `openai/gpt-image-2`) at `IMAGE_QUALITY` (default `medium`; anything but low, medium, high or auto stops the bot), goes through `img.Fit`, and is sent with the model's words, no caption. History notes `[sent a picture made from the prompt: …]`, up to 400 characters of it; a technical one `[sent a technical picture made from the prompt: …]`, up to 1,200, and its requirements, so a follow-up ("add the other planets") keeps them: the description tells the model to start a change from that note, keeping the kind and every requirement. A failure tells the model in a few fixed words (refused under the content policy, out of credit, rate-limited, too slow, or failed), never the API's text. +- **`imagegen`** offers `make_image` when a message asks for a picture (draw, sketch, doodle, paint, illustrate, art, diagram, image, picture, pic, photo, photorealistic, logo, icon, poster, banner, graphic, meme, avatar, pfp, sticker, selfie, cartoon, comic, portrait, wallpaper, render, watercolour, anime, clip art, infographic, mock-up, cutaway, cross-section, schematic, exploded view, blueprint, flowchart, org chart, gantt, mind map, visualise and their forms), if `Info.Provider` is `openrouter` and `IMAGE_MODEL` isn't off. The model writes the full prompt, an aspect ratio of seven (1:1 by default), a title for the file name, and a `kind`: `technical` (a diagram, cutaway, schematic, infographic, labelled or educational picture) or `artistic`. For `technical` it also lists up to 12 `requirements`, the facts the picture must get right, worked out before it writes the prompt, and the prompt the image model gets is a fixed brief (a teaching picture that must be accurate, in the style asked for, else a rich infographic: bold title, detailed main illustration, colour-coded sections, icons, callouts with the given facts and figures, a legend) then the model's prompt, the requirements as must-haves, and rules for text (only the words given, labels, title or caption, spelled exactly, short and legible; no invented numbers; arrows exactly as described); an `artistic` prompt goes unchanged; the feature posts the request to `/images` itself through `CallAPI` (one PNG, `n` 1) with `IMAGE_MODEL` (default `openai/gpt-image-2`) at `IMAGE_QUALITY` (default `medium`; anything but low, medium, high or auto stops the bot), goes through `img.Fit`, and is sent with the model's words, no caption. History notes `[sent a picture made from the prompt: …]`, up to 400 characters of it; a technical one `[sent a technical picture made from the prompt: …]`, up to 1,200, and its requirements, so a follow-up ("add the other planets") keeps them: the description tells the model to start a change from that note, keeping the kind and every requirement. A failure tells the model in a few fixed words (refused under the content policy, out of credit, rate-limited, too slow, or failed), never the API's text. - **`mcp`** (`MCP_CONFIG`; `${NAME}` in a server's `url`, `headers`, `args` or `env` is the bot's environment variable `NAME`, filled in at startup, and one that isn't set is a startup error naming the variable, never its value) connects to MCP servers: remote ones (`url`, `headers`) over Streamable HTTP (JSON or server-sent events, with the session re-established if the server forgets it) and local ones (`command`, `args`, `env`) over stdio (restarted with backoff if they exit, given only `PATH`, `HOME` and their `env`, and stopped when the bot stops; each line a local server writes to stderr is logged at debug only after `Redact`). It identifies itself in the handshake as `signalbot` with the bot's version (`Info.Version`, or `dev`). A server with `disabled` is skipped unchecked; one that can't be reached is logged and left out. At startup it logs each server's tools, one line per server (" MCP: …", the server's name alone when it already says MCP, as in the intro), and the chat commands ("chat commands: …"). - Each server is one tool group, listed as `server: tool, …, /command`. In the intro's `{tools}` and the prompt's `If asked what tools you have:` list its label is `**server MCP**: tool, …, /command`, without the added ` MCP` when the server's name already contains MCP in any case. `allowed_tools` or `blocked_tools` decide its tools (a name in either that the server lacks stops the bot), named `server__tool` for the model. `instructions` is its system-prompt line while offered: the config's if set (even to `""`), otherwise the `instructions` the server sent in the MCP handshake, capped at 1,000 characters. `keywords` (whole words, any case) gate it like the chart tools. - Each call has 30s (past that the model is told "the tool didn't answer within 30s; try a narrower request or later") and its text result is capped at 16K characters; images in a result are sent with the reply, up to 4. Tool results are untrusted input to the model, like a quote. Only the question and the final answer go into history; arguments and results are never logged. diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index db3059c..7cff73c 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -28,7 +28,7 @@ A message that addresses the bot and has a URL, or replies to a message with one ## Images -Asked for a picture (a drawing, painting, sketch, illustration, art in any style, a diagram, a logo, an icon, a poster, a cartoon), the model can make one with an image model on OpenRouter: [GPT Image 2](https://openrouter.ai/openai/gpt-image-2) by default (`IMAGE_MODEL`), at `IMAGE_QUALITY` (default `medium`). The model writes the whole prompt itself, as the image model sees nothing else, and the picture is sent with its reply. It says whether the picture is technical (a diagram, cutaway, cross-section, schematic, infographic, or a labelled, how-it-works or educational picture) or artistic. For a technical one it first works out the facts the picture must get right (what each label says and points to, which way arrows point, angles, counts, order) and lists them; the bot then asks the image model for an accurate picture in whatever style was asked for (a clean technical look if none), with those facts as must-haves and rules for short, exact text and nothing invented. An artistic prompt goes as the model wrote it. History keeps a note of the prompt, not the picture, and for a technical picture its requirements too, so "make it bluer" or "add the other planets" works by the model writing a new prompt that keeps them (still to scale, say). A chart of data is still the chart tools' job: the image tool's description says so. The tool is offered only on messages with words such as draw, sketch, paint, illustrate, art, diagram, cutaway, cross-section, schematic, exploded view, blueprint, flowchart, org chart, mind map, visualise, image, picture, photo, logo, icon, poster, banner, meme, avatar, cartoon or render, then for `TOOL_LINGER_ROUNDS` more replies; with words both share, such as visualise or org chart, both it and the charts are offered and the model picks. It makes new pictures only: it can't edit one you send. If the model's reply fails after a picture is made, the picture is sent alone. Each picture's cost (logged with the reply) counts toward `DAILY_BUDGET`. Only OpenRouter's API makes pictures; with another, or `IMAGE_MODEL=off`, the tool isn't offered. A prompt the image model's provider refuses under its content policy is reported to the user as such; other failures as the service failing. +Asked for a picture (a drawing, painting, sketch, illustration, art in any style, a diagram, a logo, an icon, a poster, a cartoon), the model can make one with an image model on OpenRouter: [GPT Image 2](https://openrouter.ai/openai/gpt-image-2) by default (`IMAGE_MODEL`), at `IMAGE_QUALITY` (default `medium`). The model writes the whole prompt itself, as the image model sees nothing else, and the picture is sent with its reply. It says whether the picture is technical (a diagram, cutaway, cross-section, schematic, infographic, or a labelled, how-it-works or educational picture) or artistic. For a technical one it first works out the facts the picture must get right (what each label says and points to, which way arrows point, angles, counts, order) and lists them; the bot then asks the image model for an accurate picture in whatever style was asked for, or if none a rich infographic (a bold title, a detailed main illustration, colour-coded sections, icons, callouts with the facts and figures, a legend), with those facts as must-haves and rules for short, exact text and nothing invented. An artistic prompt goes as the model wrote it. History keeps a note of the prompt, not the picture, and for a technical picture its requirements too, so "make it bluer" or "add the other planets" works by the model writing a new prompt that keeps them (still to scale, say). A chart of data is still the chart tools' job: the image tool's description says so. The tool is offered only on messages with words such as draw, sketch, paint, illustrate, art, diagram, cutaway, cross-section, schematic, exploded view, blueprint, flowchart, org chart, mind map, visualise, image, picture, photo, logo, icon, poster, banner, meme, avatar, cartoon or render, then for `TOOL_LINGER_ROUNDS` more replies; with words both share, such as visualise or org chart, both it and the charts are offered and the model picks. It makes new pictures only: it can't edit one you send. If the model's reply fails after a picture is made, the picture is sent alone. Each picture's cost (logged with the reply) counts toward `DAILY_BUDGET`. Only OpenRouter's API makes pictures; with another, or `IMAGE_MODEL=off`, the tool isn't offered. A prompt the image model's provider refuses under its content policy is reported to the user as such; other failures as the service failing. ## How tools are offered diff --git a/internal/arch/arch_test.go b/internal/arch/arch_test.go index d29d630..75c1bfd 100644 --- a/internal/arch/arch_test.go +++ b/internal/arch/arch_test.go @@ -82,7 +82,7 @@ func TestImports(t *testing.T) { } // featureWords are the names of features and words only they use. -var featureWords = regexp.MustCompile(`(?i)chart|donut|\bpies?\b|mcp|groupctx|group.?context|websearch|web.?search|\bvision\b|/intro|/schedule`) +var featureWords = regexp.MustCompile(`(?i)chart|donut|\bpies?\b|mcp|groupctx|group.?context|websearch|web.?search|\bvision\b|/intro|/schedule|imagegen|make_image|gpt-image`) // The core never mentions a feature, so deleting one leaves it unchanged. // The scenarios at the module root test the whole bot, features included. diff --git a/internal/bot/host.go b/internal/bot/host.go index ab25a6a..08f9d35 100644 --- a/internal/bot/host.go +++ b/internal/bot/host.go @@ -3,6 +3,7 @@ package bot import ( "cmp" "context" + "encoding/json" "errors" "fmt" "slices" @@ -93,16 +94,16 @@ func (b *Bot) Info() feature.Info { if b.ai == nil { info.Model = "" } else { - info.MakesImage = b.ai.ReportsCost() // OpenRouter's API, which has an images endpoint + info.Provider = b.ai.Provider() } return info } -func (b *Bot) GenerateImage(ctx context.Context, r feature.ImageRequest) ([]byte, error) { +func (b *Bot) CallAPI(ctx context.Context, path string, body map[string]any) (json.RawMessage, error) { if b.ai == nil { return nil, errors.New("no model") } - return b.ai.Image(ctx, r) + return b.ai.Call(ctx, path, body) } func (b *Bot) Go(fn func(context.Context)) { diff --git a/internal/feature/feature.go b/internal/feature/feature.go index a23649e..17df3c7 100644 --- a/internal/feature/feature.go +++ b/internal/feature/feature.go @@ -137,14 +137,6 @@ type Picture struct { HistoryNote string // what history keeps of it; "" keeps "[sent an image]" } -// ImageRequest asks for an image to be made from a prompt. -type ImageRequest struct { - Model string // the image model's ID at the API, such as "openai/gpt-image-2" - Prompt string - AspectRatio string // such as "1:1" or "16:9"; "" lets the model choose - Quality string // "low", "medium", "high" or "auto"; "" is the API's default -} - // ToolGroup is a set of tools offered to the model together. One with no // Tools, only Names, such as a feature's chat commands, is named only in // the prompt's list of what the bot has, not in the intro's {tools}. @@ -178,7 +170,7 @@ type Info struct { Audio bool // the model takes audio PDFs bool // the model's API takes PDFs CallsTools bool // the model can call tools - MakesImage bool // the API can make an image from a prompt (GenerateImage): OpenRouter's + Provider string // the model API's provider, as server tools name it: "openrouter", or "" for another Tools []string // the Names of every tool group with tools, in feature order; none when it can't call tools Intro string // INTRO with {name}, {model}, {tools} and {more} filled in, as in a group IntroDM string // the same in a DM, with IntroLine's DM-only lines too @@ -256,11 +248,12 @@ type Host interface { Tell(user, text string) // Groups lists the groups the bot shares with user. Groups(ctx context.Context, user string) ([]Group, error) - // GenerateImage makes an image from a prompt with the model's API, and - // returns its bytes. What it cost counts toward the chat's daily budget - // when called from a tool's Run. It fails when Info().MakesImage is - // false. - GenerateImage(ctx context.Context, r ImageRequest) ([]byte, error) + // CallAPI posts body as JSON to path (such as "/images") at the model's + // API and returns the response body, from a tool's Run only, so what it + // cost counts toward the reply and the chat's daily budget. The core + // adds the key, and on OpenRouter asks for providers that don't collect + // the data; a feature never sees the key. + CallAPI(ctx context.Context, path string, body map[string]any) (json.RawMessage, error) // Redact replaces every name and ID of anyone but the bot in text with // "redacted", for logging text the bot doesn't control. Redact(text string) string diff --git a/internal/feature/featuretest/featuretest.go b/internal/feature/featuretest/featuretest.go index 062c6eb..63116b8 100644 --- a/internal/feature/featuretest/featuretest.go +++ b/internal/feature/featuretest/featuretest.go @@ -4,6 +4,7 @@ package featuretest import ( "context" + "encoding/json" "errors" "slices" "strings" @@ -17,15 +18,15 @@ import ( // Host records what a feature registers and lets a test drive it. Set its // exported fields before the feature registers. type Host struct { - Settings map[string]string // what Env reads - Bot feature.Info // what Info returns - Fetch func(m feature.Message, i int) ([]byte, error) // what Media returns; nil fails - Image func(context.Context, feature.ImageRequest) ([]byte, error) // what GenerateImage returns; nil fails - Shared []feature.Group // what Groups returns - TimerErr error // if set, At fails with it, as the core does at its cap - Redactor func(string) string // what Redact does; nil leaves text as it is - StoreErr error // if set, Store fails with it, as the core does with no usable state directory - Unusable bool // if set, OfferTools drops a group with tools, as the core does when the API can run none + Settings map[string]string // what Env reads + Bot feature.Info // what Info returns + Fetch func(m feature.Message, i int) ([]byte, error) // what Media returns; nil fails + API func(ctx context.Context, path string, body map[string]any) (json.RawMessage, error) // what CallAPI returns; nil fails + Shared []feature.Group // what Groups returns + TimerErr error // if set, At fails with it, as the core does at its cap + Redactor func(string) string // what Redact does; nil leaves text as it is + StoreErr error // if set, Store fails with it, as the core does with no usable state directory + Unusable bool // if set, OfferTools drops a group with tools, as the core does when the API can run none mu sync.Mutex read []string @@ -159,12 +160,12 @@ func (h *Host) Env(key, def string) string { func (h *Host) Info() feature.Info { return h.Bot } -// GenerateImage returns what Image does; nil fails. -func (h *Host) GenerateImage(ctx context.Context, r feature.ImageRequest) ([]byte, error) { - if h.Image == nil { - return nil, errors.New("no image") +// CallAPI returns what API does; nil fails. +func (h *Host) CallAPI(ctx context.Context, path string, body map[string]any) (json.RawMessage, error) { + if h.API == nil { + return nil, errors.New("no API") } - return h.Image(ctx, r) + return h.API(ctx, path, body) } // Store opens a saved state as the core does, in the directory diff --git a/internal/features/imagegen/imagegen.go b/internal/features/imagegen/imagegen.go index 037ce3a..02fce27 100644 --- a/internal/features/imagegen/imagegen.go +++ b/internal/features/imagegen/imagegen.go @@ -3,7 +3,9 @@ package imagegen import ( + "cmp" "context" + "encoding/base64" "encoding/json" "errors" "fmt" @@ -45,7 +47,9 @@ const description = "Make a picture from a text prompt with an image model, and "labelled or how-it-works illustration; artistic for anything else, such as art, a scene, a portrait, a logo or a meme. " + "For technical, first work out the facts yourself, as an expert would check them, then list each one the picture must get right in requirements: " + "what every label says and exactly what it points to, which way each arrow points and what it means, angles, counts, order, " + - "what is perpendicular, parallel, above or inside what. Keep labels few and short; name every box, label and arrow in the prompt and how they connect. " + + "what is perpendicular, parallel, above or inside what. Unless the user names a style, plan a rich infographic: a title, the main illustration, " + + "three to six short callouts with key facts and figures, and a legend; give every word and number it should show, as the image model invents none, " + + "and name every box, label and arrow and how they connect. " + "Make one picture per call, and at most 4 in a reply. It can't see or change a picture the user sent: it only makes a new one from your words. " + "To change a picture you made, start from its note in the conversation: keep its kind and every requirement, add the change, and rewrite the whole prompt. " + "After it is made, reply in one short sentence, or not at all: don't describe the picture back." @@ -62,8 +66,9 @@ var schema = json.RawMessage(`{"type":"object","properties":{` + // it: image models favour looks over accuracy unless told otherwise. const ( technicalBrief = "A picture that teaches, so it must be accurate: draw exactly what is described, and nothing that contradicts it. " + - "Keep any style the description asks for, but never at the cost of accuracy; if it names none, use a clean, uncluttered layout " + - "with room around each part, consistent line weights and high contrast. " + + "Keep any style the description asks for, but never at the cost of accuracy; if it names none, make it a rich, polished infographic: " + + "a bold title, a detailed main illustration with depth and texture, colour-coded sections, icons, callout boxes with the facts and figures given, " + + "and a small legend, in a clear visual hierarchy where every part stays legible. " + "Draw each thing once; things too close to tell apart at the picture's scale share one mark and one label, with an inset if they must be shown apart." textRules = "Text: only the words given above (labels, any title or caption), spelled exactly, each short, large and legible, " + "a label placed next to what it names with a leader line if needed, and each label exactly once. No other text, no placeholder text, no invented numbers or values. " + @@ -95,7 +100,7 @@ func Register(h feature.Host) error { return nil case info.Model == "": return nil - case !info.MakesImage: + case info.Provider != "openrouter": logx.Infof("images: off, as only OpenRouter's API makes them") return nil case !slices.Contains([]string{"low", "medium", "high", "auto"}, quality): @@ -162,7 +167,8 @@ func run(h feature.Host, model, quality string) func(context.Context, string) (s a.AspectRatio = "" } a.Prompt = txt.Clamp(a.Prompt, maxPrompt) - data, err := h.GenerateImage(ctx, feature.ImageRequest{Model: model, Prompt: imagePrompt(a), AspectRatio: a.AspectRatio, Quality: quality}) + logx.Infof("image asked: %s, %d requirements, %s", cmp.Or(a.Kind, "no kind"), len(a.Requirements), cmp.Or(a.AspectRatio, "model's ratio")) // never the prompt + data, err := generate(ctx, h, model, quality, a.AspectRatio, imagePrompt(a)) if err != nil { return "error: the image could not be made (" + reason(err) + "). Tell the user, briefly.", nil, err } @@ -175,6 +181,27 @@ func run(h feature.Host, model, quality string) func(context.Context, string) (s } } +// generate asks OpenRouter's images endpoint for one PNG and returns it. +func generate(ctx context.Context, h feature.Host, model, quality, ratio, prompt string) ([]byte, error) { + body := map[string]any{"model": model, "prompt": prompt, "n": 1, "output_format": "png", "quality": quality} + if ratio != "" { + body["aspect_ratio"] = ratio + } + data, err := h.CallAPI(ctx, "/images", body) + if err != nil { + return nil, err + } + var res struct { + Data []struct { + B64 string `json:"b64_json"` + } `json:"data"` + } + if json.Unmarshal(data, &res) != nil || len(res.Data) == 0 || res.Data[0].B64 == "" { + return nil, errors.New("no image in the response") + } + return base64.StdEncoding.DecodeString(res.Data[0].B64) +} + // historyNote is what history keeps of a picture, so a change asked for // later can build on it: the prompt, and for a technical picture its kind // and requirements too, which a follow-up must keep (such as "to scale"). diff --git a/internal/features/imagegen/imagegen_test.go b/internal/features/imagegen/imagegen_test.go index cbaf68b..1949c00 100644 --- a/internal/features/imagegen/imagegen_test.go +++ b/internal/features/imagegen/imagegen_test.go @@ -3,7 +3,10 @@ package imagegen import ( "bytes" "context" + "encoding/base64" + "encoding/json" "errors" + "fmt" "image" "image/color" "image/png" @@ -30,7 +33,7 @@ func pngBytes(t *testing.T) []byte { // host is a host whose API makes images, with settings. func host(settings map[string]string) *featuretest.Host { h := featuretest.New() - h.Bot = feature.Info{Model: "x/model", CallsTools: true, MakesImage: true} + h.Bot = feature.Info{Model: "x/model", CallsTools: true, Provider: "openrouter"} for k, v := range settings { h.Settings[k] = v } @@ -79,7 +82,7 @@ func TestOff(t *testing.T) { "no model": func() *featuretest.Host { h := host(nil); h.Bot.Model = ""; return h }(), "other API": func() *featuretest.Host { h := host(nil) - h.Bot.MakesImage = false + h.Bot.Provider = "" return h }(), } { @@ -98,18 +101,18 @@ func TestRun(t *testing.T) { var logs logx.Buffer defer logx.SetOutput(&logs, &logs, false)() h := host(map[string]string{"IMAGE_MODEL": "x/painter", "IMAGE_QUALITY": "high"}) - var got feature.ImageRequest - h.Image = func(_ context.Context, r feature.ImageRequest) ([]byte, error) { - got = r - return pngBytes(t), nil - } + var got req + h.API = answering(t, pngBytes(t), &got, nil) Register(h) run := h.ToolGroups()[0].Tools[0].Run out, pics, err := run(context.Background(), `{"prompt":" a fox in the snow ","aspect_ratio":"16:9","title":"Snow fox"}`) if err != nil || len(pics) != 1 || !strings.Contains(out, "attached") { t.Fatalf("%q %v %v", out, pics, err) } - if got != (feature.ImageRequest{Model: "x/painter", Prompt: "a fox in the snow", AspectRatio: "16:9", Quality: "high"}) { + if !strings.Contains(logs.String(), "image asked: no kind, 0 requirements, 16:9") || strings.Contains(logs.String(), "fox") { + t.Errorf("log %q", logs.String()) + } + if got != (req{Path: "/images", Model: "x/painter", Prompt: "a fox in the snow", AspectRatio: "16:9", Quality: "high"}) { t.Errorf("asked %+v", got) } if p := pics[0]; p.Name != "Snow fox" || p.Caption != "" || p.HistoryNote != "[sent a picture made from the prompt: a fox in the snow]" || !bytes.Equal(p.Data, pngBytes(t)) { @@ -133,7 +136,7 @@ func TestRun(t *testing.T) { func TestRunFails(t *testing.T) { h := host(nil) var fail error - h.Image = func(context.Context, feature.ImageRequest) ([]byte, error) { return nil, fail } + h.API = answering(t, nil, nil, &fail) Register(h) run := h.ToolGroups()[0].Tools[0].Run for e, want := range map[string]string{ @@ -148,7 +151,8 @@ func TestRunFails(t *testing.T) { t.Errorf("%s: %q", e, out) } } - h.Image = func(context.Context, feature.ImageRequest) ([]byte, error) { return []byte("not an image"), nil } + fail = nil + h.API = answering(t, []byte("not an image"), nil, &fail) if out, pics, err := run(context.Background(), `{"prompt":"x"}`); err == nil || pics != nil { t.Errorf("not an image: %q", out) } @@ -158,11 +162,8 @@ func TestRunFails(t *testing.T) { // first, with its requirements listed; an artistic one goes as written. func TestTechnicalPrompt(t *testing.T) { h := host(nil) - var got feature.ImageRequest - h.Image = func(_ context.Context, r feature.ImageRequest) ([]byte, error) { - got = r - return pngBytes(t), nil - } + var got req + h.API = answering(t, pngBytes(t), &got, nil) Register(h) run := h.ToolGroups()[0].Tools[0].Run run(context.Background(), `{"prompt":"a cutaway of a stereo record groove","kind":"technical",`+ @@ -191,3 +192,25 @@ func TestTechnicalPrompt(t *testing.T) { } } } + +// req is what an image request asked for. +type req struct{ Path, Model, Prompt, AspectRatio, Quality string } + +// answering is a fake model API that records an image request in got and +// answers it as OpenRouter's images endpoint does with data, or fails with +// *fail. +func answering(t *testing.T, data []byte, got *req, fail *error) func(context.Context, string, map[string]any) (json.RawMessage, error) { + return func(_ context.Context, path string, body map[string]any) (json.RawMessage, error) { + if got != nil { + s := func(k string) string { v, _ := body[k].(string); return v } + *got = req{path, s("model"), s("prompt"), s("aspect_ratio"), s("quality")} + if body["n"] != 1 || body["output_format"] != "png" { + t.Errorf("body %v", body) + } + } + if fail != nil && *fail != nil { + return nil, *fail + } + return json.RawMessage(fmt.Sprintf(`{"created":1,"data":[{"b64_json":%q}],"usage":{"cost":0.04}}`, base64.StdEncoding.EncodeToString(data))), nil + } +} diff --git a/internal/model/model.go b/internal/model/model.go index 0beb38d..5bc52bb 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -11,8 +11,10 @@ import ( "errors" "fmt" "io" + "maps" "net/http" "net/url" + "regexp" "slices" "strings" "sync" @@ -369,58 +371,73 @@ func (s *spend) take() (float64, bool) { return c, ok } -// maxImage caps an image the API returns, base64 and all. -const maxImage = 24 << 20 +// maxCall caps a Call's response, and callWait how long it may take. +const ( + maxCall = 32 << 20 + callWait = 150 * time.Second +) -// Image makes an image with OpenRouter's images endpoint, from providers -// that don't collect the data, and returns its bytes. Its cost is added to -// the Ask whose tool called it. -func (c *Client) Image(ctx context.Context, r feature.ImageRequest) ([]byte, error) { - if !c.openRouter { - return nil, errors.New("image generation needs OpenRouter's API") - } - body := map[string]any{"model": r.Model, "prompt": r.Prompt, "n": 1, "output_format": "png", - "provider": map[string]string{"data_collection": "deny"}} - if r.AspectRatio != "" { - body["aspect_ratio"] = r.AspectRatio +// apiPath is a path a Call may post to: an endpoint of the API, no query. +var apiPath = regexp.MustCompile(`^(/[a-z0-9_-]+)+$`) + +// Provider is the API's provider as server tools name it: "openrouter", +// or "" for another API. +func (c *Client) Provider() string { + if c.openRouter { + return "openrouter" } - if r.Quality != "" { - body["quality"] = r.Quality + return "" +} + +// Call posts body to path at the API, for a tool, and returns the +// response. On OpenRouter it asks for providers that don't collect the +// data, as every request does; the cost the response reports is added to +// the reply of the Ask whose tool called it. Outside a tool there is no +// reply to count it toward, so it refuses. +func (c *Client) Call(ctx context.Context, path string, body map[string]any) (json.RawMessage, error) { + if _, ok := ctx.Value(spendKey{}).(*spend); !ok { + return nil, errors.New("the model's API is called only from a tool") + } + if !apiPath.MatchString(path) || path == "/chat/completions" { + return nil, fmt.Errorf("not an endpoint a tool may call: %q", path) + } + body = maps.Clone(body) + if body == nil { + body = map[string]any{} + } + if c.openRouter { + p := map[string]any{} // the body's provider settings, of whatever Go type, as a JSON object + if v, ok := body["provider"]; ok && v != nil { + raw, err := json.Marshal(v) + if err != nil || json.Unmarshal(raw, &p) != nil || p == nil { + return nil, errors.New("provider must be a JSON object") + } + } + p["data_collection"] = "deny" + body["provider"] = p } payload, err := json.Marshal(body) if err != nil { return nil, err } start := time.Now() - data, err := c.postTo(ctx, "/images", payload, 150*time.Second, maxImage) + data, err := c.postTo(ctx, path, payload, callWait, maxCall) if err != nil { return nil, err } - var res struct { - Data []struct { - B64 string `json:"b64_json"` - } `json:"data"` + var usage struct { Usage struct { Cost *float64 `json:"cost"` } `json:"usage"` } - if err := json.Unmarshal(data, &res); err != nil { - return nil, errors.New("unreadable image response") - } + json.Unmarshal(data, &usage) // a response without usage costs nothing known cost := 0.0 - if res.Usage.Cost != nil { - cost = *res.Usage.Cost - } - addSpend(ctx, cost, res.Usage.Cost != nil) - if len(res.Data) == 0 || res.Data[0].B64 == "" { - return nil, errors.New("no image in the response") - } - img, err := base64.StdEncoding.DecodeString(res.Data[0].B64) - if err != nil { - return nil, errors.New("undecodable image") + if usage.Usage.Cost != nil { + cost = *usage.Usage.Cost } - logx.Infof("image %.1fs, %d KB, $%.3f", time.Since(start).Seconds(), len(img)>>10, cost) - return img, nil + addSpend(ctx, cost, usage.Usage.Cost != nil) + logx.Infof("api %s %.1fs, %d KB, $%.3f", path, time.Since(start).Seconds(), len(data)>>10, cost) + return data, nil } // rejected is err as ErrImages if the first request carried images and an diff --git a/internal/model/model_test.go b/internal/model/model_test.go index 2023db2..20a5dbb 100644 --- a/internal/model/model_test.go +++ b/internal/model/model_test.go @@ -3,7 +3,6 @@ package model import ( "context" "crypto/tls" - "encoding/base64" "encoding/json" "errors" "fmt" @@ -638,33 +637,30 @@ func TestRetryDelay(t *testing.T) { } } -// An image is made at OpenRouter's images endpoint, from providers that -// don't collect the data, and what it cost counts toward the reply that -// asked for it. -func TestImage(t *testing.T) { +// A tool calls an endpoint of the API through Call: the core adds the key, +// and on OpenRouter asks for providers that don't collect the data, keeping +// any other provider settings; the cost the response reports counts toward +// the reply. Outside a tool, or at a path that isn't an endpoint, it +// refuses; on another API the request goes as given. +func TestCall(t *testing.T) { var logs logx.Buffer t.Cleanup(logx.SetOutput(&logs, &logs, false)) - png := []byte("\x89PNG\r\n\x1a\nfake") var mu sync.Mutex var chat int - var imageBody map[string]any + var called map[string]any srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { b, _ := io.ReadAll(r.Body) mu.Lock() defer mu.Unlock() switch r.URL.Path { case "/images": - json.Unmarshal(b, &imageBody) - if string(b) == "" || r.Header.Get("Authorization") != "Bearer or-key" { + called = nil + json.Unmarshal(b, &called) + if r.Header.Get("Authorization") != "Bearer or-key" { w.WriteHeader(401) return } - if p, _ := imageBody["prompt"].(string); p == "refuse" { - w.WriteHeader(400) - io.WriteString(w, `{"error":{"code":400,"message":"Your request was rejected by the safety system"}}`) - return - } - fmt.Fprintf(w, `{"created":1,"data":[{"b64_json":%q}],"usage":{"cost":0.04}}`, base64.StdEncoding.EncodeToString(png)) + io.WriteString(w, `{"created":1,"data":[{"b64_json":"cG5n"}],"usage":{"cost":0.04}}`) case "/chat/completions": chat++ if chat == 1 { @@ -676,32 +672,54 @@ func TestImage(t *testing.T) { })) t.Cleanup(srv.Close) c := client(t, srv.URL, true) - var got []byte + var got json.RawMessage draw := feature.Tool{Name: "draw", Run: func(ctx context.Context, _ string) (string, []feature.Picture, error) { - data, err := c.Image(ctx, feature.ImageRequest{Model: "openai/gpt-image-2", Prompt: "a red panda", AspectRatio: "16:9", Quality: "medium"}) - got = data + var err error + got, err = c.Call(ctx, "/images", map[string]any{"model": "x/painter", "prompt": "a red panda", "provider": map[string]any{"order": []string{"a"}}}) return "made", nil, err }} r, err := c.Ask(context.Background(), Request{Text: "draw a red panda", Tools: []feature.Tool{draw}}) - if err != nil || string(got) != string(png) { - t.Fatalf("got %q, %v", got, err) + if err != nil || !strings.Contains(string(got), `"b64_json":"cG5n"`) { + t.Fatalf("got %s, %v", got, err) } if r.Cost < 0.0429 || r.Cost > 0.0431 || !r.Costed { t.Errorf("cost %v", r.Cost) } - want := map[string]any{"model": "openai/gpt-image-2", "prompt": "a red panda", "aspect_ratio": "16:9", "quality": "medium", "n": float64(1), - "output_format": "png", "provider": map[string]any{"data_collection": "deny"}} - if !reflect.DeepEqual(imageBody, want) { - t.Errorf("image request %v", imageBody) + want := map[string]any{"model": "x/painter", "prompt": "a red panda", "provider": map[string]any{"order": []any{"a"}, "data_collection": "deny"}} + if !reflect.DeepEqual(called, want) { + t.Errorf("request %v", called) } - if l := logs.String(); !strings.Contains(l, "$0.043") || strings.Contains(l, "red panda") { + if l := logs.String(); !strings.Contains(l, "api /images ") || !strings.Contains(l, "$0.043") || strings.Contains(l, "red panda") { t.Errorf("logged %q", l) } - if _, err := c.Image(context.Background(), feature.ImageRequest{Model: "m", Prompt: "refuse"}); err == nil || !strings.Contains(err.Error(), "status 400: Your request was rejected by the safety system") { - t.Errorf("refusal: %v", err) + if _, err := c.Call(context.Background(), "/images", map[string]any{}); err == nil { + t.Error("called outside a tool") + } + inTool := context.WithValue(context.Background(), spendKey{}, &spend{}) + for _, path := range []string{"/chat/completions", "images", "/images?x=1", "/../keys", ""} { + if _, err := c.Call(inTool, path, map[string]any{}); err == nil { + t.Errorf("called %q", path) + } + } + // Provider settings of any Go type keep theirs; a nil body is an empty + // one; a provider that isn't an object is refused. + type prefs struct { + Order []string `json:"order"` + } + c.Call(inTool, "/images", map[string]any{"provider": prefs{[]string{"b"}}}) + if p, _ := called["provider"].(map[string]any); !reflect.DeepEqual(p, map[string]any{"order": []any{"b"}, "data_collection": "deny"}) { + t.Errorf("provider %v", called["provider"]) + } + if _, err := c.Call(inTool, "/images", nil); err != nil || !reflect.DeepEqual(called, map[string]any{"provider": map[string]any{"data_collection": "deny"}}) { + t.Errorf("nil body: %v, sent %v", err, called) + } + if _, err := c.Call(inTool, "/images", map[string]any{"provider": "allow"}); err == nil { + t.Error("a provider that isn't an object was sent") } - if _, err := client(t, srv.URL, false).Image(context.Background(), feature.ImageRequest{Model: "m", Prompt: "x"}); err == nil { - t.Error("made an image on another API") + other := client(t, srv.URL, false) + other.Call(inTool, "/images", map[string]any{"model": "m"}) + if _, ok := called["provider"]; ok || other.Provider() != "" || c.Provider() != "openrouter" { + t.Errorf("another API got %v", called) } }