Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
9 changes: 5 additions & 4 deletions TECHNICAL.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/FILES_LINKS_TOOLS_MCP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion internal/arch/arch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 4 additions & 3 deletions internal/bot/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package bot
import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"slices"
Expand Down Expand Up @@ -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)) {
Expand Down
21 changes: 7 additions & 14 deletions internal/feature/feature.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
29 changes: 15 additions & 14 deletions internal/feature/featuretest/featuretest.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package featuretest

import (
"context"
"encoding/json"
"errors"
"slices"
"strings"
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
37 changes: 32 additions & 5 deletions internal/features/imagegen/imagegen.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
package imagegen

import (
"cmp"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -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."
Expand All @@ -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. " +
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
}
Expand All @@ -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").
Expand Down
Loading
Loading