diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 768aacb..188ccfe 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -21,7 +21,7 @@
"name": "fxtr",
"source": "./plugins/fxtr",
"description": "Skills for writing, running, and viewing fxtr experiments, and for calling models from them with behaviors",
- "version": "0.1.4",
+ "version": "0.1.5",
"author": {
"name": "TransluceAI"
},
diff --git a/plugins/fxtr/.claude-plugin/plugin.json b/plugins/fxtr/.claude-plugin/plugin.json
index 1c979f2..86af4c0 100644
--- a/plugins/fxtr/.claude-plugin/plugin.json
+++ b/plugins/fxtr/.claude-plugin/plugin.json
@@ -4,5 +4,5 @@
"author": {
"name": "TransluceAI"
},
- "version": "0.1.4"
+ "version": "0.1.5"
}
diff --git a/plugins/fxtr/skills/behaviors/SKILL.md b/plugins/fxtr/skills/behaviors/SKILL.md
index 6a0fcc9..b8ab5b8 100644
--- a/plugins/fxtr/skills/behaviors/SKILL.md
+++ b/plugins/fxtr/skills/behaviors/SKILL.md
@@ -14,16 +14,17 @@ The pages below are its documentation. Read the ones a task needs before writing
## Where to read
-| Task | Read |
-| ------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |
-| Add behaviors to a project; hold a conversation, judge outputs, and summarize verdicts in fxtr steps; test without credentials | [Calling language models](references/guides/language-models.mdx) |
-| Pick a provider, an adapter, and an exact model ID | [Choosing models](references/guides/choosing-models.mdx) |
-| Script users or simulate them with models (a base model, steered by a pilot), offer tools, or write a custom conversation flow | [Policies and tools](references/guides/policies-and-tools.mdx) |
-| Rollout statuses and `max_turns`, failures, retries, streaming | [Rollout outcomes and retries](references/guides/rollout-outcomes.mdx) |
-| Messages and content, stored records, transcripts, conversations in the viewer, checkpoints | [Conversation records and checkpoints](references/guides/conversation-records.mdx) |
-| Run Docent readings, or convert records for Docent | [Docent readings](references/guides/docent-readings.mdx) |
-| Choose a layer; imports, adapters and their options, model providers, sampling and reasoning settings, requests and responses | [API overview](references/reference/api.mdx) |
-| Steps, workflows, arrays, launching jobs, and the step cache | the adjacent [fxtr skill](../fxtr/SKILL.md) |
+| Task | Read |
+| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
+| Add behaviors to a project; hold a conversation, judge outputs, and summarize verdicts in fxtr steps; test without credentials | [Calling language models](references/guides/language-models.mdx) |
+| Pick a provider, an adapter, and an exact model ID | [Choosing models](references/guides/choosing-models.mdx) |
+| Script users or simulate them with models (a base model, steered by a pilot), offer tools, or write a custom conversation flow | [Policies and tools](references/guides/policies-and-tools.mdx) |
+| What each provider's dialect carries, adaptation losses and refusing them, structured output (`response_format`, strict tools, tool output schemas), refusals and other stops, codecs | [Dialects and adaptation](references/guides/dialects-and-adaptation.mdx) |
+| Rollout statuses and `max_turns`, failures, retries, streaming | [Rollout outcomes and retries](references/guides/rollout-outcomes.mdx) |
+| Messages and content, stored records, transcripts, conversations in the viewer, checkpoints | [Conversation records and checkpoints](references/guides/conversation-records.mdx) |
+| Run Docent readings, or convert records for Docent | [Docent readings](references/guides/docent-readings.mdx) |
+| Choose a layer; imports, adapters (including Gemini and OpenRouter) and their options, model providers, sampling, reasoning and speed settings, requests and responses | [API overview](references/reference/api.mdx) |
+| Steps, workflows, arrays, launching jobs, and the step cache | the adjacent [fxtr skill](../fxtr/SKILL.md) |
## Best practices
diff --git a/plugins/fxtr/skills/behaviors/provenance.json b/plugins/fxtr/skills/behaviors/provenance.json
index ac98808..2ead3c7 100644
--- a/plugins/fxtr/skills/behaviors/provenance.json
+++ b/plugins/fxtr/skills/behaviors/provenance.json
@@ -2,10 +2,10 @@
"skill": "behaviors",
"documentation": "https://docs.transluce.ai/behaviors",
"packages": {
- "fxtr": "0.1.0a0",
- "behaviors": "0.0.1a4"
+ "fxtr": "0.2.0a0",
+ "behaviors": "0.0.1a5"
},
- "revision": "052f907cc35979930fda832a71aec0c2194e7e48",
+ "revision": "d4dc6a2e28ca36addbd6aee70256eb22317e1c93",
"modified": false,
- "content_sha256": "a9a5b26e4b86c7b765f0d3c7ce1ce7bea062364e7112c5bec2ad86aed6ca2f1d"
+ "content_sha256": "384ea30cb2960b22608612b69eae76cde2e91e70eca2341ebcb3df757e0c7a90"
}
diff --git a/plugins/fxtr/skills/behaviors/references/INDEX.md b/plugins/fxtr/skills/behaviors/references/INDEX.md
index e555652..c6f5ece 100644
--- a/plugins/fxtr/skills/behaviors/references/INDEX.md
+++ b/plugins/fxtr/skills/behaviors/references/INDEX.md
@@ -12,6 +12,7 @@ in the order of the site's navigation.
- [Choosing models](guides/choosing-models.mdx): Find the exact model IDs a provider offers your account, pick the adapter for its endpoint, and check a model before a sweep.
- [Conversation records and checkpoints](guides/conversation-records.mdx): What a rollout records, how conversations are stored as fxtr entities and flattened into transcripts, and how to checkpoint a session.
+- [Dialects and adaptation](guides/dialects-and-adaptation.mdx): How a request reaches each provider: the dialects the adapters speak, what an adapter changes to send a request and how to refuse it, structured output, responses that are not answers, and the codecs behind the adapters.
- [Docent readings](guides/docent-readings.mdx): Convert conversations to Docent's data models, and run a Docent reading against a transcript or agent run with a model you choose.
- [Calling language models](guides/language-models.mdx): Use the behaviors library to hold conversations and judge outputs in fxtr steps.
- [Policies and tools](guides/policies-and-tools.mdx): Decide what the model sees each turn: scripted users, users simulated by a base model and steered by a pilot, tool policies, their combinations, and custom conversation flows.
diff --git a/plugins/fxtr/skills/behaviors/references/guides/choosing-models.mdx b/plugins/fxtr/skills/behaviors/references/guides/choosing-models.mdx
index c47cf47..e5d376a 100644
--- a/plugins/fxtr/skills/behaviors/references/guides/choosing-models.mdx
+++ b/plugins/fxtr/skills/behaviors/references/guides/choosing-models.mdx
@@ -50,6 +50,27 @@ This is one page, even with `limit=1000`. While `has_more` is true, request the
`after_id` set to the returned `last_id`, and collect its models before advancing again.
Pass a returned `id` to `AnthropicMessagesAPI(model_id)`; `display_name` is only for presentation.
+## Gemini
+
+[List models](https://ai.google.dev/api/models#method:-models.list)
+with `GET https://generativelanguage.googleapis.com/v1beta/models`:
+
+```bash
+curl --fail-with-body --silent --show-error \
+ 'https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000' \
+ -H "x-goog-api-key: $GEMINI_API_KEY" \
+ -o /tmp/gemini-models.json &&
+jq -r '.models[]
+ | select(.supportedGenerationMethods | index("generateContent"))
+ | [(.name | sub("^models/"; "")), .displayName] | @tsv' /tmp/gemini-models.json &&
+jq '{nextPageToken}' /tmp/gemini-models.json
+```
+
+While `nextPageToken` is set, request the next page with `pageToken` set to it. The filter keeps
+models that serve `generateContent`, the method the adapter calls. Pass the returned `name`
+without its `models/` prefix to `GeminiGenerateContentAPI(model_id)`, from
+`behaviors.implementations.models.gemini`.
+
## OpenRouter
OpenRouter serves models from multiple vendors through an OpenAI-compatible endpoint. Its
@@ -71,31 +92,29 @@ For the general catalog, change `/models/user` to `/models`. The
Use the full returned `id`, including its vendor prefix and any suffix, with:
```python
-import os
-
-from behaviors.implementations.models.openai_compatible import OpenAICompatibleAPI
+from behaviors.implementations.models.openrouter import OpenRouterAPI
-api = OpenAICompatibleAPI(
- model_id, # Exact id selected from the OpenRouter listing.
- base_url="https://openrouter.ai/api/v1",
- api_key=os.environ["OPENROUTER_API_KEY"],
-)
+api = OpenRouterAPI(model_id) # Exact id selected from the OpenRouter listing.
```
-The OpenAI SDK does not read `OPENROUTER_API_KEY` by itself, so pass it explicitly as above.
+`OpenRouterAPI` reads `OPENROUTER_API_KEY` unless you pass `api_key`, and sends back the
+reasoning state OpenRouter returns, which `OpenAICompatibleAPI` pointed at OpenRouter would not.
Close the adapter with `await api.aclose()` when finished, as in the
[conversation step](language-models.mdx#a-conversation-as-a-step).
## Search and validate a candidate
-Search a saved response by ID or display name, changing the file and search text as needed:
+Search a saved response by ID or display name, changing the file and search text as needed. The
+filter reads any of the listings above: Gemini's lists `models` rather than `data`, and its `name`
+is the ID with a `models/` prefix, which the filter removes.
```bash
jq -r --arg query 'claude' '
- .data[]
- | select(([.id, (.name // .display_name // "")] | join(" ") | ascii_downcase)
+ (.data // .models)[]
+ | (.id // (.name | sub("^models/"; ""))) as $id
+ | select(([$id, (.display_name // .displayName // .name // "")] | join(" ") | ascii_downcase)
| contains($query | ascii_downcase))
- | .id
+ | $id
' /tmp/openrouter-models.json
```
diff --git a/plugins/fxtr/skills/behaviors/references/guides/dialects-and-adaptation.mdx b/plugins/fxtr/skills/behaviors/references/guides/dialects-and-adaptation.mdx
new file mode 100644
index 0000000..fd355a8
--- /dev/null
+++ b/plugins/fxtr/skills/behaviors/references/guides/dialects-and-adaptation.mdx
@@ -0,0 +1,240 @@
+---
+title: "Dialects and adaptation"
+description: "How a request reaches each provider: the dialects the adapters speak, what an adapter changes to send a request and how to refuse it, structured output, responses that are not answers, and the codecs behind the adapters."
+---
+
+behaviors describes every model call in one vocabulary: a `ModelRequest` goes in, and a
+`ModelResponse` or `ModelCallFailure` comes out, whichever provider serves it. Each provider
+adapter speaks one **dialect**, the wire schema of one provider API, and converts between the
+vocabulary and that dialect with a **codec**. Not every dialect can carry everything a request
+can say, so before sending, the adapter fits the request to its dialect and model, and reports
+each change on the result.
+
+This page is about that boundary: which dialect each adapter speaks, what adaptation changes and
+how to refuse it, structured output, and how to tell an answer from a refusal. The
+[API overview](../reference/api.mdx#provider-adapters) covers constructing the adapters.
+
+## Dialects
+
+A dialect names an API schema, not a vendor. A model served through OpenRouter is called over
+Chat Completions whoever made it, and a local server may speak any dialect it implements.
+
+| Dialect | Adapters | Served by |
+| ------------------------- | -------------------------------------- | ------------------------------------------------------------------------------- |
+| `anthropic_messages` | `AnthropicMessagesAPI` | Anthropic, and services that implement the Messages API (pass their `base_url`) |
+| `openai_responses` | `OpenAIResponsesAPI` | OpenAI |
+| `openai_chat_completions` | `OpenAICompatibleAPI`, `OpenRouterAPI` | OpenAI, OpenRouter, and compatible servers such as vLLM |
+| `gemini_generate_content` | `GeminiGenerateContentAPI` | Google's Gemini API |
+
+An adapter's `dialect` and `model_id` properties say what it serves. Where a model is offered in
+several dialects, the dialect decides what a request can carry. For example, only OpenAI
+Responses and Gemini declare a tool's output schema, and Chat Completions can't return OpenAI's
+encrypted reasoning to the model, except through OpenRouter, which carries reasoning state of its
+own.
+
+A conversation can change provider partway through, and its context keeps the reasoning blocks
+of earlier turns. A provider accepts back only reasoning state it issued for that model, so an
+adapter leaves out reasoning blocks that carry another provider's state, and the model reasons
+afresh on those turns.
+
+## What an adapter changes
+
+An adapter changes a part of a request its dialect or model can't carry as asked: it leaves the
+part out, sends its nearest equivalent, or sends it without enforcing it. Both a
+`ModelResponse` and a `ModelCallFailure` list every change in `adaptation_losses`, one
+`RequestLoss` per change, with:
+
+* `code`, a short, stable name for the kind of change, such as `stop_sequences`;
+* `detail`, what exactly changed;
+* `semantic`, `True` when the model was asked something different, and `False` when only cost,
+ latency, or caching changed.
+
+A request the dialect carries whole has no losses. Some common codes:
+
+| Code | Change |
+| ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
+| `stop_sequences` | Stop sequences left out (OpenAI Responses has none). |
+| `reasoning_budget` | A reasoning budget sent as the nearest effort level (the OpenAI dialects have no budget). |
+| `reasoning_effort` | An effort level the API doesn't offer sent as the nearest one, such as Gemini's `max` as `high`. |
+| `foreign_reasoning` | Reasoning blocks with another provider's state left out. |
+| `speed` | A speed tier left out, for a dialect without one. |
+| `cache_breakpoint` | Prompt-cache breakpoints dropped or their TTL shortened, where a dialect has no breakpoints or limits them (Anthropic keeps the latest four). |
+| `response_format_*`, `response_schema_*`, `json_mode` | A response format changed (see [Structured output](#structured-output)). |
+| `tool_strict_*`, `tool_schema_weakened`, `tool_output_schema`, `tool_result_shape` | A tool's schema or strictness changed. |
+
+The set is open: a code names each new kind of change an adapter makes, and a code always has the
+same `semantic` value. Match codes you act on, and log the rest.
+
+An adapter also learns from a model's rejections. When a model refuses a request spelled one way
+that it would take spelled another (a Gemini model that refuses `thinkingBudget: 0` but takes the
+`MINIMAL` thinking level, say), the adapter resends it respelled within the same call, whatever
+retry schedule the caller set. Each fix is tried at most once per call, but one call can trigger
+several, so it can be resent more than once. Once a respelled request succeeds, the adapter
+keeps that spelling for its later requests to the model and logs a warning once. A fix that
+changes what the model is asked, or how the request is served, is listed in
+`adaptation_losses` like any other change; one that only respells the request with the same
+meaning (Anthropic's two spellings of thinking off) adds nothing there. `AnthropicMessagesAPI`,
+`OpenAIResponsesAPI`, and `GeminiGenerateContentAPI` have fixes of this kind.
+
+In a rollout, a session of `chat_session_model_from_api` records each call's `ModelResponse` in
+the model turn's metadata, so the losses are stored with the conversation:
+
+```python
+from behaviors.types import ModelResponse, find_metadata
+
+for turn in rollout.model_turns:
+ response = find_metadata(turn.metadata, ModelResponse)
+ if response is not None:
+ for loss in response.adaptation_losses:
+ print(loss.code, loss.semantic, loss.detail)
+```
+
+### Refusing changes in meaning
+
+By default every change is made and reported. To have a call fail instead of being sent with a
+changed meaning, set the request's `adaptation_policy`:
+
+```python
+from behaviors.types import AdaptationPolicy, ModelCallFailure, ModelRequest
+
+request = ModelRequest(
+ ...,
+ adaptation_policy=AdaptationPolicy(semantic_changes="refuse"),
+)
+result = await api.generate(request)
+if isinstance(result, ModelCallFailure) and result.category == "adaptation_refused":
+ refused = [loss for loss in result.proposed_adaptation_losses if loss.semantic]
+```
+
+`semantic_changes` is `"allow"` (the default) or `"refuse"`. Changes that affect only cost,
+latency, or caching are made under either. A refused call returns a `ModelCallFailure` with
+category `adaptation_refused`: its `proposed_adaptation_losses` are the changes that were not
+made, the semantic ones among them being what the policy refused, and its `adaptation_losses` the
+changes made to what was sent, if anything was. Usually nothing was sent, and
+`provider_http_status` is `None`; when a model rejected the request and the fix it learned would
+change the meaning, the provider's status and message are kept.
+
+The policy is part of the request, so it reaches the adapter through retries and wrappers, and a
+stored request records what the call allowed. A refusal recurs on every attempt, which is why
+`adaptation_refused` is not among the categories retried by default (see
+[Failures and retries](rollout-outcomes.mdx#failures-and-retries)). The adapters
+listed above read the policy; any other `ModelAPI` sends the request as it is, and may ignore
+`response_format` too.
+
+## Structured output
+
+Set a request's optional `response_format` to constrain the model's answer:
+
+* `ResponseFormatJsonSchema(schema=..., strict=True)` asks for JSON matching `schema`.
+ `strict=True` asks the provider to enforce it; `strict=False` offers it as guidance. It also
+ takes an optional `name` and `description`, which OpenAI uses.
+* `ResponseFormatJsonObject()` asks for one valid JSON value of any shape (JSON mode).
+* `ResponseFormatText()` asks for plain text explicitly, which is also what `None` means.
+
+A schema is JSON Schema, draft 2020-12 unless its `$schema` names another. Each provider enforces
+its own subset of JSON Schema, and the adapters fit a schema to it before sending:
+
+| Provider | Response schema | JSON mode |
+| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
+| Anthropic | Always enforced: an advisory schema is enforced anyway (`response_format_strengthened`). Keywords Anthropic can't enforce move into descriptions (`response_schema_weakened`), and objects that allowed extra keys are closed (`response_schema_strengthened`). A schema Anthropic would reject even so, such as `{}` or a recursive reference, is left out (`response_format_dropped`). | None: left out (`json_mode`). |
+| OpenAI (Responses and Chat Completions) | Enforced when strict. A strict schema that breaks OpenAI's strict-mode rules is sent without strict mode (`response_format_unenforced`); keywords OpenAI rejects move into descriptions (`response_schema_weakened`); a root that isn't an object is left out (`response_format_dropped`). | Sent. |
+| Gemini | Always enforced: an advisory schema is enforced anyway (`response_format_strengthened`). Keywords Gemini rejects move into descriptions, and those it accepts without enforcing are sent and recorded (both `response_schema_weakened`). | Sent. |
+
+An answer matches its schema only when the response stopped with `StopEndTurn`. A refusal, a
+content filter, or the token limit can leave partial, empty, or nonconforming text, and a schema
+the adapter weakened is no longer fully enforced. Check how the response ended (see
+[When a response is not an answer](#when-a-response-is-not-an-answer)) and validate the answer
+yourself before using it.
+
+### Tools
+
+A tool's `strict` asks the same of the model's calls to it: `True`, `False`, or `"auto"`.
+`"auto"` is OpenAI's meaning: strict when OpenAI's strict-mode rules accept the tool's input
+schema. OpenAI Responses sends it as it is, and every other adapter resolves it by those same
+rules, whatever its own provider could enforce; a schema with an optional property, for
+example, breaks OpenAI's rules, so the tool is sent non-strict to Anthropic too. Anthropic and
+OpenAI send a strict tool whose schema they can't enforce as non-strict
+(`tool_strict_unenforced`). Gemini validates
+calls for the whole request or not at all: one strict tool makes every tool strict
+(`tool_strict_strengthened`), and a required or forced tool call leaves them all unenforced.
+
+A tool's `output_schema` describes what the tool returns, and its results are then that JSON
+value as text. OpenAI Responses and Gemini send it to the model; Anthropic and Chat Completions
+have no place for it (`tool_output_schema`). Gemini also leaves out the output schema of a tool
+when one of its results in the context isn't a JSON object (`tool_result_shape`). It checks only
+that: a JSON object that doesn't match the schema keeps it, with no loss reported.
+
+To get a schema enforced exactly as written or not at all, refuse semantic changes, as
+[above](#refusing-changes-in-meaning): every change to a response format or to a strict tool's
+schema is semantic.
+
+## When a response is not an answer
+
+A response's text is a finished answer only when its `stop_reason` is `StopEndTurn` or
+`StopStopSequence`. The other stops:
+
+* `StopToolUse`: the model stopped to call tools.
+* `StopMaxTokens`: the output reached the token limit.
+* `StopRefusal`: the model or the provider's safety system declined. Any text the model wrote is
+ kept, so the content can be empty, partial, or the model's explanation. `provider_reason` is the
+ provider's own reason (`"refusal"`, `"content_filter"`, `"SAFETY"`); `complete` is `True` when
+ the response is the model's whole refusal, `False` when it was cut off or blocked, and `None`
+ when the provider doesn't say; `detail` holds whatever more the provider said, such as
+ Anthropic's policy category or Gemini's safety ratings.
+* `StopContentFilter`: the provider withheld output for what it contained rather than declining
+ the request, such as Gemini's recitation check.
+* `StopOther`: any other reason.
+
+OpenAI reports a refusal as a refusal only under a response format; without one, a model that
+declines does so in ordinary text, which ends with `StopEndTurn` like any answer.
+
+Check how a response ended before reading it:
+
+```python
+response.raise_for_stop_reason() # UnexpectedStopError unless it stopped with an answer
+```
+
+`raise_for_stop_reason(allow=(StopEndTurn, StopToolUse))` also accepts tool calls. The error's
+`stop_reason` is the stop, and its message names what the provider said.
+
+A refusal or a content filter after the request was accepted is a response, not a failure. A
+prompt a provider rejects with an error before generating, as OpenAI does, is a
+`ModelCallFailure` of category `content_filter` instead.
+
+## Codecs
+
+A codec converts between the vocabulary and one dialect, with no I/O and no provider SDK. The
+codecs are in `behaviors.implementations.dialects`: `AnthropicMessagesCodec`,
+`OpenAIResponsesCodec`, `OpenAIChatCompletionsCodec`, and `GeminiGenerateContentCodec(model=...)`.
+An adapter's `codec` property returns the one it uses, with the adapter's configuration.
+
+The model side of a codec, the `ModelSideCodec` protocol in `behaviors.interfaces.dialect_codecs`,
+works in three steps: `adapt_request(model, request)` returns an `AdaptedRequest`, the fitted
+`request` and its `losses`; `encode_request(model, request, streaming=...)` renders a fitted
+request exactly as it is, as an `EncodedRequest` with its `path`, `body`, `query`, and `headers`
+(credentials are the client's); and `decode_response`, `sse_decoder`, and `decode_failure` parse
+what the provider sends back. Since a codec needs no credentials, it shows what a request would
+send without calling anyone:
+
+```python
+from behaviors.implementations.dialects import GeminiGenerateContentCodec
+
+codec = GeminiGenerateContentCodec(model=model_id)
+adapted = codec.adapt_request(model_id, request)
+for loss in adapted.losses:
+ print(loss.code, loss.detail)
+wire = codec.encode_request(model_id, adapted.request, streaming=True)
+print(wire.path, wire.query, wire.body)
+```
+
+The adapters always stream, even from `generate`, so `streaming=True` renders what they send:
+here `/v1beta/models/{model_id}:streamGenerateContent` with the query `alt=sse`.
+
+The adapter adds what it has learned from the model's rejections on top, so a live call can
+report a change this preview doesn't.
+
+To serve a provider the adapters don't cover, first check whether it implements one of these
+dialects, and point that adapter's `base_url` at it. A new dialect needs a codec of its own,
+implementing `ModelSideCodec`, and a `ModelAPI` that sends what it encodes;
+`behaviors.implementations.dialects.codec_utils` has helpers for streamed responses, JSON bodies,
+and reading a reasoning state as the codec's own type (`own_reasoning_state`).
diff --git a/plugins/fxtr/skills/behaviors/references/guides/language-models.mdx b/plugins/fxtr/skills/behaviors/references/guides/language-models.mdx
index f199222..feff1ad 100644
--- a/plugins/fxtr/skills/behaviors/references/guides/language-models.mdx
+++ b/plugins/fxtr/skills/behaviors/references/guides/language-models.mdx
@@ -5,7 +5,8 @@ description: "Use the behaviors library to hold conversations and judge outputs
**behaviors** is a Python library for calling language models from fxtr experiments. It provides:
-* model adapters for Anthropic, OpenAI, and OpenAI-compatible services;
+* model adapters for Anthropic, OpenAI, Google's Gemini API, OpenRouter, and OpenAI-compatible
+ services;
* conversation sessions and **context policies**, which decide what the model sees next:
scripted or model-simulated user messages, tool results, or custom logic;
* retries for rate limits and server errors;
@@ -22,7 +23,7 @@ uv add "behaviors[models]"
Then commit the updated `pyproject.toml` and `uv.lock`.
-Set your provider's API key, `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`, in the project's `.env`
+Set your provider's API key, such as `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`, in the project's `.env`
(see [Project configuration](../../../fxtr/references/reference/project-configuration.mdx#env)) or in the environment.
| Provider | Adapter |
@@ -30,11 +31,13 @@ Set your provider's API key, `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`, in the pro
| OpenAI Responses | `from behaviors.implementations.models.openai_responses import OpenAIResponsesAPI` |
| Anthropic Messages | `from behaviors.implementations.models.anthropic import AnthropicMessagesAPI` |
| OpenAI Chat Completions-compatible | `from behaviors.implementations.models.openai_compatible import OpenAICompatibleAPI` |
+| OpenRouter | `from behaviors.implementations.models.openrouter import OpenRouterAPI` |
+| Gemini API | `from behaviors.implementations.models.gemini import GeminiGenerateContentAPI` |
Construct an adapter with the provider's model ID, such as `OpenAIResponsesAPI("gpt-6-luna")`.
[Choosing models](choosing-models.mdx) shows how to find the IDs your account can
use, and the [API overview](../reference/api.mdx#provider-adapters) covers the adapters'
-other options, such as `base_url` for a compatible service.
+other options and their API keys, such as `base_url` for a compatible service.
## A conversation as a step
@@ -315,10 +318,11 @@ mean_scores = context.run_step("mean_scores", mean_score, {"verdicts": verdicts}
`SamplingParams` covers `max_tokens`, `temperature`, `top_p`, `stop_sequences`, `reasoning`,
- and provider-specific `extra`. Which settings take effect depends on the adapter and model:
- for example, `OpenAIResponsesAPI` doesn't apply `stop_sequences`. Leave a setting unset
- unless your adapter and model support it. See
- [Sampling settings](../reference/api.mdx#sampling-settings).
+ `speed`, and provider-specific `extra`. Which settings take effect depends on the adapter and model:
+ for example, `OpenAIResponsesAPI` doesn't apply `stop_sequences`, and the result's
+ `adaptation_losses` lists that change. Leave a setting unset unless your adapter and model support
+ it. See [Sampling settings](../reference/api.mdx#sampling-settings) and
+ [What an adapter changes](dialects-and-adaptation.mdx#what-an-adapter-changes).
diff --git a/plugins/fxtr/skills/behaviors/references/guides/rollout-outcomes.mdx b/plugins/fxtr/skills/behaviors/references/guides/rollout-outcomes.mdx
index 2800ddb..df5f947 100644
--- a/plugins/fxtr/skills/behaviors/references/guides/rollout-outcomes.mdx
+++ b/plugins/fxtr/skills/behaviors/references/guides/rollout-outcomes.mdx
@@ -30,9 +30,15 @@ completed rollout can still contain a reply cut off at the token limit.
A model call's expected failures are returned as data: `ModelAPI.generate` returns a
`ModelCallFailure` with a `category` (`context_length`, `content_filter`, `rate_limited`,
-`overloaded`, `authentication`, `invalid_request`, or `server_error`), a `description`, and the
-provider's HTTP status. An error in the implementation itself raises. The provider adapters turn
-off their SDKs' own retries, so that these settings decide every attempt:
+`overloaded`, `authentication`, `invalid_request`, `server_error`, or `adaptation_refused`), a
+`description`, and the provider's HTTP status. `adaptation_refused` is a request that could not
+be sent without a change in meaning its `adaptation_policy` refuses (see
+[Refusing changes in meaning](dialects-and-adaptation.mdx#refusing-changes-in-meaning)).
+An error in the implementation itself raises. The provider adapters have no retry schedule of
+their own, so these settings decide when a failed call is tried again. (Some adapters resend a
+request a model rejected in a form they know how to fix, within the same call and at most once
+for each fix; that is not a retry under these settings, and happens without one. See
+[What an adapter changes](dialects-and-adaptation.mdx#what-an-adapter-changes).)
* A session of `chat_session_model_from_api` has **no retry schedule by default** (`retry=None`).
Pass `retry=RetryConfig()` to retry failures in `failure_categories_to_retry`, by default
@@ -68,10 +74,36 @@ happen:
* `ContextTurnEvent` and `ModelTurnEvent`, each carrying a completed turn, the same object that
lands on the returned rollout;
* `ModelStreamEvent`, carrying a delta of the model's output while it generates a turn, when the
- model's session streams (sessions of a streaming adapter, such as the provider adapters, do).
+ model's session streams (sessions of a streaming adapter, such as the provider adapters, do);
+* `RolloutEndEvent`, last, carrying how the rollout ended: the `status` and `end` the returned
+ rollout has. A rollout that raises reports none.
The callback is awaited in order, on the rollout's own path: a slow callback slows the rollout,
and one that raises aborts it. Deltas can describe output that a retry then discards:
`StreamRestart` tells a consumer to reset what it has assembled of the turn so far. The completed
-turns and the returned rollout are the durable content, and how the rollout ended is its returned
-status, not an event.
+turns and the returned rollout are the durable content.
+
+To watch a rollout in the viewer while its step runs, pass a `ChatRolloutPreview` publishing to
+the step's `context.preview`:
+
+```python
+from behaviors.rollouts.chat_preview import ChatRolloutPreview
+
+rollout = await run_chat_rollout(
+ model, policy, event_callback=ChatRolloutPreview(context.preview)
+)
+```
+
+It folds the events into a partial `ChatRollout` (see
+[Partial values](../../../fxtr/references/concepts/entities-and-custom-types.mdx#partial-values)): the finished turns, and
+while the model streams, a partial last model turn holding its output so far. `status` and `end`
+are `None` until the rollout ends, then what the returned rollout has. A project registering the
+behaviors renderers (`behaviorsRenderers` from
+`fxtr-view-behaviors`) sees it in the same conversation view as the finished rollout, marked in
+progress, with the reply being streamed at the bottom, and the step's row in its run's table says
+the turn the rollout is on ("turn 6 · streaming…"). To keep another callback too, call the preview
+from your own: `await preview(event)`.
+
+The same renderers show a partial `Transcript`, `TranscriptGroup`, or `AgentRun` that a step
+publishes itself, with `context.preview(Partial(Transcript, ...))`: the messages or transcripts so
+far, each one still being written (itself a partial value) marked as streaming.
diff --git a/plugins/fxtr/skills/behaviors/references/index.mdx b/plugins/fxtr/skills/behaviors/references/index.mdx
index ee819a0..5af28eb 100644
--- a/plugins/fxtr/skills/behaviors/references/index.mdx
+++ b/plugins/fxtr/skills/behaviors/references/index.mdx
@@ -35,6 +35,7 @@ execution, caching, and provenance. For the shortest example of a step that call
The other guides go further: [choosing models](guides/choosing-models.mdx),
+[dialects and adaptation](guides/dialects-and-adaptation.mdx),
[policies and tools](guides/policies-and-tools.mdx),
[rollout outcomes and retries](guides/rollout-outcomes.mdx),
[conversation records and checkpoints](guides/conversation-records.mdx), and
diff --git a/plugins/fxtr/skills/behaviors/references/reference/api.mdx b/plugins/fxtr/skills/behaviors/references/reference/api.mdx
index 16fbaee..e6dce28 100644
--- a/plugins/fxtr/skills/behaviors/references/reference/api.mdx
+++ b/plugins/fxtr/skills/behaviors/references/reference/api.mdx
@@ -11,22 +11,23 @@ fxtr steps.
## Choose a layer
-| Need | API |
-| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| One model request, no conversation state | `ModelAPI.generate(ModelRequest)`, from `behaviors.interfaces.model_apis`; returns a `ModelResponse` or a `ModelCallFailure`. |
-| Incremental output from a request | `StreamingModelAPI.generate_with_events(request, callback)`. |
-| Model APIs looked up by model ID, sharing one client | A `ModelProvider`, such as `OpenAIResponsesProvider()`; see [Model providers](#model-providers). |
-| One request with a retry schedule | `generate_with_retries(api, request, retry=..., failure_categories_to_retry=...)`, from `behaviors.implementations.models`. |
-| A conversation with accumulated messages | `chat_session_model_from_api(api, sampling, retry=...)`, from `behaviors.implementations.models`, which creates an independent session per conversation. |
-| A model against an environment or a simulated user | `run_chat_rollout(model, context_policy, ...)`, from `behaviors.rollouts.chat`; returns a `ChatRollout`. |
-| Fixed user prompts | `ScriptedUserSimulator(messages=(...))`, made a policy with `context_policy_from_user_simulator(..., initialization=...)`. |
-| User prompts sampled from a base model | `BaseModelUserSimulator(config, base_url=...)`, from `behaviors.implementations.context_policies.base_model_user_simulator`. |
-| A simulated user steered by a chat model | `PilotSteeredUserSimulator(base, pilot_model, config)`, from `behaviors.implementations.context_policies.pilot_steered_user_simulator`. |
-| User prompts interleaved with tool calls | `context_policy_from_user_and_tools(user, tools, initialization=...)`. |
-| A first turn followed only by tool turns | `context_policy_from_tool_policy(tools, first_turn_messages=..., initialization=...)`. |
-| A custom or adaptive conversation | `context_policy_from_generator`, or a subclass of `GeneratorContextPolicy`; for checkpoints, implement the `ContextPolicy` and session protocols directly. |
-| Plain transcripts for viewers or readers | `ChatRolloutTranscriptProjection`, from `behaviors.rollouts.chat`, with `Transcript`, `TranscriptGroup`, and `AgentRun`. |
-| Docent readings | `DocentReadingStep` and the conversions in `behaviors.implementations.docent`, with `behaviors[docent]`. |
+| Need | API |
+| -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| One model request, no conversation state | `ModelAPI.generate(ModelRequest)`, from `behaviors.interfaces.model_apis`; returns a `ModelResponse` or a `ModelCallFailure`. |
+| Incremental output from a request | `StreamingModelAPI.generate_with_events(request, callback)`. |
+| Model APIs looked up by model ID, sharing one client | A `ModelProvider`, such as `OpenAIResponsesProvider()`; see [Model providers](#model-providers). |
+| What a request would send a provider, without sending it | A dialect codec's `adapt_request` and `encode_request`; see [Codecs](../guides/dialects-and-adaptation.mdx#codecs). |
+| One request with a retry schedule | `generate_with_retries(api, request, retry=..., failure_categories_to_retry=...)`, from `behaviors.implementations.models`. |
+| A conversation with accumulated messages | `chat_session_model_from_api(api, sampling, retry=...)`, from `behaviors.implementations.models`, which creates an independent session per conversation. |
+| A model against an environment or a simulated user | `run_chat_rollout(model, context_policy, ...)`, from `behaviors.rollouts.chat`; returns a `ChatRollout`. |
+| Fixed user prompts | `ScriptedUserSimulator(messages=(...))`, made a policy with `context_policy_from_user_simulator(..., initialization=...)`. |
+| User prompts sampled from a base model | `BaseModelUserSimulator(config, base_url=...)`, from `behaviors.implementations.context_policies.base_model_user_simulator`. |
+| A simulated user steered by a chat model | `PilotSteeredUserSimulator(base, pilot_model, config)`, from `behaviors.implementations.context_policies.pilot_steered_user_simulator`. |
+| User prompts interleaved with tool calls | `context_policy_from_user_and_tools(user, tools, initialization=...)`. |
+| A first turn followed only by tool turns | `context_policy_from_tool_policy(tools, first_turn_messages=..., initialization=...)`. |
+| A custom or adaptive conversation | `context_policy_from_generator`, or a subclass of `GeneratorContextPolicy`; for checkpoints, implement the `ContextPolicy` and session protocols directly. |
+| Plain transcripts for viewers or readers | `ChatRolloutTranscriptProjection`, from `behaviors.rollouts.chat`, with `Transcript`, `TranscriptGroup`, and `AgentRun`. |
+| Docent readings | `DocentReadingStep` and the conversions in `behaviors.implementations.docent`, with `behaviors[docent]`. |
The guides cover the layers above the request:
[policies and tools](../guides/policies-and-tools.mdx),
@@ -50,8 +51,9 @@ general judge: build one for your experiment from these interfaces, as the
`SimulatedUserText`, the tool policies, and the policy combinators. The model-driven user
simulators are in modules of their own there: `base_model_user_simulator`, with the profile
types in `base_model_prompt`, and `pilot_steered_user_simulator`, with `PilotSteering`.
+* `behaviors.implementations.dialects` exports the dialect codecs, which need no provider SDK.
* `behaviors.interfaces` holds the protocols: `model_apis` (including `ModelProvider`),
- `chat_session_models`, `context_policies`, and `projections`.
+ `dialect_codecs`, `chat_session_models`, `context_policies`, and `projections`.
* The provider adapters and their model providers are each in a module of their own (below),
imported explicitly, because they need the provider SDKs. So does `base_model_user_simulator`.
@@ -74,23 +76,40 @@ other kind needs a session model that understands it. Close sessions you start y
## Provider adapters
Install the provider SDKs with the `models` extra, `behaviors[models]`. The core types, context
-policies, and rollouts with a fake model need no SDK.
+policies, codecs, and rollouts with a fake model need no SDK.
-| Provider interface | Module | Adapter | Model provider |
-| ------------------------------------------------ | ---------------------------------------------------- | ---------------------- | --------------------------- |
-| Anthropic Messages | `behaviors.implementations.models.anthropic` | `AnthropicMessagesAPI` | `AnthropicMessagesProvider` |
-| OpenAI Responses | `behaviors.implementations.models.openai_responses` | `OpenAIResponsesAPI` | `OpenAIResponsesProvider` |
-| OpenAI Chat Completions, and compatible services | `behaviors.implementations.models.openai_compatible` | `OpenAICompatibleAPI` | `OpenAICompatibleProvider` |
+| Provider interface | Module | Adapter | Model provider |
+| ------------------------------------------------ | ---------------------------------------------------- | -------------------------- | ------------------------------- |
+| Anthropic Messages | `behaviors.implementations.models.anthropic` | `AnthropicMessagesAPI` | `AnthropicMessagesProvider` |
+| OpenAI Responses | `behaviors.implementations.models.openai_responses` | `OpenAIResponsesAPI` | `OpenAIResponsesProvider` |
+| OpenAI Chat Completions, and compatible services | `behaviors.implementations.models.openai_compatible` | `OpenAICompatibleAPI` | `OpenAICompatibleProvider` |
+| OpenRouter | `behaviors.implementations.models.openrouter` | `OpenRouterAPI` | none |
+| Gemini API | `behaviors.implementations.models.gemini` | `GeminiGenerateContentAPI` | `GeminiGenerateContentProvider` |
+
+Each adapter speaks one provider API's wire schema, its dialect; OpenRouter is served over Chat
+Completions. [Dialects and adaptation](../guides/dialects-and-adaptation.mdx) covers what each
+dialect carries and what an adapter changes to send a request.
Construct an adapter with the provider's model ID, as in `OpenAIResponsesAPI("gpt-6-luna")`;
[Choosing models](../guides/choosing-models.mdx) shows how to find IDs. Adapters read
-credentials from the environment (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`). Each also takes
-`api_key` and `base_url`, for another account or a compatible service, or an SDK client of your
-own with `client=...`, but not both. An adapter closes a client it created, and leaves an
-injected client to its caller. Never store credentials in experiment inputs or entities.
-
-The adapters turn off the SDKs' own retries, so that behaviors decides when a call is tried again
-(see [Rollout outcomes and retries](../guides/rollout-outcomes.mdx#failures-and-retries)).
+credentials from the environment: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `OPENROUTER_API_KEY`,
+and `GEMINI_API_KEY` (or `GOOGLE_API_KEY`). Each also takes `api_key`, and all but
+`OpenRouterAPI` take `base_url`, for another account or a compatible service; or pass a client of
+your own with `client=...` instead: the provider's SDK client, or for Gemini a `GeminiClient`
+from the same module. An SDK client must authenticate with an API key (a key given as a function,
+or an Azure AD token provider, also works). The adapters refuse a client that authenticates or
+signs requests when sending them, such as an Anthropic `credentials=` provider or a Bedrock or
+Vertex client, and an OpenAI admin key is never sent to a model endpoint. An adapter closes a
+client it created, and leaves an injected client to its caller. Never store credentials in
+experiment inputs or entities.
+
+The adapters have no retry schedule of their own, so that behaviors decides when a failed call
+is tried again (see
+[Rollout outcomes and retries](../guides/rollout-outcomes.mdx#failures-and-retries)). The one
+exception is separate from that schedule: when a model rejects a request in a form the adapter
+knows how to fix, `AnthropicMessagesAPI`, `OpenAIResponsesAPI`, and `GeminiGenerateContentAPI`
+resend it fixed within the same call, at most once for each fix (see
+[What an adapter changes](../guides/dialects-and-adaptation.mdx#what-an-adapter-changes)).
### Adapter options
@@ -102,24 +121,22 @@ Each adapter also takes keyword options that apply to every request it sends.
unset, since Anthropic requires one.
* `final_block_cache_control`, a `CacheControl`, puts a prompt-cache breakpoint on the final
content block of each request, when that block is non-empty text or a tool result the request
- didn't already mark. With it, each turn of a conversation reads the cached prefix the previous
- turn wrote, without marking messages yourself. Adding it raises `ModelError` when the request
- would then have more than Anthropic's four breakpoints, or a 1-hour breakpoint after a 5-minute
- one.
-* `thinking_display`, `"summarized"` (the default) or `"omitted"`, is sent with enabled thinking.
- `"summarized"` streams summarized thinking text; `"omitted"` returns only signed, empty
- thinking blocks. The adapter always sends it, since newer models omit thinking text unless
- asked.
-* `fast_mode=True` asks for fast-mode inference on every request (`speed: "fast"`, with its beta
- header). A model that doesn't offer fast mode rejects the request.
+ didn't already mark. With it, each turn of a conversation can read the cached prefix the
+ previous turn wrote, without marking messages yourself. When the request then has more than
+ Anthropic's four breakpoints, the adapter drops the earliest ones, and a 1-hour breakpoint after
+ a 5-minute one is shortened to 5 minutes; each such change is recorded as a `cache_breakpoint`
+ loss (see [What an adapter changes](../guides/dialects-and-adaptation.mdx#what-an-adapter-changes)).
```python
from behaviors.implementations.models.anthropic import AnthropicMessagesAPI
from behaviors.types import CacheControl
-api = AnthropicMessagesAPI(model_id, final_block_cache_control=CacheControl(), fast_mode=True)
+api = AnthropicMessagesAPI(model_id, final_block_cache_control=CacheControl())
```
+Whether thinking text comes back and the fast speed tier are set per request instead, with
+`ReasoningParams.summary` and `SamplingParams.speed` (see [Sampling settings](#sampling-settings)).
+
`OpenAIResponsesAPI` and `OpenAICompatibleAPI` take `extra_body`, a dictionary added to every
request's body; a request's `SamplingParams.extra` takes precedence over it. `OpenAICompatibleAPI`
also takes `forward_cache_control=True`, to send cache hints as Anthropic-style `cache_control`
@@ -127,6 +144,12 @@ to a service that reads them, such as OpenRouter serving an Anthropic model, and
`max_tokens_param`, `"max_tokens"` (the default) or `"max_completion_tokens"`, the name the
service expects for the output limit.
+`OpenRouterAPI` is `OpenAICompatibleAPI` set up for OpenRouter: its base URL, its key, and the
+reasoning state OpenRouter returns for models that sign or encrypt their reasoning, which it
+sends back on later turns. It takes `extra_body`, where OpenRouter's routing options go (such as
+`provider`), `forward_cache_control`, and `max_tokens_param`. `GeminiGenerateContentAPI` takes
+no options beyond its credentials.
+
## Model providers
A `ModelProvider`, from `behaviors.interfaces.model_apis`, looks up a `ModelAPI` by model ID:
@@ -134,11 +157,12 @@ A `ModelProvider`, from `behaviors.interfaces.model_apis`, looks up a `ModelAPI`
can't serve it. Use one where code picks models by ID as it runs, such as a harness whose main
and helper calls name different models, or to send requests for many models through one client.
-Each adapter module has a provider (the table above), which builds that module's adapter for any
+Each adapter module except `openrouter` has a provider (the table above), which builds that module's adapter for any
model ID. It takes the adapter's credentials and options, less the model ID; it builds one
adapter per model ID, on the first lookup, and returns the same one after that; and every
adapter it builds sends its requests through the provider's one client, its `client` property.
-Close the provider, not the adapters it built: `await provider.aclose()` closes the client if the
+`variant="openrouter"` and `reasoning_echo_field="reasoning"` set up the codec as `OpenRouterAPI`
+does. Close the provider, not the adapters it built: `await provider.aclose()` closes the client if the
provider created it, and leaves a client passed with `client=...` to its caller. Closing an
adapter that a provider built does nothing.
@@ -150,6 +174,8 @@ from behaviors.implementations.models.openai_compatible import OpenAICompatibleP
openrouter = OpenAICompatibleProvider(
base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"],
+ variant="openrouter",
+ reasoning_echo_field="reasoning",
)
try:
subject = openrouter.get_model_api(subject_id)
@@ -179,19 +205,48 @@ A `ModelRequest` has `context` (the messages), `tools`, `tool_choice`, `parallel
`ModelCallFailure`; check which before reading the response's fields. In `usage`, the counts of
cached and reasoning tokens are `None` when the provider doesn't report them.
+Reasoning in a response is a `ContentReasoning` block. Its `form` says what its `text` is: the
+model's own reasoning (`"full"`), a summary the provider wrote of it (`"summary"`), or reasoning the
+provider withheld (`"redacted"`, with empty text). Its `reasoning_state` is what the provider asks
+to be sent back on the next request of the conversation. Keep the block as it is in the context of
+later requests: an adapter sends a provider back only the state that provider issued for that
+model, and leaves out reasoning it can't use, listing it in `adaptation_losses`.
+
+`ModelRequest` also has two optional fields: `response_format`, which asks for
+[structured output](../guides/dialects-and-adaptation.mdx#structured-output), and
+`adaptation_policy`, which says whether the adapter may
+[change the request's meaning](../guides/dialects-and-adaptation.mdx#refusing-changes-in-meaning)
+to send it. A response's and a failure's `adaptation_losses` list what the adapter changed (see
+[What an adapter changes](../guides/dialects-and-adaptation.mdx#what-an-adapter-changes)).
+
+A response's text is a finished answer only when it stopped with `StopEndTurn` or
+`StopStopSequence`; a refusal can be empty. Call `response.raise_for_stop_reason()` before
+reading it, as
+[When a response is not an answer](../guides/dialects-and-adaptation.mdx#when-a-response-is-not-an-answer)
+explains.
+
## Sampling settings
-`SamplingParams` has `max_tokens`, `temperature`, `top_p`, `stop_sequences`, `reasoning`, and a
-provider-specific `extra`. A setting left `None` leaves the choice to the adapter or the
-provider, and which settings take effect depends on the adapter and the model:
-`OpenAIResponsesAPI`, for example, doesn't apply `stop_sequences`. Leave a setting unset unless
-your adapter and model support it, and don't expect `extra` settings to carry over from one
-adapter to another. Write numeric fields with their declared types, such as `temperature=0.0`
+`SamplingParams` has `max_tokens`, `temperature`, `top_p`, `stop_sequences`, `reasoning`,
+`speed`, and a provider-specific `extra`. A setting left `None` leaves the choice to the adapter
+or the provider, and which settings take effect depends on the adapter and the model:
+`OpenAIResponsesAPI`, for example, doesn't apply `stop_sequences`, and says so in the result's
+`adaptation_losses`
+([What an adapter changes](../guides/dialects-and-adaptation.mdx#what-an-adapter-changes)).
+Leave a setting unset unless your adapter and model support it, and don't expect `extra` settings to carry over from
+one adapter to another. Write numeric fields with their declared types, such as `temperature=0.0`
rather than `0`, since stored records are checked strictly.
-`ReasoningParams` has `enabled`, `budget_tokens`, and `effort`, one of `"minimal"`, `"low"`,
-`"medium"`, `"high"`, `"xhigh"`, and `"max"`. Each adapter turns them into its provider's
-parameters:
+`speed` is `"fast"` or `"standard"`, the provider's speed tier: Anthropic's fast mode, or OpenAI's
+and OpenRouter's fast service tier. It is sent as asked, so a model without the tier rejects the
+request or serves the standard tier, and `Usage.speed` says which it served. Gemini has no speed
+tier, and leaves it out.
+
+`ReasoningParams` has `enabled`, `budget_tokens`, `effort`, one of `"minimal"`, `"low"`,
+`"medium"`, `"high"`, `"xhigh"`, and `"max"`, and `summary`, whether readable reasoning comes
+back: `True` asks for it (Anthropic's summarized thinking, an OpenAI Responses `"detailed"`
+summary, Gemini's thoughts), `False` asks for none, and `None` leaves the provider's default.
+Each adapter turns them into its provider's parameters:
* The OpenAI adapters send an `effort` you set as it is, `"xhigh"` and `"max"` included, as
`reasoning.effort` (Responses) or `reasoning_effort` (Chat Completions). They don't lower it to
@@ -204,10 +259,22 @@ parameters:
thinking with that budget, and enabled thinking with no budget into adaptive thinking, which
only newer models offer: give older ones a budget. An `effort` is sent as
`output_config.effort`, except `"minimal"`, which Anthropic doesn't offer, sent as `"low"`.
+* `GeminiGenerateContentAPI` sends a `budget_tokens` as `thinkingBudget`, `enabled=False` as a
+ budget of 0, and an `effort` as `thinkingLevel`, with `"xhigh"` and `"max"` sent as `"high"`.
+ Which of these a model takes is the model's: some models can't turn thinking off, and a
+ budget and a level together are rejected. A model that rejects a budget of 0 is sent the
+ `"minimal"` level instead, which doesn't guarantee no thinking.
-`SamplingOverrides(inner=api, reasoning=...)` wraps an adapter and pins the reasoning settings of
-every request; despite its name, it overrides reasoning only.
+`SamplingOverrides(inner=api, reasoning=..., speed=...)` wraps an adapter and pins the reasoning
+settings, the speed tier, or both on every request; a field left `None` leaves requests as they
+are. It overrides no other sampling field.
Provider prompt-cache hints (`CacheableContentText`, `CacheableToolParam`, `CacheControl`) ask the
-provider to cache a prompt's prefix. They are unrelated to fxtr's
-[step cache](../../../fxtr/references/concepts/managing-the-step-cache.mdx), which keeps completed step results.
+provider to cache a prompt's prefix. `FinalBlockCacheControl(inner=api)`, from
+`behaviors.implementations.models.overrides`, wraps any adapter and adds a breakpoint to a
+request's final block when that block is non-empty text or a tool result you didn't already mark,
+so each turn of a conversation can read the prefix the previous turn wrote. Whether a breakpoint
+reaches the provider depends on the dialect: Gemini has none, and the Chat Completions adapters send
+them only with `forward_cache_control=True`. An adapter that drops or changes a breakpoint records
+a `cache_breakpoint` loss. Prompt-cache hints are unrelated
+to fxtr's [step cache](../../../fxtr/references/concepts/managing-the-step-cache.mdx), which keeps completed step results.
diff --git a/plugins/fxtr/skills/first-experiment/provenance.json b/plugins/fxtr/skills/first-experiment/provenance.json
index 90d9239..c4ad8f7 100644
--- a/plugins/fxtr/skills/first-experiment/provenance.json
+++ b/plugins/fxtr/skills/first-experiment/provenance.json
@@ -2,10 +2,10 @@
"skill": "first-experiment",
"documentation": null,
"packages": {
- "fxtr": "0.1.0a0",
- "behaviors": "0.0.1a4"
+ "fxtr": "0.2.0a0",
+ "behaviors": "0.0.1a5"
},
- "revision": "052f907cc35979930fda832a71aec0c2194e7e48",
+ "revision": "d4dc6a2e28ca36addbd6aee70256eb22317e1c93",
"modified": false,
"content_sha256": "1b39e083738e6d10b515568bf7912241a1874cda150eb40908b92e7927d38b5f"
}
diff --git a/plugins/fxtr/skills/fxtr/SKILL.md b/plugins/fxtr/skills/fxtr/SKILL.md
index 3ccbdb6..761fd68 100644
--- a/plugins/fxtr/skills/fxtr/SKILL.md
+++ b/plugins/fxtr/skills/fxtr/SKILL.md
@@ -131,6 +131,27 @@ before [adding one](references/reference/renderers.mdx#adding-a-package-to-a-pro
* **Keep the viewer running** across launches and renderer edits. It rebuilds the renderers when
their sources change, and the open viewer switches to them in place, so never ask the user to
reload or restart it.
+* **Link the user to what you are pointing at.** The viewer's URL holds the job, the level shown,
+ the slice, and the open panels, so instead of describing where to click, give the user a link:
+ the viewer's URL (the one `fxtr view` printed, also saved in `.fxtr/viewer.json` within the project), then `#` and `&`-separated parts.
+
+ ```
+ http://127.0.0.1:8000/#job=&w=flowchart(/outer,model=sonnet)&slice=(prompt=3)&card=judge&p=table(/outer/judge,model=sonnet)&p=.output.transcript
+ ```
+
+ `job` is the job's ID (left out, the newest job). `w` is the workflow invocation shown (left
+ out, the root's trace): `trace`, `flowchart`, or the id of an `InvocationPanel` renderer
+ of that workflow, applied to its step path from the root, with the keys of the mapped workflows
+ on the way. `slice` picks dim values for every card and panel. `card` names a step of that workflow (or
+ `return`, what it returned) whose card to scroll to. Each `p` opens a panel, in order,
+ each following the one before it; `pin` opens one that stays as it is. A panel is an address,
+ a view applied to a location and params: the view is `table`, `invocation`, `tree`, `code`, a
+ renderer's or page's id, or nothing for the default; the location is a step path from the root
+ (`/outer/judge`), or `cid:` for an entity, then a field path (`.output.transcript`,
+ `.inputs.prompt`, `[2]` for a list item); params bind dims and the params a view declares, by
+ name, as bare values (`3`, `sonnet`) or JSON (`"two words"`, `{"message":2}`). After the first
+ panel, a location may be relative to the panel before it: `.field…` below it, `../step` a
+ sibling. Percent-encode only spaces, `%`, `&`, `#`, `+`, and quotes.
### Reading the documentation
diff --git a/plugins/fxtr/skills/fxtr/provenance.json b/plugins/fxtr/skills/fxtr/provenance.json
index f6c5e0e..3412604 100644
--- a/plugins/fxtr/skills/fxtr/provenance.json
+++ b/plugins/fxtr/skills/fxtr/provenance.json
@@ -2,10 +2,10 @@
"skill": "fxtr",
"documentation": "https://docs.transluce.ai/fxtr",
"packages": {
- "fxtr": "0.1.0a0",
- "behaviors": "0.0.1a4"
+ "fxtr": "0.2.0a0",
+ "behaviors": "0.0.1a5"
},
- "revision": "052f907cc35979930fda832a71aec0c2194e7e48",
+ "revision": "d4dc6a2e28ca36addbd6aee70256eb22317e1c93",
"modified": false,
- "content_sha256": "4777ef0f3815d1b5efde11039f878d974f8221b50a1ca112904a4ad2e44472b5"
+ "content_sha256": "7b6a9ea55aceabebf1bb2782f5e6164bdaa0f184888404b4ecda71fcf3592248"
}
diff --git a/plugins/fxtr/skills/fxtr/references/concepts/entities-and-custom-types.mdx b/plugins/fxtr/skills/fxtr/references/concepts/entities-and-custom-types.mdx
index 24392dd..8b5c178 100644
--- a/plugins/fxtr/skills/fxtr/references/concepts/entities-and-custom-types.mdx
+++ b/plugins/fxtr/skills/fxtr/references/concepts/entities-and-custom-types.mdx
@@ -87,6 +87,30 @@ class Verdict(DataclassEntity, fxtr_type="org.example.qa.Verdict.v1"):
This is the kind of structure an array value cannot hold, and one of the main reasons to reach for
an entity.
+### Partial values
+
+A value still being produced, such as a conversation whose model is mid-reply, does not yet have
+every field its class requires. `Partial[T]` holds one without loosening `T`: any of `T`'s fields
+may be `None`, and wherever a field holds a tagged dataclass `D` (directly, in a union, or as the
+elements of a tuple, list, or dict), the value there may be a `Partial[D]` instead. Fields not
+given take their dataclass default, or `None`.
+
+```python
+from fxtr.entity_defns.partial import Partial
+
+draft = Partial(Verdict, outcome=Partial(Scored))
+draft.answer # None
+draft = draft.replace(outcome=Scored(score=0.8))
+draft.complete() # IncompletePartialError: answer is still None
+```
+
+`complete()` returns the finished `T`, completing nested partial values, once every required field
+is set; it raises `IncompletePartialError`, naming the path of each missing field, until then.
+`Partial.from_value(value)` wraps a finished value. A partial value has its own type tag, so it is
+never mistaken for, or loaded as, a finished `T`. It can be a field of a tagged dataclass or entity
+(`value: Partial[Verdict]`), and it is what a step publishes with `context.preview` (see
+[Workflows and steps](workflows-and-steps.mdx#the-context-argument)).
+
fxtr currently converts dataclasses to and from their stored form with the
[cattrs](https://catt.rs/) library, with strict settings: unknown fields, missing fields, and
diff --git a/plugins/fxtr/skills/fxtr/references/concepts/workflows-and-steps.mdx b/plugins/fxtr/skills/fxtr/references/concepts/workflows-and-steps.mdx
index aa6a717..36d54cd 100644
--- a/plugins/fxtr/skills/fxtr/references/concepts/workflows-and-steps.mdx
+++ b/plugins/fxtr/skills/fxtr/references/concepts/workflows-and-steps.mdx
@@ -280,7 +280,21 @@ other. A `StepContext` and a `WorkflowContext` both let you:
A `WorkflowContext` additionally has the scheduling operations: `run_step`,
`run_child_workflow`, `add_source_array` for introducing fixed data into the graph, and `combine`
and `stack` for putting handles side by side. A `StepContext` exposes the step's `cache_address`, the
-address its result is stored at.
+address its result is stored at, and `preview`:
+
+* **Preview.** `context.preview(value)` publishes a value showing the result the step is producing,
+ which the viewer shows in the step's panel while it runs. Pass a
+ [partial value](entities-and-custom-types.mdx#partial-values) of what the step will
+ return, or any tagged dataclass. Each call replaces the last, only the latest is kept, and it
+ is saved at most a few times a second, so calling it on every streamed token is fine. A step
+ that fails or is stopped keeps its last preview; when a step completes, its result takes the
+ preview's place and the preview is deleted. When a preview costs more to build than an event
+ costs to handle, such as a long conversation assembled again on every token, pass a function of
+ no arguments returning it instead, `context.preview(lambda: draft.value)`: fxtr calls it only
+ when it saves the preview, and once more if the step fails or is stopped. A preview is not the
+ step's result: nothing reads it but the viewer, which shows it with the value's renderer when
+ the project registers one for previews, else as the same data tree as a finished entity (see
+ [Live previews](../reference/renderers.mdx#live-previews)).
### Registered names
diff --git a/plugins/fxtr/skills/fxtr/references/guides/running-and-viewing-jobs.mdx b/plugins/fxtr/skills/fxtr/references/guides/running-and-viewing-jobs.mdx
index 105b678..ac63d23 100644
--- a/plugins/fxtr/skills/fxtr/references/guides/running-and-viewing-jobs.mdx
+++ b/plugins/fxtr/skills/fxtr/references/guides/running-and-viewing-jobs.mdx
@@ -127,7 +127,9 @@ The first sentence of each step's and workflow's docstring is what appears on it
those as short imperative sentences that tell a reader what the operation does, such as "Compute
mean scores across judges." Leave out edge cases and what the step is mapped over, which the card
already shows. For progress worth reading while a step runs, write log lines with
-`context.log(...)`.
+`context.log(...)`, or publish the result so far with `context.preview(...)`, which the step's
+panel shows as it changes
+(see [Workflows and steps](../concepts/workflows-and-steps.mdx#the-context-argument)).
`EXPERIMENT.md`, at the project root, describes the experiment for someone reading its results:
the question it asks, what it compares or measures and why, and how each score or judgment is
diff --git a/plugins/fxtr/skills/fxtr/references/index.mdx b/plugins/fxtr/skills/fxtr/references/index.mdx
index b16cbdc..3ae1cab 100644
--- a/plugins/fxtr/skills/fxtr/references/index.mdx
+++ b/plugins/fxtr/skills/fxtr/references/index.mdx
@@ -48,7 +48,7 @@ fxtr experiments are organized into *projects*, which have two components.
## Getting Started
fxtr pairs with [**behaviors**](../../behaviors/references/index.mdx), a library for calling language models from fxtr steps. It
-provides model adapters for OpenAI and Anthropic, multi-turn conversations, retries, and
+provides model adapters for OpenAI, Anthropic, and Google, multi-turn conversations, retries, and
storable conversation records.
To get started, follow the [installation guide](installation.mdx) to install fxtr and set up your project and database.
diff --git a/plugins/fxtr/skills/fxtr/references/reference/project-configuration.mdx b/plugins/fxtr/skills/fxtr/references/reference/project-configuration.mdx
index b660a2f..33f727a 100644
--- a/plugins/fxtr/skills/fxtr/references/reference/project-configuration.mdx
+++ b/plugins/fxtr/skills/fxtr/references/reference/project-configuration.mdx
@@ -22,7 +22,8 @@ already depends on fxtr, `uv run fxtr new` does the same):
pyproject.toml the project, its dependency on fxtr, and [tool.fxtr]
README.md how to run it
.gitignore fxtr.local.toml, .env, .venv/, __pycache__/, .fxtr/ (where
- `fxtr view` records its address), node_modules/, and dist/
+ `fxtr view` records its address and the jobs you star),
+ node_modules/, and dist/
.env API keys for model providers
src/my_project/
__init__.py
diff --git a/plugins/fxtr/skills/fxtr/references/reference/renderers.mdx b/plugins/fxtr/skills/fxtr/references/reference/renderers.mdx
index 78c39fc..85c52f7 100644
--- a/plugins/fxtr/skills/fxtr/references/reference/renderers.mdx
+++ b/plugins/fxtr/skills/fxtr/references/reference/renderers.mdx
@@ -31,12 +31,14 @@ const bundle: ViewBundle = {
export default bundle;
```
-| Slot | Subject | Props | What it draws |
-| -------------------- | -------------------------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
-| `EntityPanel` | an entity type tag | `{ id, storage }` | The entity, opened in a pane. |
-| `EntityInlineLink` | an entity type tag | `{ id }` | The entity where it is referenced, inside the viewer's link. It must be static text: no `EntityLink`, buttons, or other interactive elements. |
-| `EntityHoverPreview` | an entity type tag | `{ id }` | A compact preview, shown when a link to the entity is hovered. |
-| `InvocationPanel` | a step's or workflow's registered name | `{ invocations, storage }` | The invocations the viewer's selection picks out; for the root workflow, a view of the whole run. |
+| Slot | Subject | Props | What it draws |
+| --------------------- | -------------------------------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
+| `EntityPanel` | an entity type tag | `{ id, storage }` | The entity, opened in a pane. |
+| `EntityInlineLink` | an entity type tag | `{ id }` | The entity where it is referenced, inside the viewer's link. It must be static text: no `EntityLink`, buttons, or other interactive elements. |
+| `EntityHoverPreview` | an entity type tag | `{ id }` | A compact preview, shown when a link to the entity is hovered. |
+| `PartialEntityPanel` | an entity type tag | `{ value, partial, live, storage }` | A value a running step is producing, its latest `context.preview`, in place of the step's output. See [Live previews](#live-previews). |
+| `PartialEntityInline` | an entity type tag | `{ value, partial, live }` | The same value in one line, in the running step's table row: how far it has got. See [Live previews](#live-previews). |
+| `InvocationPanel` | a step's or workflow's registered name | `{ invocations, storage }` | The invocations the viewer's selection picks out; for the root workflow, a view of the whole run. |
The prop types are `EntityPanelProps`, `EntityViewProps` (the `id` alone), and
`InvocationPanelProps`. Give each renderer an ID prefixed with your project's name. Two renderers
@@ -173,6 +175,47 @@ Register it with `renderer(InvocationPanel, "my_experiment.judge", "my-project.J
JudgePanel)`. `eachInvocation` suits a view of one invocation's record repeated per invocation; a
panel that shows many spawns together, like this one, reads them directly.
+## Live previews
+
+While a step runs, the viewer shows its latest
+[preview](../concepts/workflows-and-steps.mdx#the-context-argument) in place of its output, and
+after it fails, the last one under the error. A preview is not a stored entity, so its renderer is
+handed the value itself, `value`, instead of an ID; the viewer dispatches on the value's type tag as
+for an entity. A type with no `PartialEntityPanel` renderer of its own shows the same data tree as a
+finished entity's raw view, with the fields not yet known as `null`.
+
+Registering a `PartialEntityPanel` renderer for a type is how a renderer opts in to showing its
+values as they stream. `partial` is true while the value is still being produced: then any field may
+be `null` whatever its type says, a list may be shorter than it will be, and nested
+[partial values](../concepts/entities-and-custom-types.mdx#partial-values) are already unwrapped into
+the records they will become. A renderer reading a field unconditionally must treat `null` as "not
+yet". `isPartial(part)` from `fxtr-view` says which parts are still being produced, for one that
+shows a part in progress differently (the reply being written, not one just finished); read it on
+the value as handed over, since a copy of a part is not marked. `live` says whether the step is still
+running: it is false for the last preview of a step that failed or stopped, whose partial value
+will never be finished, so the renderer should not show it as in progress. Share the component with
+the type's `EntityPanel` renderer, so a value looks the same streaming as finished:
+
+```tsx views/src/report.tsx
+import { PartialEntityPanel, renderer, type PartialEntityPanelProps } from "fxtr-view";
+import { ReportView, type ReportData } from "./report_view";
+
+export function ReportPreview({ value, partial, live }: PartialEntityPanelProps) {
+ return ;
+}
+
+export const reportPreview = renderer(PartialEntityPanel, "org.example.Report.v1", "my-project.Report", ReportPreview);
+```
+
+The value changes as new previews arrive without remounting the component, so its state survives.
+A renderer that throws on a preview falls back to the data tree, with its error above it.
+
+A running step's row in a run's table shows the preview in one line, where a finished row shows its
+result's `EntityInlineLink`. A `PartialEntityInline` renderer, given the same props without
+`storage`, says how far the value has got (behaviors' rollout reads "turn 6 · streaming…"); like an
+inline link, it must be static phrasing content. A type with none shows its type name and
+"partial".
+
## Links
Anything that stands for an entity should lead to it. In text and tables, `EntityLink({ id })` is