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..51189e3 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 @@ -33,6 +34,36 @@ The pages below are its documentation. Read the ones a task needs before writing models shows, rather than substituting another. Without credentials to check, take candidate IDs from the provider's published catalog, and tell the user that account access has not been verified. -* **Shape model experiments as the guide does**: one step per conversation, with every setting - that affects the request in a configuration entity; fxtr replicas for repeated samples; and - separate steps for judging and for aggregating verdicts. +* **Make each argument of a model call its own step input.** Then every result points at the + exact settings that produced it, and the cache sees every setting. Hard-code nothing that + affects a request in a step. + * The model is a `model_name` string, such as `openai/gpt-6-luna`. The project's own + `make_api(model_name)` builds the `ModelAPI` from it, and the step closes the API in + `finally`. The string is the record of which model was called: a `Judgment` holds none. + * Sampling is a `SamplingParamsEntity` the project defines, a frozen `DataclassEntity` with one + field, `params: SamplingParams`. An fxtr array can't hold a `SamplingParams` as a value, but + it can hold a reference to an entity. behaviors provides no such type. + * A prompt, a rubric, the judge's instructions, and an output schema (as JSON text) are + `TextEntity` inputs. +* **Shape model experiments as the guide does**: one step per conversation; fxtr replicas for + repeated samples; and separate steps for transcripts, judging, and aggregating judgments. +* **Judge with behaviors' `judge`**, from `behaviors.judging.judge`, which returns a `Judgment`. + Write its output schema with a `behaviors.judging.schemas` function (`binary_schema`, + `continuous_schema`, `categorical_schema`, `structured_schema`). Each starts with a + `discussion`, so the judge explains before it decides. For the instructions, start from + `DEFAULT_SYSTEM_INSTRUCTIONS_ENTITY`, from `behaviors.judging.defaults`. `judge` needs + `jsonschema`, which a project adds itself: `uv add "behaviors[models]" jsonschema`. +* **Point at evidence with a citation, not a number.** When a judge's answer has to name a place + in an entity (the message where a behavior first appears, the line a score rests on), make that + field a citation field, written by a `CustomFormat`'s `schema` method, and ask for exactly one + citation, or an empty string when there is none. The viewer draws such a field as a link that opens the entity at that place. An integer + index is drawn as a bare number. +* **Link a judge's call output first.** When you link the user to one call of a judge step, add + `section_order=output_first` to its `invocation` view, so the judgment shows above the + transcript and rubric it was given: + `p=invocation(/judge,item=0127,judge=sonnet,section_order=output_first)`. +* **Use as many citation fields as the answer needs.** One schema can have several, and they need + not be checked the same way: each way is a `CustomFormat` with a name of its own, which writes + its field with `schema(description=...)` and is passed to `judge` in `custom_formats` (lines in + a discussion, a whole message in a field that points at one). See + [Citations](references/reference/api.mdx#citations). diff --git a/plugins/fxtr/skills/behaviors/provenance.json b/plugins/fxtr/skills/behaviors/provenance.json index ac98808..ca1a050 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": "6432f6ad1682ca0a8ff344a6ef66cb09bbccb8f7", "modified": false, - "content_sha256": "a9a5b26e4b86c7b765f0d3c7ce1ce7bea062364e7112c5bec2ad86aed6ca2f1d" + "content_sha256": "f67fdb291628ed957c6fa39d933926312c3c3864bea083e28264c69666da8d96" } 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..2a088a8 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 ``` @@ -105,6 +124,6 @@ streaming, tools, and reasoning, then try the chosen adapter and sampling settin request before launching a sweep. Without credentials, the providers' published catalogs and documentation give candidate IDs, but not whether your account can use them. -Keep the chosen provider, model ID, and request settings in the experiment's configuration -inputs, so that each run records what was selected (see +Pass the chosen provider and model ID, and each request setting, to the step as inputs, so that +each run records what was selected (see [A conversation as a step](language-models.mdx#a-conversation-as-a-step)). diff --git a/plugins/fxtr/skills/behaviors/references/guides/conversation-records.mdx b/plugins/fxtr/skills/behaviors/references/guides/conversation-records.mdx index 8078f2f..876fc52 100644 --- a/plugins/fxtr/skills/behaviors/references/guides/conversation-records.mdx +++ b/plugins/fxtr/skills/behaviors/references/guides/conversation-records.mdx @@ -12,9 +12,9 @@ are stored and shown, and how they differ from a session's checkpoint. Messages are `SystemMessage`, `UserMessage`, `AssistantMessage`, and `ToolMessage`, each holding a tuple of typed content blocks. An assistant's content may include text, tool calls, reasoning, redacted reasoning, or summarized reasoning, so don't assume every block has `.text`. For the -answer's text alone, keep the `ContentText` blocks of the turn's `AssistantMessage`s, as the -[judge step's](language-models.mdx#a-judge-step) `answer_text` does, and keep the -structured rollout for later inspection. +answer's text alone, keep the `ContentText` blocks of the turn's `AssistantMessage`s, and keep the +structured rollout for later inspection. To give a whole conversation to a judge, flatten it into +a `Transcript`, as the [judge step](language-models.mdx#a-judge-step) does. ## Metadata @@ -72,7 +72,7 @@ initializations, such as `SetSystemMessage`, are fxtr entities, with type IDs of `org.transluce.behaviors..v`, such as `org.transluce.behaviors.ChatRollout.v2`. A version is bumped when a type's stored shape changes, and a record stored under an earlier version doesn't load as the current type. Versions are per type: `ChatRollout` and its turns use `.v2`, -while messages and `ModelResponse` use `.v1`. Only the current version of each type is supported. +messages use `.v1`, and `ModelResponse` uses `.v2`. Only the current version of each type is supported. A step that returns a `ChatRollout` has it stored like any other entity (see [Entities and custom types](../../../fxtr/references/concepts/entities-and-custom-types.mdx)), and 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..35d9727 --- /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. Keywords OpenAI rejects move into descriptions (`response_schema_weakened`). In a strict schema, so do keywords strict mode rejects that constrain only their own field's value, such as a `format` outside OpenAI's list or `uniqueItems`, and the rest stays enforced (`response_schema_weakened`). A strict schema that breaks OpenAI's strict-mode rules in any other way, such as an optional property, is sent without strict mode (`response_format_unenforced`). 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. OpenAI moves keywords out of a strict tool's input +schema as it does for a response schema (`tool_schema_weakened`). Anthropic and OpenAI send a strict +tool whose schema they still 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..92a3f31 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; @@ -17,12 +18,15 @@ description: "Use the behaviors library to hold conversations and judge outputs Add behaviors, with its provider SDKs, to your project: ```bash -uv add "behaviors[models]" +uv add "behaviors[models]" jsonschema ``` +`judge` checks a judge's answers with the `jsonschema` package, which behaviors installs only +with its `docent` extra. + 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,18 +34,26 @@ 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 This step holds a two-turn conversation: it asks a question, then asks the model to explain its -answer. The model and sampling settings arrive as a configuration entity, so every conversation -points at the exact settings that produced it. Keep every setting that affects the request in the -configuration, so that changing one changes the step's inputs. +answer. Each setting of the model call is a step input of its own: + +* `model_name` names the provider and the model, such as `openai/gpt-6-luna`. +* `sampling` holds the sampling settings. +* `system_prompt` and `prompt` are the text the model is sent. + +This way, every conversation points at the exact settings that produced it, and the step cache +sees each one. Don't hard-code a setting that affects the request in the step: changing it would +not change the step's inputs. ```python from dataclasses import dataclass @@ -54,6 +66,7 @@ from behaviors.implementations.context_policies import ( context_policy_from_user_simulator, ) from behaviors.implementations.models import chat_session_model_from_api +from behaviors.implementations.models.anthropic import AnthropicMessagesAPI from behaviors.implementations.models.openai_responses import OpenAIResponsesAPI from behaviors.rollouts.chat import run_chat_rollout from behaviors.types import ( @@ -62,28 +75,40 @@ from behaviors.types import ( ) from fxtr.core.entities import BoundID from fxtr.entity_defns.dataclass_entity import DataclassEntity -from fxtr.experiment.handles import ArrayHandle +from fxtr.experiment.handles import ArrayHandle, ScalarHandle from fxtr.experiment.steps import StepContext, step from fxtr.experiment.workflows import WorkflowContext, workflow @dataclass(frozen=True) -class ConversationConfig(DataclassEntity, fxtr_type="org.example.my_experiment.ConversationConfig.v1"): - model_name: str - sampling: SamplingParams - system_prompt: str +class SamplingParamsEntity(DataclassEntity, fxtr_type="local.my_project.SamplingParamsEntity.v1"): + """Sampling settings stored as an entity, so a step can take them as an input.""" + params: SamplingParams -def make_api(model_name: str) -> OpenAIResponsesAPI: - return OpenAIResponsesAPI(model_name) + +def make_api(model_name: str) -> AnthropicMessagesAPI | OpenAIResponsesAPI: + """The adapter for a model named `anthropic/MODEL` or `openai/MODEL`. The caller closes it.""" + provider, _, model_id = model_name.partition("/") + if provider == "anthropic": + return AnthropicMessagesAPI(model_id) + if provider == "openai": + return OpenAIResponsesAPI(model_id) + raise ValueError(f"Name a model as anthropic/MODEL or openai/MODEL, not {model_name!r}") @step(name="my_experiment.conversation") -async def converse(context: StepContext, config: ConversationConfig, prompt: str) -> ChatRollout: +async def converse( + context: StepContext, + model_name: str, + sampling: SamplingParamsEntity, + system_prompt: str, + prompt: str, +) -> ChatRollout: """Answer a prompt, then explain the answer in a follow-up turn.""" - api = make_api(config.model_name) + api = make_api(model_name) try: - model = chat_session_model_from_api(api, config.sampling, retry=RetryConfig()) + model = chat_session_model_from_api(api, sampling.params, retry=RetryConfig()) user = ScriptedUserSimulator(messages=( UserMessage(content=(ContentText(text=prompt),)), UserMessage(content=(ContentText(text="Explain your answer."),)), @@ -91,7 +116,7 @@ async def converse(context: StepContext, config: ConversationConfig, prompt: str policy = context_policy_from_user_simulator( user, initialization=SetSystemMessage( - message=SystemMessage(content=(ContentText(text=config.system_prompt),)), + message=SystemMessage(content=(ContentText(text=system_prompt),)), ), ) # One more turn than there are scripted prompts, so the rollout can end as completed. @@ -104,14 +129,21 @@ async def converse(context: StepContext, config: ConversationConfig, prompt: str @workflow(name="my_experiment.run") async def experiment( context: WorkflowContext, - configs: Annotated[ArrayHandle[BoundID[ConversationConfig]], "[model: str]"], + model_name: Annotated[ArrayHandle[str], "[model: str]"], + sampling: ScalarHandle[BoundID[SamplingParamsEntity]], + system_prompt: ScalarHandle[str], prompts: Annotated[ArrayHandle[str], "[prompt: str]"], ) -> Annotated[ArrayHandle[BoundID[ChatRollout]], "[model: str, prompt: str]"]: """Hold one conversation per model and prompt.""" rollouts = context.run_step( "conversations", converse, - {"config": configs, "prompt": prompts}, + { + "model_name": model_name, + "sampling": sampling, + "system_prompt": system_prompt, + "prompt": prompts, + }, map_over=["model", "prompt"], ) return cast(ArrayHandle[BoundID[ChatRollout]], rollouts) @@ -119,6 +151,12 @@ async def experiment( In this step: +* `SamplingParamsEntity` is the project's own type. `SamplingParams` is a tagged dataclass, and an + fxtr array can't hold one as a value. An array can hold a reference to an entity, so the + sampling settings are stored as one. The step passes `sampling.params` on to behaviors. +* `make_api` builds the adapter from the model name, splitting off the provider prefix. The + `model_name` input is the stored record of which model the step called. Building every adapter + in this one helper also lets you substitute a fake model for credential-free checks. * `chat_session_model_from_api` wraps the adapter as a conversation model. Pass `retry=RetryConfig()` to retry rate limits, overloads, and server errors; without it, calls aren't retried. @@ -127,15 +165,13 @@ In this step: message. * `run_chat_rollout` alternates between the policy and the model, and returns a `ChatRollout`: the whole conversation, with its status. The step's output is an entity, so fxtr stores it. -* Building the adapter in one helper, `make_api`, lets you substitute a fake model for - credential-free checks. * The adapter is closed in `finally`, because `run_chat_rollout` closes the conversation sessions but not the provider client. Put the step and workflow in a module of your project, here `my_project.conversations`, and list it in `[tool.fxtr] modules` (see -[Project configuration](../../../fxtr/references/reference/project-configuration.mdx)). Launch it with a stored -configuration per model: +[Project configuration](../../../fxtr/references/reference/project-configuration.mdx)). Launch it with the stored +sampling settings and a model name per model: ```python import anyio @@ -144,19 +180,21 @@ from behaviors.types import SamplingParams from fxtr.core.entities import BoundID from fxtr.entity_defns.array import Array from fxtr.project.running import open_local_client, run_job -from my_project.conversations import ConversationConfig, experiment +from my_project.conversations import SamplingParamsEntity, experiment async def main() -> None: async with open_local_client(__file__) as client: - luna = await client.store(ConversationConfig( - model_name="gpt-6-luna", - sampling=SamplingParams(max_tokens=2000), - system_prompt="Answer concisely.", - )) - configs = Array.from_items([(("luna",), luna)], ("[model: str]", BoundID[ConversationConfig])) - prompts = Array.from_items([(("greeting",), "Hello!")], ("[prompt: str]", str)) - await run_job(client, experiment, {"configs": configs, "prompts": prompts}, root="conv-v1") + sampling = await client.store(SamplingParamsEntity(params=SamplingParams(max_tokens=2000))) + inputs = { + "model_name": Array.from_items( + [(("luna",), "openai/gpt-6-luna")], ("[model: str]", str) + ), + "sampling": Array.scalar(sampling, BoundID[SamplingParamsEntity]), + "system_prompt": Array.scalar("Answer concisely.", str), + "prompts": Array.from_items([(("greeting",), "Hello!")], ("[prompt: str]", str)), + } + await run_job(client, experiment, inputs, root="conv-v1") if __name__ == "__main__": @@ -168,131 +206,182 @@ For repeated samples of each conversation, add `replicas={"sample": range(n)}` t ## A judge step -Judging needs no conversation state, so a judge calls the model once with `generate_with_retries`. -This step grades a conversation's final answer and returns a `Verdict` entity, which the viewer -can link to. Put it in the same module as the conversation step, whose `make_api` it uses: +behaviors' `judge` asks a model to assess evidence against a rubric. It checks the model's answer +against an output schema, and sends a rejected answer back with what was wrong. It returns a +`Judgment`, an entity the viewer can show. See [Judging](../reference/api.mdx#judging) for +all of its arguments. + +A judge reads a conversation as a `Transcript`. The first step below flattens a rollout into one +with `ChatRolloutTranscriptProjection`. The second grades the conversation's final answer. Put +both in the same module as the conversation step, whose `SamplingParamsEntity` and `make_api` +they use: ```python -import re -from dataclasses import dataclass -from typing import Annotated +import json +from typing import cast import anyio -from behaviors.implementations.models import ( - DEFAULT_FAILURE_CATEGORIES_TO_RETRY, - generate_with_retries, -) +from behaviors.judging.defaults import DEFAULT_ENTITY_TO_PROMPT_TEXT +from behaviors.judging.judge import Judgment, judge +from behaviors.rollouts.chat import ChatRolloutTranscriptProjection from behaviors.types import ( - AssistantMessage, ChatMessage, ChatRollout, ContentText, ModelCallFailure, - ModelRequest, RetryConfig, RolloutCompleted, SamplingParams, UserMessage, + ChatRollout, ContentText, SystemMessage, TextEntity, Transcript, UserMessage, ) -from fxtr.core.entities import BoundID -from fxtr.entity_defns.array import Array -from fxtr.entity_defns.dataclass_entity import DataclassEntity +from behaviors.types.json import JSONObject from fxtr.experiment.steps import StepContext, step - -@dataclass(frozen=True) -class JudgeConfig(DataclassEntity, fxtr_type="org.example.my_experiment.JudgeConfig.v1"): - model_name: str - sampling: SamplingParams - rubric: str +# The messages the judge is sent. `judge` fills in each {placeholder}: an entity under its name, +# and the output schema the answer must fit. +JUDGE_TEMPLATE = ( + SystemMessage(content=(ContentText(text="{instructions}"),)), + UserMessage(content=(ContentText(text="{transcript}\n\n{rubric}\n\n{output_schema}"),)), +) -@dataclass(frozen=True) -class Verdict(DataclassEntity, fxtr_type="org.example.my_experiment.Verdict.v1"): - score: int | None # None when there was nothing to grade or the reply had no score - judge_reply: str - - -def answer_text(messages: tuple[ChatMessage, ...]) -> str: - """The assistant's text, without reasoning or tool-use blocks.""" - return "".join( - block.text - for message in messages - if isinstance(message, AssistantMessage) - for block in message.content - if isinstance(block, ContentText) - ) +@step(name="my_experiment.transcript") +async def to_transcript(context: StepContext, rollout: ChatRollout) -> Transcript: + """The conversation as a transcript, the form a judge reads.""" + return await ChatRolloutTranscriptProjection().to_transcript(rollout) -@step(name="my_experiment.judge") -async def judge(context: StepContext, judge_config: JudgeConfig, rollout: ChatRollout) -> Verdict: - """Grade the conversation's final answer against the rubric from 0 to 10.""" - if not isinstance(rollout.status, RolloutCompleted) or not rollout.model_turns: - return Verdict(score=None, judge_reply=f"not graded: {rollout.status.kind}") - prompt = ( - f"{judge_config.rubric}\n\n" - f"Answer to grade:\n{answer_text(rollout.model_turns[-1].messages)}\n\n" - "End your reply with a line of the form 'Score: N', where N is from 0 to 10." - ) - request = ModelRequest( - context=(UserMessage(content=(ContentText(text=prompt),)),), - tools=(), - tool_choice=None, - parallel_tool_calls=None, - sampling=judge_config.sampling, - ) - api = make_api(judge_config.model_name) +@step(name="my_experiment.grade_answer") +async def grade_answer( + context: StepContext, + model_name: str, + sampling: SamplingParamsEntity, + instructions: TextEntity, + rubric: TextEntity, + output_schema: TextEntity, + transcript: Transcript, +) -> Judgment: + """Grade the conversation's final answer against the rubric.""" + api = make_api(model_name) try: - response = await generate_with_retries( + return await judge( api, - request, - retry=RetryConfig(), - failure_categories_to_retry=DEFAULT_FAILURE_CATEGORIES_TO_RETRY, + context_template=JUDGE_TEMPLATE, + entities={"instructions": instructions, "rubric": rubric, "transcript": transcript}, + entity_to_prompt_text=DEFAULT_ENTITY_TO_PROMPT_TEXT, + output_schema=cast(JSONObject, json.loads(output_schema.text)), + sampling=sampling.params, ) finally: with anyio.CancelScope(shield=True): await api.aclose() - if isinstance(response, ModelCallFailure): - # Raise rather than return: a returned failure would be cached as the result. - raise RuntimeError(f"judge call failed ({response.category}): {response.description}") - reply = answer_text(response.output) - match = re.search(r"Score:\s*(\d+)\s*$", reply) - score = int(match.group(1)) if match else None - return Verdict(score=score if score is not None and 0 <= score <= 10 else None, judge_reply=reply) ``` -Schedule it in the workflow, mapped over the conversations, with the judge configuration as a -single stored input. The `judge_config: JudgeConfig` and `rollout: ChatRollout` annotations load -the entities before the body runs: +The judge's settings are step inputs, as the conversation's are: + +* `model_name` and `sampling` are the judge model and its sampling settings. A `Judgment` does + not record a model name: the `model_name` input is that record. +* `instructions`, `rubric`, and `output_schema` are `TextEntity` inputs. The output schema is + JSON text, which the step parses. +* The judgment records the ID of each entity it was given, and every request and response. + +Schedule both steps in the workflow, mapped over the conversations. The judge's settings are +workflow inputs with no dimensions, so every call gets the same ones: ```python -verdicts = context.run_step( +# Workflow inputs: +# judge_model_name: ScalarHandle[str] +# judge_sampling: ScalarHandle[BoundID[SamplingParamsEntity]] +# judge_instructions: ScalarHandle[BoundID[TextEntity]] +# rubric: ScalarHandle[BoundID[TextEntity]] +# output_schema: ScalarHandle[BoundID[TextEntity]] +transcripts = context.run_step( + "transcripts", to_transcript, {"rollout": rollouts}, map_over=["model", "prompt"] +) +judgments = context.run_step( "judge_final_answers", - judge, - {"judge_config": judge_config, "rollout": rollouts}, + grade_answer, + { + "model_name": judge_model_name, + "sampling": judge_sampling, + "instructions": judge_instructions, + "rubric": rubric, + "output_schema": output_schema, + "transcript": transcripts, + }, map_over=["model", "prompt"], ) ``` -The judge follows the [return or raise](../../../fxtr/references/concepts/workflows-and-steps.mdx#failures-return-or-raise) -rule: it returns a `Verdict` for outcomes every attempt would reproduce, such as a conversation -that never completed or a reply without a score. It raises when the model call still fails after -its retries, so resuming the job calls the judge again. +The launcher stores the judge's text inputs. `DEFAULT_SYSTEM_INSTRUCTIONS_ENTITY` is behaviors' +default judge instructions. The functions in `behaviors.judging.schemas` (`binary_schema`, +`continuous_schema`, `categorical_schema`, and `structured_schema`) write common output schemas. +Each schema starts with a `discussion` field, so the judge explains before it decides: + +```python +import json + +from behaviors.judging.defaults import DEFAULT_SYSTEM_INSTRUCTIONS_ENTITY +from behaviors.judging.schemas import continuous_schema +from behaviors.types import TextEntity + +RUBRIC = "Grade how correct and well-explained the assistant's final answer is." +OUTPUT_SCHEMA = continuous_schema( + score_description="How good the final answer is, from 0 to 10.", minimum=0, maximum=10 +) + +# In `main`, with the other inputs: +inputs |= { + "judge_model_name": Array.scalar("openai/gpt-6-luna", str), + "judge_sampling": Array.scalar(sampling, BoundID[SamplingParamsEntity]), + "judge_instructions": Array.scalar( + await client.store(DEFAULT_SYSTEM_INSTRUCTIONS_ENTITY), BoundID[TextEntity] + ), + "rubric": Array.scalar(await client.store(TextEntity(text=RUBRIC)), BoundID[TextEntity]), + "output_schema": Array.scalar( + await client.store(TextEntity(text=json.dumps(OUTPUT_SCHEMA))), BoundID[TextEntity] + ), +} +``` + +`judge` follows the [return or raise](../../../fxtr/references/concepts/workflows-and-steps.mdx#failures-return-or-raise) +rule: + +* It returns a `Judgment` whose `output` is `None` when every attempt would end the same way. That + is when the model gave no accepted answer in `max_answers` tries, or when the request is too + long for the model's context. The step returns it, so the result is cached. +* It raises `ModelCallFailedError` when a model call fails for any other reason, such as a rate + limit that outlasts its retries, an outage, or a wrong API key. The step raises too, so resuming + the job calls the judge again. + +The transcript step flattens every conversation, including one that didn't complete, so the judge +grades it as far as it went. To grade only completed conversations, check `rollout.status` first (see +[Check a rollout's status before scoring it](#rollouts-settings-and-testing)). ## Summarize the verdicts -A reduction step takes one model's verdict references and loads them: +A reduction step takes one model's judgment references and loads them: ```python +from typing import Annotated, cast + +from fxtr.core.entities import BoundID +from fxtr.entity_defns.array import Array + + @step(name="my_experiment.mean_score") async def mean_score( context: StepContext, - verdicts: Annotated[Array[BoundID[Verdict]], "[prompt: str]"], + judgments: Annotated[Array[BoundID[Judgment]], "[prompt: str]"], ) -> float | None: """Average the judge's scores across prompts.""" - scores: list[int] = [] - for ref in verdicts.values(): - verdict = await context.load(ref) - if verdict.score is not None: - scores.append(verdict.score) + scores: list[float] = [] + for ref in judgments.values(): + judgment = await context.load(ref) + # `output` is None when the judge never gave an accepted answer. + if judgment.output is not None: + scores.append(float(cast(float, judgment.output["score"]))) return sum(scores) / len(scores) if scores else None # In the workflow: -mean_scores = context.run_step("mean_scores", mean_score, {"verdicts": verdicts}, map_over=["model"]) +mean_scores = context.run_step( + "mean_scores", mean_score, {"judgments": judgments}, map_over=["model"] +) ``` ## Rollouts, settings, and testing @@ -315,10 +404,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/policies-and-tools.mdx b/plugins/fxtr/skills/behaviors/references/guides/policies-and-tools.mdx index 04ff9c3..e74e4de 100644 --- a/plugins/fxtr/skills/behaviors/references/guides/policies-and-tools.mdx +++ b/plugins/fxtr/skills/behaviors/references/guides/policies-and-tools.mdx @@ -41,8 +41,8 @@ When the completion contains ``, the user has left: the simulator e and nothing around the marker is sent. The model is called through the completions endpoint (`/v1/completions`) of an OpenAI-compatible server, such as vLLM or sglang. -Its settings are a `BaseModelUserSimulatorConfig`, a tagged dataclass you can keep in your -step's configuration entity: +Its settings are a `BaseModelUserSimulatorConfig`, a tagged dataclass. A step takes it inside +an entity, as [the step below](#a-step-with-a-simulated-user) does: ```python from behaviors.implementations.context_policies.base_model_prompt import ( @@ -146,9 +146,17 @@ record no rollout. ### A step with a simulated user -This step has a steered, base-model user talk to the subject model. The simulators' settings are -in the configuration entity; where the base model is served is not, since it doesn't change what -is sampled: +This step has a steered, base-model user talk to the subject model. Each setting is a step input +of its own: + +* `subject_model_name` and `subject_sampling` are the subject model and its sampling settings, as + in the [conversation step](language-models.mdx#a-conversation-as-a-step), whose + `SamplingParamsEntity` and `make_api` this step uses. +* `pilot_model_name` is the pilot model. +* `simulated_user` holds the two simulators' configurations. They are tagged dataclasses, and an + fxtr array can't hold one as a value, so they are stored in an entity, `SimulatedUserConfigs`. + +Where the base model is served is not an input, since it doesn't change what is sampled: ```python import os @@ -166,37 +174,44 @@ from behaviors.implementations.context_policies.pilot_steered_user_simulator imp PilotSteeredUserSimulator, PilotSteeredUserSimulatorConfig, ) from behaviors.implementations.models import chat_session_model_from_api -from behaviors.implementations.models.openai_responses import OpenAIResponsesAPI from behaviors.rollouts.chat import run_chat_rollout -from behaviors.types import ChatRollout, RetryConfig, SamplingParams +from behaviors.types import ChatRollout, RetryConfig from fxtr.entity_defns.dataclass_entity import DataclassEntity from fxtr.experiment.steps import StepContext, step +from my_project.conversations import SamplingParamsEntity, make_api @dataclass(frozen=True) -class SimulatedChatConfig(DataclassEntity, fxtr_type="org.example.my_experiment.SimulatedChatConfig.v1"): - subject_model: str - subject_sampling: SamplingParams +class SimulatedUserConfigs(DataclassEntity, fxtr_type="local.my_project.SimulatedUserConfigs.v1"): user: BaseModelUserSimulatorConfig - pilot_model: str pilot: PilotSteeredUserSimulatorConfig @step(name="my_experiment.simulated_chat") -async def simulated_chat(context: StepContext, config: SimulatedChatConfig) -> ChatRollout: +async def simulated_chat( + context: StepContext, + subject_model_name: str, + subject_sampling: SamplingParamsEntity, + pilot_model_name: str, + simulated_user: SimulatedUserConfigs, +) -> ChatRollout: """A conversation between the subject model and a steered, simulated user.""" - subject_api = OpenAIResponsesAPI(config.subject_model) - pilot_api = OpenAIResponsesAPI(config.pilot_model) + subject_api = make_api(subject_model_name) + pilot_api = make_api(pilot_model_name) base_user = BaseModelUserSimulator( - config.user, + simulated_user.user, base_url=os.environ["BASE_MODEL_URL"], # Such as http://localhost:8000/v1. api_key=os.environ.get("BASE_MODEL_API_KEY", "none"), # The SDK needs some key. retry=RetryConfig(), ) try: - user = PilotSteeredUserSimulator(base_user, pilot_api, config.pilot, retry=RetryConfig()) + user = PilotSteeredUserSimulator( + base_user, pilot_api, simulated_user.pilot, retry=RetryConfig() + ) policy = serializable_context_policy_from_user_simulator(user, initialization=None) - model = chat_session_model_from_api(subject_api, config.subject_sampling, retry=RetryConfig()) + model = chat_session_model_from_api( + subject_api, subject_sampling.params, retry=RetryConfig() + ) # The user ends the conversation; max_turns caps one that runs on. return await run_chat_rollout(model, policy, max_turns=12) finally: diff --git a/plugins/fxtr/skills/behaviors/references/guides/rollout-outcomes.mdx b/plugins/fxtr/skills/behaviors/references/guides/rollout-outcomes.mdx index 2800ddb..3f53e7c 100644 --- a/plugins/fxtr/skills/behaviors/references/guides/rollout-outcomes.mdx +++ b/plugins/fxtr/skills/behaviors/references/guides/rollout-outcomes.mdx @@ -30,17 +30,24 @@ 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 `DEFAULT_FAILURE_CATEGORIES_TO_RETRY`: `rate_limited`, `overloaded`, and `server_error`. * For one request, `generate_with_retries(api, request, retry=..., failure_categories_to_retry=...)` - takes the same settings, both required, as in the - [judge step](language-models.mdx#a-judge-step). Once attempts run out, it returns - the last failure. + takes the same settings, both required. Once attempts run out, it returns the last failure. +* `judge`, as in the [judge step](language-models.mdx#a-judge-step), takes the same + two settings, and by default retries `DEFAULT_FAILURE_CATEGORIES_TO_RETRY` with `RetryConfig()`. + Once attempts run out, it raises `ModelCallFailedError`. `RetryConfig` sets the schedule: `max_attempts` (3 by default, counting the first), `initial_backoff_seconds` (1), `backoff_base` (3), `max_backoff_seconds` (120), and @@ -68,10 +75,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..70a1796 100644 --- a/plugins/fxtr/skills/behaviors/references/index.mdx +++ b/plugins/fxtr/skills/behaviors/references/index.mdx @@ -16,8 +16,11 @@ You control the messages, tools, and stopping conditions of an interaction. beha the conversation loop and provides configurable retries and failure recording. Users can be scripted, or simulated by models: a base model writing the user's messages, optionally steered by a chat model (see [Simulated users](guides/policies-and-tools.mdx#simulated-users)). -behaviors supplies no general-purpose judge: you write one for your experiment from its -interfaces, as the [judge step](guides/language-models.mdx#a-judge-step) does. +To have a model judge another model's output, `judge` asks a model to assess evidence against +a rubric and returns its answer, checked against a schema, with its citations (see +[Judging](reference/api.mdx#judging)). The +[judge step](guides/language-models.mdx#a-judge-step) shows `judge` grading a +conversation in an fxtr step. behaviors works with [fxtr](../../fxtr/references/index.mdx): conversation records can be stored as fxtr entities, returned from steps, and inspected in the experiment viewer. fxtr manages the experiment's @@ -35,6 +38,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..4b00683 100644 --- a/plugins/fxtr/skills/behaviors/references/reference/api.mdx +++ b/plugins/fxtr/skills/behaviors/references/reference/api.mdx @@ -11,22 +11,24 @@ 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`. | +| A model's assessment of evidence against a rubric | `judge(model_api, context_template=..., entities=..., ...)`, from `behaviors.judging.judge`; returns a `Judgment`. See [Judging](#judging). | +| 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), @@ -34,9 +36,9 @@ The guides cover the layers above the request: [conversation records and checkpoints](../guides/conversation-records.mdx), and [Docent readings](../guides/docent-readings.mdx). Users simulated by a base model, and steered by a pilot model, are in -[Simulated users](../guides/policies-and-tools.mdx#simulated-users). behaviors supplies no -general judge: build one for your experiment from these interfaces, as the -[judge step](../guides/language-models.mdx#a-judge-step) does. +[Simulated users](../guides/policies-and-tools.mdx#simulated-users). The general judge is +described under [Judging](#judging), and the +[judge step](../guides/language-models.mdx#a-judge-step) shows it in an fxtr step. ## Where things are imported from @@ -50,8 +52,14 @@ 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`. +* `behaviors.judging` holds the judge, each part in a module of its own: `judge` (`judge`, + `fill_context_template`, `CustomFormat`, `Judgment`, `JudgeAttempt`, `InvalidOutputReason`), `schemas` (the output schema functions), + `citations` (`Citation`), `agent_run_evidence` (prompt text and citation checking for agent runs + and transcripts), and `defaults`. `judge` needs the `jsonschema` + package, which `behaviors[docent]` installs. * 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 +82,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 +127,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 +150,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 +163,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 +180,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 +211,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 +265,298 @@ 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. `CacheControl.ttl` sets a breakpoint's lifetime: Anthropic and +Anthropic-style Chat Completions accept `"5m"` or `"1h"`; OpenAI Responses accepts `"30m"` or +`"12h"`. A lifetime is a minimum, so one the destination does not offer becomes the shortest it +offers that is at least as long, or its longest if none is (an OpenAI `"12h"` is sent to +Anthropic as `"1h"`), with a non-semantic `cache_breakpoint` loss. A tool result and its marked +final block end at the same place, so both get the longer of their lifetimes. Anthropic rejects a +longer lifetime after a shorter one, so for Anthropic and Anthropic-style Chat Completions a later +breakpoint is shortened to match. Leaving `ttl=None` inherits the destination's default; for +Responses, that is the request's `prompt_cache_options.ttl` when set. +Prompt-cache hints are unrelated +to fxtr's [step cache](../../../fxtr/references/concepts/managing-the-step-cache.mdx), which keeps completed step results. + +## Judging + +`judge`, from `behaviors.judging.judge`, asks a model to assess evidence against a rubric. It +fills in the request from a template, reads the model's answer as one JSON object, checks the answer, and sends a +rejected answer back to the model with what was wrong. An answer that was cut off at the output +limit is not read: the model is asked for a shorter one. It returns a `Judgment`. + +```python +from behaviors.judging.agent_run_evidence import AGENT_RUN_LINE_CITATION_FORMAT +from behaviors.judging.defaults import DEFAULT_ENTITY_TO_PROMPT_TEXT +from behaviors.judging.judge import Judgment, judge +from behaviors.judging.schemas import binary_schema +from behaviors.types import ( + AgentRun, + ContentText, + SystemMessage, + TextEntity, + UserMessage, +) +from fxtr.experiment.steps import StepContext, step + +# The project's own sampling entity and adapter helper, as in the conversation step of +# "Calling language models". +from my_project.conversations import SamplingParamsEntity, make_api + + +CONTEXT_TEMPLATE = ( + SystemMessage(content=(ContentText(text="{instructions}\n\n{citation_instructions}"),)), + UserMessage(content=(ContentText(text="{run}\n\n{rubric}\n\n{output_schema}"),)), +) + + +@step(name="my_experiment.judge_run") +async def judge_run( + context: StepContext, + instructions: TextEntity, + rubric: TextEntity, + run: AgentRun, + model_name: str, + sampling: SamplingParamsEntity, +) -> Judgment: + api = make_api(model_name) + try: + return await judge( + api, + context_template=CONTEXT_TEMPLATE, + entities={"instructions": instructions, "rubric": rubric, "run": run}, + entity_to_prompt_text=DEFAULT_ENTITY_TO_PROMPT_TEXT, + output_schema=binary_schema( + match_description="True if the agent misreported its results.", + discussion=AGENT_RUN_LINE_CITATION_FORMAT.schema( + description="Why, citing the evidence." + ), + ), + sampling=sampling.params, + custom_formats=[AGENT_RUN_LINE_CITATION_FORMAT], + ) + finally: + await api.aclose() +``` + +The arguments: + +* **`entities`** is everything the model is given, each under a name: the instructions, the + rubric, the evidence. They are fxtr entities, so the judgment can record the ID of each. A + name is letters, digits and underscores. +* **`context_template`** is the messages to send, with a placeholder wherever something should + go. A placeholder is one word in braces. `{run}`, or any other name in `entities`, becomes + that entity as text, enclosed in a section that shows its name. `{output_schema}` becomes the + output schema, and `{citation_instructions}` becomes the instructions for citing an + entity, followed by what each custom format says about the entities it writes (or nothing, when no custom format is used). Other braces, such as those of JSON, are left alone. Only the template is searched: + text that comes from an entity is put in as it is. It is an error for a template to have no + `{output_schema}`, to have a placeholder that is neither of those two nor a name in + `entities`, to have no placeholder for an entity, or to have no `{citation_instructions}` + when a custom format has instructions to put there. +* **`entity_to_prompt_text`** maps the class of each entity to the function that writes + it as text for the prompt, for every class that no custom format writes. + `DEFAULT_ENTITY_TO_PROMPT_TEXT`, from `behaviors.judging.defaults`, has one for an + `AgentRun`, a `Transcript` and a `TextEntity` + (a piece of text as an entity, from `behaviors.types`). `DEFAULT_SYSTEM_INSTRUCTIONS_ENTITY`, from the same module, is + a ready set of instructions for judging agent runs and transcripts. For a rubric or evidence + of your own kind, define an entity class and add a function for it to the mapping. +* **`output_schema`** is the JSON Schema of the answer, which must describe an object. The + functions in `behaviors.judging.schemas` write common ones: `binary_schema`, + `continuous_schema`, `categorical_schema` and `structured_schema` each return the schema of a complete answer that starts with a + `discussion`. To ask for several answers at once, write the outer object by hand and use + these functions for its properties. +* **`custom_formats`** lists every `CustomFormat` the schema uses. A `CustomFormat`, from + `behaviors.judging.judge`, describes one kind of answer field that needs a check JSON Schema + cannot express, such as text with citations. You use the same object twice: + `fmt.schema(description=...)` writes the field into the output schema, and passing `fmt` here + tells `judge` how to check it. Its fields: + + * `name`: the `format` the field has in the schema, such as `"citations"`. + * `value_schema`: the JSON Schema of the value apart from its format, such as + `{"type": "string"}`. + * `validator`: the function that checks the field's value. It takes `entities` and the value, + and returns `None` or a message saying what is wrong. + * `entity_to_prompt_text`: how an entity has to be written into the prompt for the validator + to work, as a mapping from entity class to function. The citation format needs each line of + an agent run labelled, because its validator checks citations against those labels. `judge` + writes entities of those classes with these functions. + * `entity_instructions`: the text that explains that writing to the model, as a mapping from + entity class to text. For the citation format, it says what the line labels are and how to + cite them. `judge` puts the text for each class among `entities` where the template has + `{citation_instructions}`. + + A format that only checks the value leaves both mappings empty. It is an error for the schema + to name a format that is not listed here, to list a format the schema never names, or to list + two with the same name. It is also an error for two formats, or a format and + `entity_to_prompt_text`, to give different functions for the same class, because an entity is + written once. +* **`sampling`** is the sampling parameters for each call, and **`callback`**, if given, + receives the events of each call when the model API can stream. +* **`max_answers`** is how many answers the model gets, 3 by default. An answer that is not + accepted goes back to the model with what was wrong, until it has given this many. +* **`retry`** and **`failure_categories_to_retry`** say when a failed call is made again. By + default, a call that fails from a rate limit, an overloaded provider or a server error is made + again after a wait, up to three calls for one answer (`RetryConfig()`). A failed call that is + made again does not use up one of the model's answers. If your model API already retries + failed calls, the two multiply: pass `retry=RetryConfig(max_attempts=1)` to make each call + once. + +All of these but `callback` change what a judgment can come out as. In a step, pass the ones you +vary as step inputs, so the judgment points at the settings that produced it and the step cache +sees each one: `sampling` in a sampling entity of the project's own, as the example does, and +`max_answers` as a number. A setting kept in the step's code, such as `retry`, is invisible to the +step cache, so clear the step's cached results when you change it. + +To fill in a template of the same kind outside `judge`, use `fill_context_template`, from +`behaviors.judging.judge`. It takes the messages and the text for each placeholder, and follows +the same placeholder rules: + +```python +messages = fill_context_template( + (UserMessage(content=(ContentText(text="Summarize this run.\n\n{run}"),)),), + {"run": agent_run_to_prompt_text(run)}, +) +``` + +It only puts text in. It does not write entities as text, enclose them in named sections, or add +the output schema or the citation instructions, so its result is not the request `judge` would +send. A placeholder with no text given for it is an error. + +### Citations + +The model cites an entity by the name it has in `entities`, in square brackets. With the format +this package ships, a citation is the name, a colon and a line address. For example, +`[run:T0B3L4]` cites transcript 0, block 3, line 4 of the entity named `run`. + +Put `{citation_instructions}` in the template to have this explained to the model, with the +names your entities have. + +`judge` only looks for citations in fields that have a custom format. A field with no custom +format is free text: the model can write anything there, and bracketed text in it is never read +as a citation. When no custom format is used at all, `{citation_instructions}` is replaced with +nothing, so the model is not asked for citations. + +`judge` checks nothing about citations itself. In a field with a custom format, it reads the +citations out and stores them in the judgment. Whether a citation is acceptable is for the +format's validator to decide. + +Bracketed text is read as a citation only when it starts with an entity's exact name. Other +bracketed text, such as `[sic]`, is left alone. + +A citation is read wherever it sits. It does not need a space before or after it, so the second +of `[run:T0B3L1][run:T0B3L2]` is a citation, and so is the one in `lied[run:T0B3L1]`. This also +means indexing with an entity's name, such as `results[run]`, is read as a citation. + +To have the addresses checked, use `AGENT_RUN_LINE_CITATION_FORMAT`, from +`behaviors.judging.agent_run_evidence`: make the field with its `schema(description=...)` +method, which gives it the format `"citations"`, and pass it in `custom_formats`. + +With that format, an agent run or a transcript is cited by line. `judge` writes each one into +the prompt with a label on every message and on every line of it: + +```text +<|T0B3; role: assistant|> +<|L0|>Running the tests. +<|L1|>run({"cmd":"pytest"}) + +``` + +* `T0B3` is block 3 (the fourth message) of transcript 0. A transcript given by itself, not + inside an agent run, has no transcript number: `B3`. +* `L0`, `L1` and so on number the lines of that message. Each non-empty line of its text is a + line, and each tool call is one line. + +A citation names the entity, then a line or a run of lines: + +| Citation | What it cites | +| ------------------- | -------------------------------------- | +| `[run:T0B3L1]` | Line 1 of that message | +| `[run:T0B3L0-1]` | Lines 0 to 1 | +| `[transcript:B3L1]` | A line of a transcript given by itself | + +In a field of this format, every citation has to be a line or a run of lines of an agent run or +a transcript. The format's validator sends an answer back to the model when a citation: + +* names a line, a block or a transcript that does not exist; +* names a whole block (`[run:T0B3]`) or the whole entity (`[run]`); +* has no entity name (`[T0B3L1]`); +* is not well formed: nothing follows the colon (`[run:]`), there is a space before the colon + (`[run :T0B3L1]`), or the address starts or ends with a space (`[run: T0B3L1]`); +* has a name that is not an entity's: `[agent_run:T0B3L1]`, or `[Run]` when the entity is + named `run`; +* cites anything other than an agent run or a transcript. `[rubric]` and + `[rubric:paragraph 3]` are both sent back. + +Bracketed text that is not a citation is left alone, so a judge can quote the evidence. That +includes text with a colon in it, such as `[INFO: tests started]` or `[Note: second run]`. A +wrong name is only reported when the address looks like one of the labels. + +The format also holds the text that explains these labels to the model, so instructions of your +own do not have to. `judge` puts that text where the template has `{citation_instructions}`, +which the template must have when the format is used. The functions that write the labels are +`agent_run_to_prompt_text` and `transcript_to_prompt_text`, which are also the ones in +`DEFAULT_ENTITY_TO_PROMPT_TEXT`. + +The viewer's judgment view opens the cited agent run or transcript at those lines and highlights +them. + +When a field has to name a place in an entity, such as the message where a behavior first +appears, make it a citation field and ask for exactly one citation, or an empty string when +there is none. The viewer draws such a field as a link that opens the entity at that place. A +number that counts to the place, such as a message's index, is drawn as a number. + +One schema can have several citation fields, checked in different ways. Each way is a +`CustomFormat` with a name of its own, such as `"message_citation"`: write each field with its +format's `schema` method and pass every format in `custom_formats`. A format that adds a rule +about the field, such as exactly one citation, and relies on the prompt text of another format +has two empty mappings. + +### The judgment + +A `Judgment` has: + +* `output`: the model's answer, or `None` if no answer was accepted. +* `citations`: a `Citation` for each citation in the answer. It holds the cited entity's ID, + the address, and where the citation is written in the answer (`path_to_output_field`, + `start_in_field` and `end_in_field`). +* `attempts`: a `JudgeAttempt` for every answer the model gave, with the request, the response, + and `invalid_output_reasons`: an `InvalidOutputReason` for each thing wrong with an answer + that was rejected, with the part of the output that is wrong (`path_in_output`) and what is + wrong there (`description`). If a failed call ended the judgment, the last attempt holds that + failure. +* `entity_ids`: the ID of each entity, under the name it was given. + +`judge` follows the +[return or raise](../../../fxtr/references/concepts/workflows-and-steps.mdx#failures-return-or-raise) rule, so a step +can return what it returns: + +* When no answer is accepted within `max_answers`, `judge` returns a judgment whose `output` is + `None`. +* A call that fails in one of `failure_categories_to_retry` is made again, as `retry` says. +* A request too long for the model's context fails on every run, so `judge` returns a judgment + whose `output` is `None`. This is fixed, not an argument: a failure that might pass, returned + instead of raised, would be cached as the step's result. +* Any other failed call, and one that still fails after it was made again, raises + `ModelCallFailedError`, so the step is not cached and runs again when the job is resumed. To + handle such a failure yourself, catch the exception and read its `failure`. + +A judgment refers to its entities by ID, and fxtr only stores a record whose references it +already holds. Pass the instructions, rubric and evidence to the step as inputs, as above. An +entity the step builds itself has to be stored with `await context.store(entity)` before the +step returns the judgment. diff --git a/plugins/fxtr/skills/first-experiment/SKILL.md b/plugins/fxtr/skills/first-experiment/SKILL.md index 7682774..daa0e7e 100644 --- a/plugins/fxtr/skills/first-experiment/SKILL.md +++ b/plugins/fxtr/skills/first-experiment/SKILL.md @@ -123,18 +123,28 @@ that fits: one question, answered with model calls. 4. **What are we measuring?** To make a quantitative comparison between the variables we are studying, we need some way to measure differences in behavior. In some cases, this can just be a pure function (e.g. response length or accuracy), but usually this will involve running a judge or grader model with - a rubric that returns a verdict. Judge models should be asked for a rationale or explanation before - giving a final answer, which should be either a numeric score or a set of named categories. XML - format for structured outputs is a good default. Note that for some exploratory tasks (like seeing + a rubric that returns a verdict. Judge with behaviors' `judge`, and give it an output schema from + `behaviors.judging.schemas`: `continuous_schema` for a numeric score, `categorical_schema` for + named categories, or `binary_schema` for yes or no. Every schema starts with a `discussion`, so + the judge explains its reasoning before it gives its answer. Note that for some exploratory tasks (like seeing how models respond to an open-ended prompt), it might make sense to first generate some initial data and then look at it manually before proposing what the actual rubric or set of outcomes should be! -5. **What data types will we use to represent the experiment?** It usually makes sense to define some - new entity types to hold the results of various parts of your experiment. For some parts of the experiment, you might be able to use the types from the `behaviors` library; in this case you should - just use these. However, other things such as experiment configuration, judge results, and the final - report object should usually be experiment-specific types. By default you should use - "local.{projectname}.{TypeName}" for experiment-specific types (since there is not yet a global - registry of types). +5. **What inputs and data types will the experiment use?** Give each setting of a model call its + own workflow input, so every result points at the exact settings that produced it, and the cache + sees a changed setting: + + * a model is a name with its provider, such as `anthropic/claude-opus-5-5`, which the project's + `make_api` turns into a model API; + * a prompt template is a string, and a rubric, the judge's instructions and the judge's output + schema are `TextEntity` entities; + * sampling settings go in a small entity of the project's own, `SamplingParamsEntity`, because an + array can't hold a `SamplingParams` itself. + + Use behaviors' types for what they cover: `ChatRollout` for a conversation, `Transcript` for what + a judge reads, and `Judgment` for a judge's answer. Define experiment-specific types for the + sampling entity, a per-condition summary, and the final report. By default, name them + "local.{projectname}.{TypeName}" (there is not yet a global registry of types). Show the design in one short block before writing code, along with what each part becomes in fxtr. For example: @@ -150,15 +160,22 @@ Summary: per model, the mean score Size: pilot 2 x 3 x 1 = 6 conversations (6 model calls) + 6 judge calls full 2 x 10 x 3 = 60 conversations (60 model calls) + 60 judge calls -New entity types to define: -- GenerationConfig: provider, model_name, sampling, prompt_template -- JudgeConfig: provider, model_name, sampling, rubric -- JokeGrade: topic, joke, score, rationale, judge_reply -- JokeReport: references to the jokes, grades, and summary arrays +Inputs: +- model_name, over [model]: anthropic/claude-haiku-4-5-20251001, anthropic/claude-sonnet-5-5 +- sampling: one SamplingParamsEntity (max_tokens 1000), shared by the jokes and the judge +- prompt_template, topics, samples +- judge_model_name (anthropic/claude-opus-5-5), judge_sampling, judge_instructions, rubric, + output_schema (a continuous_schema from 1 to 10) + +Types to define: +- SamplingParamsEntity: params +- ModelSummary: jokes, graded, mean_score +- JokeReport: references to the jokes, judgments, and summary arrays Structure of the experiment workflow: - a joke step mapped over [model, topic] replicated over [sample], returning a ChatRollout -- a judge step mapped over [model, topic, sample] +- a transcript step mapped over [model, topic, sample], returning a Transcript +- a judge step mapped over [model, topic, sample], calling `judge` and returning a Judgment - a summary step mapped over [model] ``` @@ -198,13 +215,13 @@ and [Calling language models](../behaviors/references/guides/language-models.mdx Then tell the user what you are about to do, and then write the following: -* **One module** for the experiment, registered in `[tool.fxtr] modules`, holding its - configuration entities, its verdict and report entities, its steps, and its workflow, shaped as - the behaviors skill's best practices say. Pass each step only the fields it uses: a +* **One module** for the experiment, registered in `[tool.fxtr] modules`, holding its sampling + entity, its summary and report types, its `make_api`, its steps, and its workflow, shaped as the + behaviors skill's best practices say. Pass each step only the fields it uses: a conversation step that receives the question's text but not its reference answer doesn't rerun when a reference answer is corrected, and only the judge does. -* **A launcher** at the project root that builds the items, stores a configuration per condition, - runs the workflow, and prints the summary from the report in an `on_result` callback +* **A launcher** at the project root that builds the items, stores the sampling settings and the + judge's instructions, rubric and output schema, runs the workflow, and prints the summary from the report in an `on_result` callback ([Read results](../fxtr/references/guides/running-and-viewing-jobs.mdx#read-results)), so its output ends with the answer rather than the report's ID. Define the pilot and full sizes side by side and choose one with an argument (`uv run python launch.py pilot`), so the full run is @@ -286,7 +303,7 @@ changes on a first experiment: * **Adding a new step at the end** (e.g. for a new analysis): all previous steps will hit the cache, so you can just insert the new step into the workflow in place. * **Changing a step's code** (how answers are parsed or scored): the cache won't notice. Clear - that step's entries, or add a configuration field, as + that step's entries, or add an input that changes with the logic, as [Handling changes to step logic](../fxtr/references/concepts/managing-the-step-cache.mdx#handling-changes-to-step-logic) says, and tell the user which results that recomputes. diff --git a/plugins/fxtr/skills/first-experiment/provenance.json b/plugins/fxtr/skills/first-experiment/provenance.json index 90d9239..7649488 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": "6432f6ad1682ca0a8ff344a6ef66cb09bbccb8f7", "modified": false, - "content_sha256": "1b39e083738e6d10b515568bf7912241a1874cda150eb40908b92e7927d38b5f" + "content_sha256": "a940ab9c02eec8a663fd3ef94d622a4dc88c9a42b4d5f7faa777c4c90b3e340a" } diff --git a/plugins/fxtr/skills/fxtr/SKILL.md b/plugins/fxtr/skills/fxtr/SKILL.md index 3ccbdb6..189edba 100644 --- a/plugins/fxtr/skills/fxtr/SKILL.md +++ b/plugins/fxtr/skills/fxtr/SKILL.md @@ -61,6 +61,7 @@ Running and viewing jobs before the first launch. | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- | | Launch a job, watch it in the viewer, return a report and read results, resume, inspect, or share jobs | [Running and viewing jobs](references/guides/running-and-viewing-jobs.mdx) | | Choose how many steps run at once, or speed up a job whose steps call APIs | [Choose how many steps run at once](references/guides/running-and-viewing-jobs.mdx#choose-how-many-steps-run-at-once) | +| Set up a remote, push a job to a fxtr hub or an OCI registry, or pull one | [Pushing and pulling jobs](references/guides/pushing-and-pulling-jobs.mdx) | | Reuse or recompute cached results, resolve cache conflicts, change a step's logic | [Managing the step cache](references/concepts/managing-the-step-cache.mdx) | | Look up a command's options | [CLI reference](references/reference/cli.mdx) | @@ -131,6 +132,31 @@ 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}`). The `invocation` + view shows one call: its status line, then its inputs, a workflow's runs, and its output; with + `section_order=output_first` the output comes right under the status line instead + (`section_order=inputs_first` is the default). Link output first when the user wants to read + what the call returned. 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..fac62c0 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": "6432f6ad1682ca0a8ff344a6ef66cb09bbccb8f7", "modified": false, - "content_sha256": "4777ef0f3815d1b5efde11039f878d974f8221b50a1ca112904a4ad2e44472b5" + "content_sha256": "3188553424bccd6a1a5b64c814bec89797e7468678f4d4e0fed6540d89636780" } diff --git a/plugins/fxtr/skills/fxtr/references/INDEX.md b/plugins/fxtr/skills/fxtr/references/INDEX.md index 357e8f7..b461ddf 100644 --- a/plugins/fxtr/skills/fxtr/references/INDEX.md +++ b/plugins/fxtr/skills/fxtr/references/INDEX.md @@ -23,6 +23,7 @@ in the order of the site's navigation. - [Running and viewing jobs](guides/running-and-viewing-jobs.mdx): Launch jobs from Python or the command line, watch them in the viewer, read their results, and resume, inspect, or share them. - [Importing external datasets](guides/importing-external-datasets.mdx): Bring external datasets into fxtr as typed arrays for processing in workflows. +- [Pushing and pulling jobs](guides/pushing-and-pulling-jobs.mdx): Share jobs through a fxtr hub or an OCI registry, with fxtr push and pull. ## Reference diff --git a/plugins/fxtr/skills/fxtr/references/concepts/arrays-and-parallel-computations.mdx b/plugins/fxtr/skills/fxtr/references/concepts/arrays-and-parallel-computations.mdx index b5d623b..b51b803 100644 --- a/plugins/fxtr/skills/fxtr/references/concepts/arrays-and-parallel-computations.mdx +++ b/plugins/fxtr/skills/fxtr/references/concepts/arrays-and-parallel-computations.mdx @@ -190,7 +190,7 @@ dimensions to map over, and the runner: flowchart LR M["models
[model]"] --> R["run_step(answer, map_over=[model, prompt])"] P["prompts
[prompt]"] --> R - C["judge config
[] (broadcast)"] --> R + C["sampling
[] (broadcast)"] --> R R --> O["answers
[model, prompt]"] ``` @@ -280,15 +280,15 @@ has. You can choose to instead use an inner join by passing `join="inner"`, whic This is the usual way to pass pieces of a dataset to a step that expects simple values: ```python -# cases: [case_id: str]: Case (a struct with prompt and expected fields) -# judge_config: []: BoundID[JudgeConfig] (a scalar, broadcast to every call) +# cases: [case_id: str]: Case (a struct with prompt and expected fields) +# model_name: []: str (a scalar, broadcast to every call) questions = cases.field("prompt").collect() questions.expect_type(("[case_id: str]", str)) # the field, still keyed by case_id answers = context.run_step( "answer", answer, - {"question": questions, "config": judge_config}, + {"question": questions, "model_name": model_name}, map_over=["case_id"], ) answers.expect_type(("[case_id: str]", BoundID[Answer])) @@ -389,7 +389,7 @@ hard.expect_type(("[case_id: str]", Case)) # fewer rows, same dimensions answers = context.run_step( "answer_hard", answer, - {"question": hard.field("prompt").collect(), "config": judge_config}, + {"question": hard.field("prompt").collect(), "model_name": model_name}, map_over=["case_id"], ) answers.expect_type(("[case_id: str]", BoundID[Answer])) # one row per hard case 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..d47e270 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 @@ -15,13 +15,14 @@ Entities are for three kinds of data: * **Objects with irregular structure.** Array values must follow one fixed schema, but an entity can hold a tagged union, nested optional parts, or a blob of JSON, because it is serialized as a unit rather than laid out in columns. -* **Things other objects should point to.** A judge's verdict about a transcript naturally - references the transcript. A result should reference the configuration that produced it. Entity - references make these links explicit, and the viewer renders them as links you can click. +* **Things other objects should point to.** One example includes the transcripts that you pass to a + judge. When these transcripts are wrapped as entities, it allows fxtr to explicitly link to relevant + parts of the transcript when your LLM judge makes claims in its verdict. These links are rendered in + the viewer and are clickable. Because an entity's ID is a hash of its content, identical content always has the same ID and is -stored once. Storing the same model configuration from a hundred steps costs one record, and two -jobs that reference it reference the very same thing. +stored once. Storing the same entity from a hundred steps costs one record, and two jobs that +reference it reference the very same thing. ## Defining entities @@ -35,14 +36,14 @@ from fxtr.entity_defns.dataclass_entity import DataclassEntity @dataclass(frozen=True) -class ModelConfig(DataclassEntity, fxtr_type="org.example.qa.ModelConfig.v1"): - model_name: str - temperature: float +class Document(DataclassEntity, fxtr_type="org.example.qa.Document.v1"): + title: str + text: str # the whole document, often thousands of words @dataclass(frozen=True) class Answer(DataclassEntity, fxtr_type="org.example.qa.Answer.v1"): - config: BoundID[ModelConfig] + document: BoundID[Document] question: str text: str ``` @@ -54,8 +55,8 @@ that a changed type can be introduced under a new name while old records keep th Fields may be primitives, tuples and frozen sets, nested dataclasses, `BoundID[T]` references to other entities, nullable and union types, and recursive JSON values. The `Answer` above points at -its `ModelConfig` by reference, so every answer records exactly which configuration produced it -without copying the configuration into every record. +its `Document` by reference. Every answer about the same document shares one stored copy of the +document, without copying the entire text into every record. ### Inline tagged unions @@ -84,9 +85,53 @@ class Verdict(DataclassEntity, fxtr_type="org.example.qa.Verdict.v1"): outcome: Scored | Refused ``` +behaviors' `Judgment` uses the same structure: each of its attempts records the model's response +or the failure of the call, as `ModelResponse | ModelCallFailure`. + This is the kind of structure an array value cannot hold, and one of the main reasons to reach for an entity. +The same limit applies to a step's inputs, since every input is an array. Array values must be +primitives, structs, lists, or entity references. A tagged dataclass or a union can't be one. To +pass such a value to a step, wrap it in a small entity and pass a reference to that. Sampling +settings are a common case (behaviors' `SamplingParams` is a tagged dataclass): + +```python +from behaviors.types import SamplingParams + + +@dataclass(frozen=True) +class SamplingParamsEntity(DataclassEntity, fxtr_type="local.my_project.SamplingParamsEntity.v1"): + params: SamplingParams +``` + +Keep the entity to the one value an array can't hold. Pass each other setting, such as a model's +name, as its own input. + +### 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 @@ -144,13 +189,15 @@ read it back. You can store from a step context, a workflow context, or the proj launcher, and all three expose the same two methods: ```python -ref = await context.store(ModelConfig(model_name="gpt-6-luna", temperature=0.2)) -config = await context.load(ref) +ref = await context.store( + Document(title="Refund policy", text="Refunds are issued within 30 days.") +) +document = await context.load(ref) ``` A `BoundID` is cheap to pass around and to put in other entities and arrays. A bare `EntityID`, such as one read out of an array of untyped IDs, needs its type to be loaded: -`await context.load(entity_id, as_type=ModelConfig)`. +`await context.load(entity_id, as_type=Document)`. The only way to get an entity back is to have its ID, and storing an entity gives it no name and puts it in no list you can browse. So for an entity to be retrievable later, something that is @@ -165,12 +212,21 @@ Arrays hold references, never entities themselves. The common pattern is to stor then build the array from the references, with `BoundID[T]` as the value type: ```python -refs = [((name,), await client.store(config)) for name, config in configs.items()] -models = Array.from_items(refs, ("[model: str]", BoundID[ModelConfig])) +refs = [((doc_id,), await client.store(document)) for doc_id, document in documents.items()] +docs = Array.from_items(refs, ("[doc: str]", BoundID[Document])) +``` + +A single reference that every call should receive goes in a scalar array: + +```python +params = SamplingParams(temperature=0.2, max_tokens=1000) +sampling = Array.scalar( + await client.store(SamplingParamsEntity(params=params)), BoundID[SamplingParamsEntity] +) ``` Two shorthands cover the step side. A step annotated to **receive** an entity, as in -`config: ModelConfig`, gets the loaded object rather than the reference. A step annotated to +`document: Document`, gets the loaded object rather than the reference. A step annotated to **return** an entity type, as in `-> Answer`, may return the entity itself: fxtr stores it and records the reference as the step's result, so the mapped results of such a step form an array of `BoundID[Answer]` without any explicit store calls. @@ -185,8 +241,9 @@ and referenced by ID. The rule of thumb: workflow, without needing an identity of its own. "A collection of an X and a Y", dataset rows, sweep coordinates, numbers extracted for aggregation, summary statistics. * Use an **entity** when you want to refer to the thing by ID and point at it from elsewhere, when - it is naturally a single thing rather than a collection of values (a transcript, a verdict, a - configuration, a report), or when its shape is irregular. + it is naturally a single thing rather than a collection of values (a transcript, a document, a + verdict, a report), or when its shape is irregular, such as a tagged dataclass a step takes as + input. The practical differences follow from that: diff --git a/plugins/fxtr/skills/fxtr/references/concepts/managing-the-step-cache.mdx b/plugins/fxtr/skills/fxtr/references/concepts/managing-the-step-cache.mdx index b3c3ec3..d7595ba 100644 --- a/plugins/fxtr/skills/fxtr/references/concepts/managing-the-step-cache.mdx +++ b/plugins/fxtr/skills/fxtr/references/concepts/managing-the-step-cache.mdx @@ -80,7 +80,7 @@ A step's pathname is its default cache address. That has two consequences worth the launcher, as in `root=f"qa-{uuid.uuid4()}"`, and never inside a workflow. Names are not escaped, so never put `/`, `[`, or `]` in a local name, and make names specific: -`comparison_judge_config` reads better in an address than `config`. +`judge_helpfulness` reads better in an address than `judge`. ### Customizing an address @@ -242,8 +242,10 @@ the code produced each result, and the system cannot protect you if you forget. logic. Give the new argument a default that preserves the old behavior. Existing results keep matching, because their inputs are unchanged, and new results computed with the new option have different fingerprints and so can never be confused with old ones. - (You can also bundle configuration arguments into a [config entity](entities-and-custom-types.mdx), - and handle configuration changes by adding a field to that entity.) + You can bundle configuration arguments into a [config entity](entities-and-custom-types.mdx), + and handle configuration changes by adding a field to that entity. + Or, you can make each configuration argument its own entity. The fingerprint then tracks each setting, + and each result points at the exact inputs that produced it. * **If the change is too large for a flag, give the step a new name**, for example by adding a version suffix: `qa.answer` becomes `qa.answer_v2`. The new name gets fresh cache entries, old results stay intact and attributable, and jobs that still reference the old step continue to 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..438c724 100644 --- a/plugins/fxtr/skills/fxtr/references/concepts/workflows-and-steps.mdx +++ b/plugins/fxtr/skills/fxtr/references/concepts/workflows-and-steps.mdx @@ -51,13 +51,15 @@ values indexed by named dimensions, which depth. Inside the workflow you mostly do not touch the arrays' data. You work with **handles** to them, and you pass those handles between the operations you schedule. -Here is a workflow that scores a set of prompts with a model, then asks a child workflow to -summarize the scores: +Here is a workflow that has each model answer a set of prompts, has a judge score each answer, then +asks a child workflow to summarize each model's scores: ```python from typing import Annotated -from fxtr.experiment.handles import ArrayHandle +from behaviors.types import TextEntity +from fxtr.core.entities import BoundID +from fxtr.experiment.handles import ArrayHandle, ScalarHandle from fxtr.experiment.workflows import WorkflowContext, workflow @@ -65,21 +67,40 @@ from fxtr.experiment.workflows import WorkflowContext, workflow async def evaluate( context: WorkflowContext, prompts: Annotated[ArrayHandle[str], "[prompt: str]"], - models: Annotated[ArrayHandle[BoundID[ModelConfig]], "[model: str]"], + model_name: Annotated[ArrayHandle[str], "[model: str]"], + sampling: ScalarHandle[BoundID[SamplingParamsEntity]], + judge_model_name: ScalarHandle[str], + rubric: ScalarHandle[BoundID[TextEntity]], ) -> Annotated[ArrayHandle[float], "[model: str]"]: - """Answer every prompt with every model and summarize each model's scores.""" + """Answer every prompt with every model, judge each answer, and summarize each model.""" answers = context.run_step( - "answer", answer, {"config": models, "question": prompts}, map_over=["model", "prompt"] + "answer", + answer, + {"model_name": model_name, "sampling": sampling, "question": prompts}, + map_over=["model", "prompt"], + ) + judgments = context.run_step( + "score", + score, + { + "rollout": answers, + "model_name": judge_model_name, + "sampling": sampling, + "rubric": rubric, + }, + map_over=["model", "prompt"], + ) + return context.run_child_workflow( + "summarize", summarize, {"judgments": judgments}, map_over=["model"] ) - scores = context.run_step("score", score, {"answer": answers}, map_over=["model", "prompt"]) - return context.run_child_workflow("summarize", summarize, {"scores": scores}, map_over=["model"]) ``` Three things are happening: * `context.run_step(name, step, inputs, ...)` schedules a step and immediately returns a handle to its future result. It does not wait. The `map_over` argument says which dimensions to run the - step once per key of, so `answer` is called once for every model and prompt pair. + step once per key of, so `answer` is called once for every model and prompt pair. `sampling` + has no dimensions, so every call gets the same one. So do the judge's model name and rubric. * Passing the `answers` handle to the `score` step is what makes `score` depend on `answer`. fxtr draws an edge between them in the viewer, and will not start `score` until the answers exist. * `context.run_child_workflow(...)` works the same way for a workflow. Any workflow can be the root @@ -137,44 +158,44 @@ Here is a step that asks a language model one question, using the ```python import anyio -from behaviors.implementations.models import ( - DEFAULT_FAILURE_CATEGORIES_TO_RETRY, - generate_with_retries, +from behaviors.implementations.context_policies import ( + ScriptedUserSimulator, + context_policy_from_user_simulator, ) +from behaviors.implementations.models import chat_session_model_from_api from behaviors.implementations.models.openai_responses import OpenAIResponsesAPI -from behaviors.types import ContentText, ModelCallFailure, ModelRequest, RetryConfig, UserMessage +from behaviors.rollouts.chat import run_chat_rollout +from behaviors.types import ChatRollout, ContentText, RetryConfig, RolloutFailed, UserMessage from fxtr.experiment.steps import StepContext, step @step(name="qa.answer") -async def answer(context: StepContext, config: ModelConfig, question: str) -> Answer: - """Ask the model one question and keep its reply.""" - request = ModelRequest( - context=(UserMessage(content=(ContentText(text=question),)),), - tools=(), - tool_choice=None, - parallel_tool_calls=None, - sampling=config.sampling, - ) - api = OpenAIResponsesAPI(config.model_name) +async def answer( + context: StepContext, model_name: str, sampling: SamplingParamsEntity, question: str +) -> ChatRollout: + """Ask the model one question, and keep the conversation.""" + api = OpenAIResponsesAPI(model_name) try: - response = await generate_with_retries( - api, request, retry=RetryConfig(), - failure_categories_to_retry=DEFAULT_FAILURE_CATEGORIES_TO_RETRY, - ) + model = chat_session_model_from_api(api, sampling.params, retry=RetryConfig()) + user = ScriptedUserSimulator(messages=(UserMessage(content=(ContentText(text=question),)),)) + policy = context_policy_from_user_simulator(user, initialization=None) + # One more turn than there are scripted messages, so the rollout can end as completed. + rollout = await run_chat_rollout(model, policy, max_turns=2) finally: with anyio.CancelScope(shield=True): await api.aclose() - if isinstance(response, ModelCallFailure): - raise RuntimeError(f"model call failed ({response.category}): {response.description}") - return Answer(question=question, text=answer_text(response.output)) + if isinstance(rollout.status, RolloutFailed): + failure = rollout.status.failure + raise RuntimeError(f"model call failed ({failure.category}): {failure.description}") + return rollout ``` -`ModelConfig` and `Answer` are entity types the project defines (see -[Entities and custom types](entities-and-custom-types.mdx)), and `answer_text` is a -small helper that joins the text blocks of the reply. The details of building requests, holding -multi-turn conversations, and judging outputs are in +`ChatRollout` is behaviors' record of a whole conversation, and an entity, so fxtr stores it. +`SamplingParamsEntity` is an entity type the project defines (see +[Entities and custom types](entities-and-custom-types.mdx)). The `score` step judges +each conversation against the rubric with behaviors' `judge`, and returns its `Judgment`. The +details of holding conversations and judging them are in [Calling language models](../../../behaviors/references/guides/language-models.mdx). ### How steps run and get cached @@ -242,15 +263,18 @@ always wrap one in `Annotated[..., "[...]"]`, including `"[]"` for a scalar. For an input that is a reference to an [entity](entities-and-custom-types.mdx), a stored record with an ID of its own, the annotation also decides what the body receives: -* `config: ModelConfig` loads the entity before the body runs. This is the common case. -* `config: BoundID[ModelConfig]` passes a typed reference without loading it, which is what you - want when the step's result should point back at the input. -* `config: EntityID` passes the bare ID. -* `Annotated[Array[BoundID[Document]], "[doc: str]"]` passes a whole array of references. +* `judgment: Judgment` loads the entity before the body runs. This is the common case, as in a + step that reads a judge's score from `judgment.output`. +* `judgment: BoundID[Judgment]` passes a typed reference without loading it, which is what you + want when the step's result should point back at the input, such as a summary row that links to + the judgment it summarizes. +* `judgment: EntityID` passes the bare ID. +* `Annotated[Array[BoundID[Judgment]], "[prompt: str]"]` passes a whole array of references: the + input of `summarize` above, one model's judgments over every prompt. -A step declared to return an entity type, like `-> Answer` above, can return the entity itself. -fxtr stores it and records its reference as the step's result. A step declared to return a struct -returns its `TypedDict`, and a step whose result has dimensions returns an `Array`. +A step declared to return an entity type, like `-> ChatRollout` above, can return the entity +itself. fxtr stores it and records its reference as the step's result. A step declared to return a +struct returns its `TypedDict`, and a step whose result has dimensions returns an `Array`. A workflow's parameters are usually handles. Annotating one with another type makes the runner wait for that input and pass its data instead: `Array[...]` passes the array, a single-value type @@ -280,7 +304,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/first-experiment.mdx b/plugins/fxtr/skills/fxtr/references/first-experiment.mdx index edd7804..3504a87 100644 --- a/plugins/fxtr/skills/fxtr/references/first-experiment.mdx +++ b/plugins/fxtr/skills/fxtr/references/first-experiment.mdx @@ -108,11 +108,12 @@ Size: pilot 2 models x 3 topics x 1 sample = 6 jokes, 6 judge calls Each part of a design becomes a piece of fxtr code: -* **Entities**: Data records that represent objects in your program, such as configuration - objects, measurement results, or a report that collects the final results. Each entity - type has a unique type ID, which fxtr uses to visualize it. -* **Steps**: The functions that do the work. For our joke evaluation: `tell_joke` asks one model for one joke, - `grade_joke` grades one joke, and `summarize` averages one model's grades. +* **Entities**: Data records that represent objects in your program, such as a conversation, + a judge's answer, or a report that collects the final results. Each entity type has a unique + type ID, which fxtr uses to visualize it. +* **Steps**: The functions that do the work. For our joke evaluation: `tell_joke` asks one model + for one joke, `grade_joke` has a judge grade one joke, and `summarize` averages one model's + grades. * **Arrays** hold many values indexed by named **dimensions**, including the variables you are comparing and those you are sweeping over. Each step is *mapped* over some of them to run computations in parallel. For instance, in the joke evaluation, `model`, `topic`, and `sample` are dimensions, and fxtr calls `tell_joke` once per model, topic, and sample. @@ -130,12 +131,13 @@ Create a project and install its dependencies. The commands below use the name uvx fxtr new ~/fxtr/joke-eval cd ~/fxtr/joke-eval uv sync -uv add "behaviors[models]" +uv add "behaviors[models]" jsonschema (cd views && pnpm install) ``` `fxtr new` writes an empty project and makes it a git repository. -[behaviors](../../behaviors/references/index.mdx) is our library for calling language models in fxtr, which your steps can use. +[behaviors](../../behaviors/references/index.mdx) is our library for calling language models in fxtr, which your steps can +use. Its judge checks each answer with `jsonschema`. Next, connect the project to your database: @@ -182,71 +184,44 @@ what they mean. ### Define the entities An entity is a frozen dataclass that fxtr can store and show in the viewer. Each gets a type name -of its own. You'll usually want: +of its own. -* a **configuration** for each kind of model call, holding every setting that affects its output, - so the results always point at the exact settings that produced them; -* a **measurement** entity, such as a grade or a verdict, with the judge's rationale and its full - reply; -* a **report** that references everything the experiment produced, so the launcher, and later a - results view, can find it all from one place. +You can also use existing entities from `behaviors`, such as `ChatRollout` for a conversation and +`Judgment` for a judge's answer. -You can also use existing entities like `ChatRollout` from `behaviors`. - -Here's an example configuration entity for how to generate a joke from a topic: +Here's the entity that holds a model's sampling settings, so a step can take them as an input: ```python @dataclass(frozen=True) -class GenerationConfig(DataclassEntity, fxtr_type="local.joke_eval.GenerationConfig.v1"): - """A model asked for jokes, and the prompt it is asked with.""" +class SamplingParamsEntity(DataclassEntity, fxtr_type="local.joke_eval.SamplingParamsEntity.v1"): + """Sampling settings, stored so a step can take them as an input. An array can hold a + reference to an entity, but not a `SamplingParams` itself.""" - provider: Provider - model_name: str - sampling: SamplingParams - prompt_template: str # formatted with {topic} + params: SamplingParams ``` -You can expand below to see the other types we'll need: +You'll also want a **report** that references the experiment's results, so the launcher, and +later a results view, can find them all from one place. Expand below to see it, and +the summary of each model it refers to: - + ```python - @dataclass(frozen=True) - class JudgeConfig(DataclassEntity, fxtr_type="local.joke_eval.JudgeConfig.v1"): - """A judge model and the rubric it grades jokes with.""" - - provider: Provider - model_name: str - sampling: SamplingParams - rubric: str # formatted with {topic} and {joke} - - - @dataclass(frozen=True) - class JokeGrade(DataclassEntity, fxtr_type="local.joke_eval.JokeGrade.v1"): - """The judge's grade of one joke.""" - - topic: str - joke: str - score: int | None # 1 to 10; None when there was no joke or the reply had no valid score - rationale: str - judge_reply: str - - class ModelSummary(TypedDict): """How one model's jokes were graded. A TypedDict isn't an entity: it's stored inline, as a value in an array.""" jokes: int graded: int - mean_score: float | None + mean_score: float | None # None when no joke was graded @dataclass(frozen=True) class JokeReport(DataclassEntity, fxtr_type="local.joke_eval.JokeReport.v1"): - """Everything the evaluation produced. Each field references a stored array; the comments - give each array's dimensions.""" + """The evaluation's results: the jokes, their judgments, and each model's summary. Each field + references a stored array; the comments give each array's dimensions.""" jokes: BoundID[Array[BoundID[ChatRollout]]] # [model, topic, sample] - grades: BoundID[Array[BoundID[JokeGrade]]] # [model, topic, sample] + judgments: BoundID[Array[BoundID[Judgment]]] # [model, topic, sample] summary: BoundID[Array[ModelSummary]] # [model] ``` @@ -260,30 +235,36 @@ A step is an async function decorated with `@step`. fxtr stores each call's resu **cache**, and reuses it when the same call comes up again. Write one step per call you'd make by hand: one conversation, one judgment, one summary. fxtr handles running them many times. -For our joke evaluation, we can use three steps: +For our joke evaluation, we can use four steps: -* `tell_joke(config, topic)` formats the prompt and holds a one-turn conversation with - `run_chat_rollout`. It returns the `ChatRollout`, a behaviors entity holding the whole - conversation. -* `grade_joke(judge, topic, rollout)` takes the joke's text from the rollout, sends the rubric to - the judge, and reads the `` and `` tags from its reply. A missing joke or an - unreadable score is recorded as a grade with no score. A failed model call raises, so that - fxtr retries it when you resume the job. -* `summarize(grades)` receives one model's grades, as an array over `topic` and `sample`, and - averages their scores. +* `tell_joke(model_name, sampling, prompt_template, topic)` formats the prompt and holds a + one-turn conversation with `run_chat_rollout`. It returns the `ChatRollout`. +* `transcript(rollout)` turns the conversation into a `Transcript`, which fxtr stores, so the + judgment can refer to it and the viewer can show it beside the judgment. A conversation that + didn't complete raises, which stops the job there. +* `grade_joke(model_name, sampling, instructions, rubric, output_schema, transcript)` has a judge + grade the joke with behaviors' `judge`, and returns its `Judgment`. +* `summarize(judgments)` receives one model's judgments, as an array over `topic` and `sample`, + and averages their scores. Here's the step that generates a joke: ```python @step(name="joke_eval.tell_joke") - async def tell_joke(context: StepContext, config: GenerationConfig, topic: str) -> ChatRollout: + async def tell_joke( + context: StepContext, + model_name: str, + sampling: SamplingParamsEntity, + prompt_template: str, + topic: str, + ) -> ChatRollout: """Ask a model for a joke about the topic.""" - prompt = config.prompt_template.format(topic=topic) - api = make_api(config.provider, config.model_name) + prompt = prompt_template.format(topic=topic) + api = make_api(model_name) try: # The model to talk to, which retries rate limits and server errors. - model = chat_session_model_from_api(api, config.sampling, retry=RetryConfig()) + model = chat_session_model_from_api(api, sampling.params, retry=RetryConfig()) # The user's side of the conversation: one scripted message. user = ScriptedUserSimulator(messages=(UserMessage(content=(ContentText(text=prompt),)),)) policy = context_policy_from_user_simulator(user, initialization=None) @@ -296,8 +277,57 @@ Here's the step that generates a joke: ``` -The behaviors guide [Calling language models](../../behaviors/references/guides/language-models.mdx) explains some -common conversation and judge patterns. +The judge step calls `judge`, which fills in a template with the judge's instructions, the +transcript, the rubric and the output schema. It checks the answer against the schema, and sends +it back with what was wrong until it fits. The output schema here asks for a `discussion` of the +joke first, then a `score` from 1 to 10, so the judge explains its reasoning before it scores: + + + ```python + # The messages the judge is sent. `judge` fills in each {placeholder}: the judge's instructions, + # the transcript and the rubric under their names, and the output schema it must answer in. + JUDGE_TEMPLATE = ( + SystemMessage(content=(ContentText(text="{instructions}"),)), + UserMessage(content=(ContentText(text="{transcript}\n\n{rubric}\n\n{output_schema}"),)), + ) + + + @step(name="joke_eval.grade_joke") + async def grade_joke( + context: StepContext, + model_name: str, + sampling: SamplingParamsEntity, + instructions: TextEntity, + rubric: TextEntity, + output_schema: TextEntity, + transcript: Transcript, + ) -> Judgment: + """Grade the joke in the transcript, from 1 to 10.""" + api = make_api(model_name) + try: + # `judge` sends the template filled in, checks the answer against the output schema, and + # asks again when it doesn't fit. A Judgment records the answer, the entities the judge + # was given, and every request and response. + judgment = await judge( + api, + context_template=JUDGE_TEMPLATE, + entities={"instructions": instructions, "rubric": rubric, "transcript": transcript}, + entity_to_prompt_text=DEFAULT_ENTITY_TO_PROMPT_TEXT, + output_schema=cast(JSONObject, json.loads(output_schema.text)), + sampling=sampling.params, + ) + finally: + with anyio.CancelScope(shield=True): + await api.aclose() + # Log lines show on the step's card in the viewer. + context.log(f"score: {None if judgment.output is None else judgment.output['score']}") + return judgment + ``` + + +The behaviors guide [Calling language models](../../behaviors/references/guides/language-models.mdx) explains more +conversation and judge patterns, and the [API overview](../../behaviors/references/reference/api.mdx#judging) covers +`judge`'s options. ### Connect them in a workflow @@ -311,11 +341,17 @@ Our joke evaluation can be defined using the following workflow: @workflow(name="joke_eval.evaluate") async def evaluate( context: WorkflowContext, - # The inputs the launcher supplies, with their dimensions: a configuration per model, the - # topics, and one judge configuration with no dimensions. - models: Annotated[ArrayHandle[BoundID[GenerationConfig]], "[model: str]"], + # The inputs the launcher supplies, with their dimensions. Each model is a name and the + # `[model]` dimension; everything else has no dimensions, so every call gets the same one. + model_name: Annotated[ArrayHandle[str], "[model: str]"], + sampling: ScalarHandle[BoundID[SamplingParamsEntity]], + prompt_template: ScalarHandle[str], topics: Annotated[ArrayHandle[str], "[topic: str]"], - judge: ScalarHandle[BoundID[JudgeConfig]], + judge_model_name: ScalarHandle[str], + judge_sampling: ScalarHandle[BoundID[SamplingParamsEntity]], + judge_instructions: ScalarHandle[BoundID[TextEntity]], + rubric: ScalarHandle[BoundID[TextEntity]], + output_schema: ScalarHandle[BoundID[TextEntity]], samples: int, ) -> JokeReport: """Have each model write jokes about each topic, grade them, and summarize each model.""" @@ -324,33 +360,49 @@ async def evaluate( jokes = context.run_step( "tell_jokes", tell_joke, - {"config": models, "topic": topics}, + { + "model_name": model_name, + "sampling": sampling, + "prompt_template": prompt_template, + "topic": topics, + }, map_over=["model", "topic"], replicas={"sample": range(samples)}, ) - # One call per joke. The judge goes to every call, and each call gets its joke's topic. - grades = context.run_step( + # One call per joke: its conversation as a transcript. + transcripts = context.run_step( + "transcripts", transcript, {"rollout": jokes}, map_over=["model", "topic", "sample"] + ) + # One call per joke. The judge's settings go to every call, and each call gets its transcript. + judgments = context.run_step( "grade_jokes", grade_joke, - {"judge": judge, "topic": topics, "rollout": jokes}, + { + "model_name": judge_model_name, + "sampling": judge_sampling, + "instructions": judge_instructions, + "rubric": rubric, + "output_schema": output_schema, + "transcript": transcripts, + }, map_over=["model", "topic", "sample"], ) - # One call per model, which receives that model's grades over [topic, sample]. - summary = context.run_step("summarize", summarize, {"grades": grades}, map_over=["model"]) + # One call per model, which receives that model's judgments over [topic, sample]. + summary = context.run_step("summarize", summarize, {"judgments": judgments}, map_over=["model"]) # Wait for the results (`observe`), store each array, and return a report that references # them. return JokeReport( jokes=await context.store(await jokes.observe()), - grades=await context.store(await grades.observe()), + judgments=await context.store(await judgments.observe()), summary=await context.store(await summary.observe()), ) ``` * `tell_jokes` is mapped over `model` and `topic`, and `replicas` adds a `sample` dimension, so its result is an array of rollouts indexed by `[model, topic, sample]`. -* `grade_jokes` is mapped over all three. The judge, which has no dimensions, goes to every call, - and each call gets the topic matching its joke. -* `summarize` is mapped over `model` only, so each call receives one model's grades over the +* `transcripts` and `grade_jokes` are mapped over all three. The judge's settings, which have no + dimensions, go to every call, and each call gets the transcript of its joke. +* `summarize` is mapped over `model` only, so each call receives one model's judgments over the remaining dimensions, `[topic, sample]`. [Arrays and parallel computations](concepts/arrays-and-parallel-computations.mdx) explains @@ -371,9 +423,9 @@ experiment module. Here's what it looks like for the joke evaluation: the workflow when it resumes a job or shows one in the viewer. """ - import re + import json from dataclasses import dataclass - from typing import Annotated, Literal, TypedDict + from typing import Annotated, TypedDict, cast import anyio @@ -381,26 +433,24 @@ experiment module. Here's what it looks like for the joke evaluation: ScriptedUserSimulator, context_policy_from_user_simulator, ) - from behaviors.implementations.models import ( - DEFAULT_FAILURE_CATEGORIES_TO_RETRY, - chat_session_model_from_api, - generate_with_retries, - ) + from behaviors.implementations.models import chat_session_model_from_api from behaviors.implementations.models.anthropic import AnthropicMessagesAPI from behaviors.implementations.models.openai_responses import OpenAIResponsesAPI - from behaviors.rollouts.chat import run_chat_rollout + from behaviors.judging.defaults import DEFAULT_ENTITY_TO_PROMPT_TEXT + from behaviors.judging.judge import Judgment, judge + from behaviors.rollouts.chat import ChatRolloutTranscriptProjection, run_chat_rollout from behaviors.types import ( - AssistantMessage, - ChatMessage, ChatRollout, ContentText, - ModelCallFailure, - ModelRequest, RetryConfig, RolloutCompleted, SamplingParams, + SystemMessage, + TextEntity, + Transcript, UserMessage, ) + from behaviors.types.json import JSONObject from fxtr.core.entities import BoundID from fxtr.entity_defns.array import Array from fxtr.entity_defns.dataclass_entity import DataclassEntity @@ -408,28 +458,6 @@ experiment module. Here's what it looks like for the joke evaluation: from fxtr.experiment.steps import StepContext, step from fxtr.experiment.workflows import WorkflowContext, workflow - Provider = Literal["anthropic", "openai"] - - - def make_api(provider: Provider, model_name: str) -> AnthropicMessagesAPI | OpenAIResponsesAPI: - """A client for the provider's API. Both steps build their clients here, so a test can - replace this one function with a fake model.""" - if provider == "anthropic": - return AnthropicMessagesAPI(model_name) - return OpenAIResponsesAPI(model_name) - - - def answer_text(messages: tuple[ChatMessage, ...]) -> str: - """The assistant's text, without reasoning or tool-use blocks.""" - return "".join( - block.text - for message in messages - if isinstance(message, AssistantMessage) - for block in message.content - if isinstance(block, ContentText) - ) - - # --- Entities ------------------------------------------------------------------------------------ # # An entity is a record that fxtr stores in its database and can show in the viewer. A frozen @@ -438,34 +466,11 @@ experiment module. Here's what it looks like for the joke evaluation: @dataclass(frozen=True) - class GenerationConfig(DataclassEntity, fxtr_type="local.joke_eval.GenerationConfig.v1"): - """A model asked for jokes, and the prompt it is asked with.""" + class SamplingParamsEntity(DataclassEntity, fxtr_type="local.joke_eval.SamplingParamsEntity.v1"): + """Sampling settings, stored so a step can take them as an input. An array can hold a + reference to an entity, but not a `SamplingParams` itself.""" - provider: Provider - model_name: str - sampling: SamplingParams - prompt_template: str # formatted with {topic} - - - @dataclass(frozen=True) - class JudgeConfig(DataclassEntity, fxtr_type="local.joke_eval.JudgeConfig.v1"): - """A judge model and the rubric it grades jokes with.""" - - provider: Provider - model_name: str - sampling: SamplingParams - rubric: str # formatted with {topic} and {joke} - - - @dataclass(frozen=True) - class JokeGrade(DataclassEntity, fxtr_type="local.joke_eval.JokeGrade.v1"): - """The judge's grade of one joke.""" - - topic: str - joke: str - score: int | None # 1 to 10; None when there was no joke or the reply had no valid score - rationale: str - judge_reply: str + params: SamplingParams class ModelSummary(TypedDict): @@ -474,35 +479,63 @@ experiment module. Here's what it looks like for the joke evaluation: jokes: int graded: int - mean_score: float | None + mean_score: float | None # None when no joke was graded @dataclass(frozen=True) class JokeReport(DataclassEntity, fxtr_type="local.joke_eval.JokeReport.v1"): - """Everything the evaluation produced. Each field references a stored array; the comments - give each array's dimensions.""" + """The evaluation's results: the jokes, their judgments, and each model's summary. Each field + references a stored array; the comments give each array's dimensions.""" jokes: BoundID[Array[BoundID[ChatRollout]]] # [model, topic, sample] - grades: BoundID[Array[BoundID[JokeGrade]]] # [model, topic, sample] + judgments: BoundID[Array[BoundID[Judgment]]] # [model, topic, sample] summary: BoundID[Array[ModelSummary]] # [model] + # --- Model calls --------------------------------------------------------------------------------- + + + def make_api(model_name: str) -> AnthropicMessagesAPI | OpenAIResponsesAPI: + """A client for a model named `anthropic/MODEL` or `openai/MODEL`. Both steps build their + clients here, so a test can replace this one function with a fake model.""" + provider, _, model_id = model_name.partition("/") + if provider == "anthropic": + return AnthropicMessagesAPI(model_id) + if provider == "openai": + return OpenAIResponsesAPI(model_id) + raise ValueError(f"Name a model as anthropic/MODEL or openai/MODEL, not {model_name!r}") + + + # The messages the judge is sent. `judge` fills in each {placeholder}: the judge's instructions, + # the transcript and the rubric under their names, and the output schema it must answer in. + JUDGE_TEMPLATE = ( + SystemMessage(content=(ContentText(text="{instructions}"),)), + UserMessage(content=(ContentText(text="{transcript}\n\n{rubric}\n\n{output_schema}"),)), + ) + + # --- Steps --------------------------------------------------------------------------------------- # # A step is an async function that does one unit of work. `@step` registers it under a name. fxtr # caches each call's result, and reuses it when the same step is called with the same inputs. - # An argument annotated with an entity type, such as `config: GenerationConfig`, receives the + # An argument annotated with an entity type, such as `sampling: SamplingParamsEntity`, receives the # loaded entity; the `context` gives access to fxtr, such as storing and loading entities. @step(name="joke_eval.tell_joke") - async def tell_joke(context: StepContext, config: GenerationConfig, topic: str) -> ChatRollout: + async def tell_joke( + context: StepContext, + model_name: str, + sampling: SamplingParamsEntity, + prompt_template: str, + topic: str, + ) -> ChatRollout: """Ask a model for a joke about the topic.""" - prompt = config.prompt_template.format(topic=topic) - api = make_api(config.provider, config.model_name) + prompt = prompt_template.format(topic=topic) + api = make_api(model_name) try: # The model to talk to, which retries rate limits and server errors. - model = chat_session_model_from_api(api, config.sampling, retry=RetryConfig()) + model = chat_session_model_from_api(api, sampling.params, retry=RetryConfig()) # The user's side of the conversation: one scripted message. user = ScriptedUserSimulator(messages=(UserMessage(content=(ContentText(text=prompt),)),)) policy = context_policy_from_user_simulator(user, initialization=None) @@ -514,77 +547,64 @@ experiment module. Here's what it looks like for the joke evaluation: await api.aclose() + @step(name="joke_eval.transcript") + async def transcript(context: StepContext, rollout: ChatRollout) -> Transcript: + """The conversation as a transcript, the form a judge reads.""" + if not isinstance(rollout.status, RolloutCompleted): + # Raise rather than return: there is no joke to grade, and the job stops here so you can + # see why the conversation didn't complete. + raise ValueError(f"the conversation did not complete: {rollout.status.kind}") + return await ChatRolloutTranscriptProjection().to_transcript(rollout) + + @step(name="joke_eval.grade_joke") async def grade_joke( - context: StepContext, judge: JudgeConfig, topic: str, rollout: ChatRollout - ) -> JokeGrade: - """Grade a joke from 1 to 10.""" - joke = "" - if isinstance(rollout.status, RolloutCompleted) and rollout.model_turns: - joke = answer_text(rollout.model_turns[-1].messages).strip() - if not joke: - # Return, rather than raise, for outcomes that a retry would reproduce: the result is - # cached as a grade with no score. - return JokeGrade( - topic=topic, joke="", score=None, rationale="", - judge_reply=f"not graded: no joke ({rollout.status.kind})", - ) - - # A judge needs no conversation, so it makes a single request. - request = ModelRequest( - context=(UserMessage(content=(ContentText(text=judge.rubric.format(topic=topic, joke=joke)),)),), - tools=(), - tool_choice=None, - parallel_tool_calls=None, - sampling=judge.sampling, - ) - api = make_api(judge.provider, judge.model_name) + context: StepContext, + model_name: str, + sampling: SamplingParamsEntity, + instructions: TextEntity, + rubric: TextEntity, + output_schema: TextEntity, + transcript: Transcript, + ) -> Judgment: + """Grade the joke in the transcript, from 1 to 10.""" + api = make_api(model_name) try: - response = await generate_with_retries( + # `judge` sends the template filled in, checks the answer against the output schema, and + # asks again when it doesn't fit. A Judgment records the answer, the entities the judge + # was given, and every request and response. + judgment = await judge( api, - request, - retry=RetryConfig(), - failure_categories_to_retry=DEFAULT_FAILURE_CATEGORIES_TO_RETRY, + context_template=JUDGE_TEMPLATE, + entities={"instructions": instructions, "rubric": rubric, "transcript": transcript}, + entity_to_prompt_text=DEFAULT_ENTITY_TO_PROMPT_TEXT, + output_schema=cast(JSONObject, json.loads(output_schema.text)), + sampling=sampling.params, ) finally: with anyio.CancelScope(shield=True): await api.aclose() - if isinstance(response, ModelCallFailure): - # Raise rather than return: a returned failure would be cached as the result, while a - # raised one makes the job stop, and resuming it calls the judge again. - raise RuntimeError(f"judge call failed ({response.category}): {response.description}") - - # Read the score and rationale from the reply's XML tags. - reply = answer_text(response.output) - score_match = re.search(r"\s*(\d+)\s*", reply) - score = int(score_match.group(1)) if score_match else None - rationale_match = re.search(r"(.*?)", reply, re.DOTALL) # Log lines show on the step's card in the viewer. - context.log(f"{score}: {joke}") - return JokeGrade( - topic=topic, - joke=joke, - score=score if score is not None and 1 <= score <= 10 else None, - rationale=rationale_match.group(1).strip() if rationale_match else "", - judge_reply=reply, - ) + context.log(f"score: {None if judgment.output is None else judgment.output['score']}") + return judgment @step(name="joke_eval.summarize") async def summarize( context: StepContext, - # An array, and the dimensions each call receives: all of one model's grades. Its values are - # references to the grades, which the step loads itself. - grades: Annotated[Array[BoundID[JokeGrade]], "[topic: str, sample: int]"], + # An array, and the dimensions each call receives: all of one model's judgments. Its values + # are references to the judgments, which the step loads itself. + judgments: Annotated[Array[BoundID[Judgment]], "[topic: str, sample: int]"], ) -> ModelSummary: """Average one model's scores.""" - scores = [] - for ref in grades.values(): - grade = await context.load(ref) - if grade.score is not None: - scores.append(grade.score) + scores: list[float] = [] + for ref in judgments.values(): + judgment = await context.load(ref) + # A judgment's output is None when the judge never gave an answer that fit the schema. + if judgment.output is not None: + scores.append(float(cast(float, judgment.output["score"]))) return ModelSummary( - jokes=len(grades), + jokes=len(judgments), graded=len(scores), mean_score=sum(scores) / len(scores) if scores else None, ) @@ -600,11 +620,17 @@ experiment module. Here's what it looks like for the joke evaluation: @workflow(name="joke_eval.evaluate") async def evaluate( context: WorkflowContext, - # The inputs the launcher supplies, with their dimensions: a configuration per model, the - # topics, and one judge configuration with no dimensions. - models: Annotated[ArrayHandle[BoundID[GenerationConfig]], "[model: str]"], + # The inputs the launcher supplies, with their dimensions. Each model is a name and the + # `[model]` dimension; everything else has no dimensions, so every call gets the same one. + model_name: Annotated[ArrayHandle[str], "[model: str]"], + sampling: ScalarHandle[BoundID[SamplingParamsEntity]], + prompt_template: ScalarHandle[str], topics: Annotated[ArrayHandle[str], "[topic: str]"], - judge: ScalarHandle[BoundID[JudgeConfig]], + judge_model_name: ScalarHandle[str], + judge_sampling: ScalarHandle[BoundID[SamplingParamsEntity]], + judge_instructions: ScalarHandle[BoundID[TextEntity]], + rubric: ScalarHandle[BoundID[TextEntity]], + output_schema: ScalarHandle[BoundID[TextEntity]], samples: int, ) -> JokeReport: """Have each model write jokes about each topic, grade them, and summarize each model.""" @@ -613,24 +639,40 @@ experiment module. Here's what it looks like for the joke evaluation: jokes = context.run_step( "tell_jokes", tell_joke, - {"config": models, "topic": topics}, + { + "model_name": model_name, + "sampling": sampling, + "prompt_template": prompt_template, + "topic": topics, + }, map_over=["model", "topic"], replicas={"sample": range(samples)}, ) - # One call per joke. The judge goes to every call, and each call gets its joke's topic. - grades = context.run_step( + # One call per joke: its conversation as a transcript. + transcripts = context.run_step( + "transcripts", transcript, {"rollout": jokes}, map_over=["model", "topic", "sample"] + ) + # One call per joke. The judge's settings go to every call, and each call gets its transcript. + judgments = context.run_step( "grade_jokes", grade_joke, - {"judge": judge, "topic": topics, "rollout": jokes}, + { + "model_name": judge_model_name, + "sampling": judge_sampling, + "instructions": judge_instructions, + "rubric": rubric, + "output_schema": output_schema, + "transcript": transcripts, + }, map_over=["model", "topic", "sample"], ) - # One call per model, which receives that model's grades over [topic, sample]. - summary = context.run_step("summarize", summarize, {"grades": grades}, map_over=["model"]) + # One call per model, which receives that model's judgments over [topic, sample]. + summary = context.run_step("summarize", summarize, {"judgments": judgments}, map_over=["model"]) # Wait for the results (`observe`), store each array, and return a report that references # them. return JokeReport( jokes=await context.store(await jokes.observe()), - grades=await context.store(await grades.observe()), + judgments=await context.store(await judgments.observe()), summary=await context.store(await summary.observe()), ) ``` @@ -651,42 +693,44 @@ This is usually a good place to specify global configuration arguments or inputs run your experiment over. The simplest possible launcher is just a `main` script which connects to fxtr, stores the -configurations, builds the workflow's inputs, and runs it. This one asks one model for one joke -about one topic: +entities the workflow takes, builds the workflow's inputs, and runs it. This one asks one model +for one joke about one topic: ```python launch.py +import json + import anyio -from behaviors.types import SamplingParams +from behaviors.judging.defaults import DEFAULT_SYSTEM_INSTRUCTIONS_ENTITY +from behaviors.judging.schemas import continuous_schema +from behaviors.types import SamplingParams, TextEntity from fxtr.core.entities import BoundID from fxtr.entity_defns.array import Array from fxtr.project.running import open_local_client, run_job -from joke_eval.experiment import GenerationConfig, JudgeConfig, evaluate +from joke_eval.experiment import SamplingParamsEntity, evaluate async def main() -> None: async with open_local_client(__file__) as client: - # Store the configurations, getting back references to them. - haiku = await client.store(GenerationConfig( - provider="anthropic", - model_name="claude-haiku-4-5-20251001", - sampling=SamplingParams(max_tokens=1000), - prompt_template='Write one original joke about "{topic}". Reply with the joke only.', - )) - judge = await client.store(JudgeConfig( - provider="anthropic", - model_name="claude-opus-5-5", - sampling=SamplingParams(max_tokens=1000), - rubric=( - 'Rate this joke about "{topic}" from 1 to 10.\n\n{joke}\n\n' - "Explain your rating, then give it as ...N." - ), - )) + # Store the entities the workflow takes, getting back references to them. + sampling = await client.store(SamplingParamsEntity(params=SamplingParams(max_tokens=1000))) + instructions = await client.store(DEFAULT_SYSTEM_INSTRUCTIONS_ENTITY) + rubric = await client.store(TextEntity(text="Rate how funny the joke is, from 1 to 10.")) + schema = continuous_schema(score_description="How funny it is.", minimum=1, maximum=10) + output_schema = await client.store(TextEntity(text=json.dumps(schema))) # Build the workflow's inputs, as arrays with named dimensions, and run it as a job. inputs = { - "models": Array.from_items([(("haiku-4.5",), haiku)], ("[model: str]", BoundID[GenerationConfig])), + "model_name": Array.from_items( + [(("haiku-4.5",), "anthropic/claude-haiku-4-5-20251001")], ("[model: str]", str) + ), + "sampling": Array.scalar(sampling, BoundID[SamplingParamsEntity]), + "prompt_template": Array.scalar('Write one joke about "{topic}". Just the joke.', str), "topics": Array.from_items([(("coffee",), "coffee")], ("[topic: str]", str)), - "judge": Array.scalar(judge, BoundID[JudgeConfig]), + "judge_model_name": Array.scalar("anthropic/claude-opus-5-5", str), + "judge_sampling": Array.scalar(sampling, BoundID[SamplingParamsEntity]), + "judge_instructions": Array.scalar(instructions, BoundID[TextEntity]), + "rubric": Array.scalar(rubric, BoundID[TextEntity]), + "output_schema": Array.scalar(output_schema, BoundID[TextEntity]), "samples": Array.scalar(1, int), } await run_job(client, evaluate, inputs, root="jokes-minimal") @@ -704,17 +748,20 @@ for the joke evaluation: ```python launch.py """Launch the joke evaluation: `uv run python launch.py pilot` or `uv run python launch.py full`.""" + import json import sys from typing import Any import anyio - from behaviors.types import SamplingParams + from behaviors.judging.defaults import DEFAULT_SYSTEM_INSTRUCTIONS_ENTITY + from behaviors.judging.schemas import continuous_schema + from behaviors.types import SamplingParams, TextEntity from fxtr.core.entities import BoundID, FxtrEntityStorage from fxtr.entity_defns.array import Array from fxtr.project.client import JobNotFinishedError, ProjectClient from fxtr.project.running import open_local_client, run_job - from joke_eval.experiment import GenerationConfig, JokeReport, JudgeConfig, Provider, evaluate + from joke_eval.experiment import JokeReport, SamplingParamsEntity, evaluate # The name of this run. Every cached result's address starts with it, so launching again under the # same root reuses earlier results, and a new root starts fresh. @@ -723,16 +770,27 @@ for the joke evaluation: # How many topics (from the start of TOPICS) and samples per model and topic each size uses. SIZES = {"pilot": (3, 1), "full": (10, 3)} - # Each model's short name (its key in the `model` dimension), provider, and model ID. - MODELS: dict[str, tuple[Provider, str]] = { - "haiku-4.5": ("anthropic", "claude-haiku-4-5-20251001"), - "sonnet-5.5": ("anthropic", "claude-sonnet-5-5"), + # Each model's short name (its key in the `model` dimension), and its provider and model ID. + MODELS = { + "haiku-4.5": "anthropic/claude-haiku-4-5-20251001", + "sonnet-5.5": "anthropic/claude-sonnet-5-5", } - JUDGE: tuple[Provider, str] = ("anthropic", "claude-opus-5-5") + JUDGE = "anthropic/claude-opus-5-5" + + # The sampling settings of every model call, the jokes' and the judge's. + SAMPLING = SamplingParams(max_tokens=1000) TOPICS = [ - "coffee", "dentist", "printer", "penguin", "Monday", - "airport", "houseplant", "spreadsheet", "cat", "elevator", + "coffee", + "dentist", + "printer", + "penguin", + "Monday", + "airport", + "houseplant", + "spreadsheet", + "cat", + "elevator", ] JOKE_PROMPT = ( @@ -741,50 +799,45 @@ for the joke evaluation: ) RUBRIC = """\ - You are judging a joke about "{topic}". Rate how funny it is, from 1 (not funny at all) to 10 \ - (a joke a professional comedian would be proud of). A typical competent joke is around 5. \ - Score a well-known joke, or a stock format with the topic swapped in, low. - - - {joke} - - - First explain your rating in two or three sentences, then give the score, in this form: - ... - N""" + Rate how funny the assistant's joke about the user's topic is, from 1 (not funny at all) to 10 (a + joke a professional comedian would be proud of). A typical competent joke is around 5. Score a + well-known joke, or a stock format with the topic swapped in, low. If the assistant gave no joke, + score 1.""" + + # The shape of the judge's answer: a `discussion` of its reasons first, then a `score`. + OUTPUT_SCHEMA = continuous_schema( + score_description="How funny the joke is, from 1 to 10.", minimum=1, maximum=10 + ) async def build_inputs(client: ProjectClient, size: str) -> dict[str, Array[Any]]: """The workflow's inputs, as arrays keyed by the names of its arguments.""" topic_count, samples = SIZES[size] - # Store a configuration entity per model. `client.store` returns a reference (a BoundID) to - # the stored entity, which is what the workflow takes. - models = [] - for name, (provider, model_name) in MODELS.items(): - config = GenerationConfig( - provider=provider, - model_name=model_name, - sampling=SamplingParams(max_tokens=1000), - prompt_template=JOKE_PROMPT, - ) - models.append(((name,), await client.store(config))) - provider, model_name = JUDGE - judge = JudgeConfig( - provider=provider, - model_name=model_name, - sampling=SamplingParams(max_tokens=1000), - rubric=RUBRIC, - ) + # `client.store` stores an entity and returns a reference to it (a BoundID). The jokes and the + # judge share one sampling entity. + sampling = await client.store(SamplingParamsEntity(params=SAMPLING)) # `Array.from_items` builds an array from (key, value) pairs, given its dimensions and value # type; `Array.scalar` builds one with no dimensions. return { - "models": Array.from_items(models, ("[model: str]", BoundID[GenerationConfig])), + "model_name": Array.from_items( + [((name,), model_name) for name, model_name in MODELS.items()], ("[model: str]", str) + ), + "sampling": Array.scalar(sampling, BoundID[SamplingParamsEntity]), + "prompt_template": Array.scalar(JOKE_PROMPT, str), "topics": Array.from_items( [((topic,), topic) for topic in TOPICS[:topic_count]], ("[topic: str]", str) ), - "judge": Array.scalar(await client.store(judge), BoundID[JudgeConfig]), + "judge_model_name": Array.scalar(JUDGE, str), + "judge_sampling": Array.scalar(sampling, BoundID[SamplingParamsEntity]), + "judge_instructions": Array.scalar( + await client.store(DEFAULT_SYSTEM_INSTRUCTIONS_ENTITY), BoundID[TextEntity] + ), + "rubric": Array.scalar(await client.store(TextEntity(text=RUBRIC)), BoundID[TextEntity]), + "output_schema": Array.scalar( + await client.store(TextEntity(text=json.dumps(OUTPUT_SCHEMA))), BoundID[TextEntity] + ), "samples": Array.scalar(samples, int), } @@ -869,13 +922,13 @@ uv run python launch.py pilot ``` ```text -job 06bb0ae8-f73c-4995-acf3-2ab0b299b259: running -watch it at http://127.0.0.1:8000/#job=06bb0ae8-f73c-4995-acf3-2ab0b299b259 +job 36b84ead-fcbc-435d-96b3-b94f47d37a6a: running +watch it at http://127.0.0.1:8000/#job=36b84ead-fcbc-435d-96b3-b94f47d37a6a sent it to the viewer's open tab -job 06bb0ae8-f73c-4995-acf3-2ab0b299b259: succeeded - result: bafyreicl5xf4h3itncd34nnehfpoae6hnqpcumrty7o4ffjpirgidfaray -haiku-4.5: mean score 2.67 (3 of 3 jokes graded) -sonnet-5.5: mean score 3.67 (3 of 3 jokes graded) +job 36b84ead-fcbc-435d-96b3-b94f47d37a6a: succeeded + result: bafyreifrqrpsm354vsfawbhc7jlqa3mwqmscs7epjmve2u3idtrvddctnu +haiku-4.5: mean score 2.00 (3 of 3 jokes graded) +sonnet-5.5: mean score 3.83 (3 of 3 jokes graded) ``` The launcher prints the job's ID and a link, and the viewer switches to the job. It shows the @@ -885,7 +938,8 @@ Try clicking through the results: * Open the card of the step that generates conversations (`tell_jokes`) to see its result array. Each value links to a conversation. -* Open a measurement from the judge step (`grade_jokes`) to read the judge's rationale. +* Open a judgment from the judge step (`grade_jokes`) to read the judge's discussion and score, + beside the transcript it judged. * Open the result of the summary step (`summarize`) to see the result per condition. You can use the viewer to read a few conversations and their measurements, and figure out if there is anything that you want to change in the experiment before you scale it up. @@ -906,7 +960,7 @@ uv run python launch.py full ``` It reuses all of the pilot's results and computes only the new ones: in the example, the other 54 -jokes and 54 grades. Then it stops: +jokes, their transcripts and their judgments. Then it stops: ```text job 4c713924-2fc5-4d9c-a55d-0ae1bdca398f: stopped @@ -942,14 +996,14 @@ sonnet-5.5: mean score 3.57 (30 of 30 jokes graded) ### Add a condition -Next, you can add a condition as a new key of the dimension you compare. In the example, add Opus 5.5 to -`MODELS` in `launch.py`: +Next, you can add a condition as a new key of the dimension you compare. In the example, add +Opus 5.5 to `MODELS` in `launch.py`: ```python -MODELS: dict[str, tuple[Provider, str]] = { - "haiku-4.5": ("anthropic", "claude-haiku-4-5-20251001"), - "sonnet-5.5": ("anthropic", "claude-sonnet-5-5"), - "opus-5.5": ("anthropic", "claude-opus-5-5"), +MODELS = { + "haiku-4.5": "anthropic/claude-haiku-4-5-20251001", + "sonnet-5.5": "anthropic/claude-sonnet-5-5", + "opus-5.5": "anthropic/claude-opus-5-5", } ``` @@ -1001,7 +1055,8 @@ how views work. You've built, run, and changed your first experiment. From here, you could: * Refine the rubric, or add a second judge to see whether the judges agree (in the example, - whether Opus favors its own jokes). + whether Opus favors its own jokes). Give the judge's model name and sampling a `[judge]` + dimension of their own, and map the judge step over it too. * Study a follow-up question about something you noticed in the conversations. * Start an experiment on another question, by hand or with the `first-experiment` skill. diff --git a/plugins/fxtr/skills/fxtr/references/guides/designing-views.mdx b/plugins/fxtr/skills/fxtr/references/guides/designing-views.mdx index a905891..6e63897 100644 --- a/plugins/fxtr/skills/fxtr/references/guides/designing-views.mdx +++ b/plugins/fxtr/skills/fxtr/references/guides/designing-views.mdx @@ -223,7 +223,8 @@ draws follows this guide: its own colors, fonts, tooltips, and fixed sizes do no * **Links.** Anything that stands for an entity leads to it. In text and tables, write an `EntityLink` (a chip the viewer draws: pressing opens the entity, hovering shows its preview). - The viewer labels the chip with the entity's type and a short ID, so put a readable name + The viewer labels the chip with the type's `EntityInlineLink` renderer, or with the entity's type + and a short ID when it has none. A label of that second kind names little, so put a readable name beside it (a row's guest, a model's name), as the viewer's own tables put a key beside a value. A chart's mark cannot be a chip, so a mark standing for an entity takes `const links = useEntityLinks()` from `fxtr-view`: pressing it calls `links.open(id)`, which diff --git a/plugins/fxtr/skills/fxtr/references/guides/pushing-and-pulling-jobs.mdx b/plugins/fxtr/skills/fxtr/references/guides/pushing-and-pulling-jobs.mdx new file mode 100644 index 0000000..f5b4950 --- /dev/null +++ b/plugins/fxtr/skills/fxtr/references/guides/pushing-and-pulling-jobs.mdx @@ -0,0 +1,318 @@ +--- +title: "Pushing and pulling jobs" +description: "Share jobs through a fxtr hub or an OCI registry, with fxtr push and pull." +--- + +A **remote** is a place to push jobs to and pull them from. A push sends one job's record, the +same record that `fxtr jobs export` writes, to the remote. A pull gets it back and imports it, so +a pull refuses what an import refuses. There are two kinds of remote. A `hub` remote publishes +jobs to a fxtr hub, which keeps a team's jobs, lists them, and shows each in the experiment +viewer in the browser ([A hub remote](#a-hub-remote)). An `oci` remote keeps jobs in an OCI +registry, the kind that holds container images; the usual setup is the GitHub Container Registry +(GHCR) for the jobs and the project's GitHub repository for the commits they need +([An OCI remote](#an-oci-remote)). + +## Set up a remote + +A project's remotes have names, as git remotes do, and a push goes to one of them. A project +with no remote has nowhere to push: add one first, with `fxtr remote add`. + +To use a hub, run this from the project's directory: + +```bash +uv run fxtr remote add hub --create +``` + +This makes a project on the hub at `https://hub.transluce.org`, for the GitHub +repository of your checkout's `origin`, and adds it as the remote `hub`. Anyone who can read +the GitHub repository can create a project for it, and is the project's admin. +`origin` can use an SSH host name from your SSH configuration, such as one for a second GitHub +account, as long as it resolves to `github.com`. +`--project-name` names the project (the `[project]` name by default). To use another hub, give +its URL after the remote's name. + +The command opens your browser for the steps that have to happen there, and continues when you +finish them: + +* If this computer is not connected to the hub, you sign in (with GitHub, or an email address) + and approve the connection. `uv run fxtr hub login` does this step alone. The connection lasts + until the computer goes a year without using it. +* If the hub's GitHub App is not installed on the repository, you install it on GitHub's page. + GitHub then opens a page on the hub; go back to your terminal, where the command continues and + makes the project. In an organization you do not own, GitHub asks an owner to approve. If that + takes longer than the command waits (15 minutes), run the command again once it is approved. + +On a computer with no browser, `--no-browser` prints the links to open elsewhere. + +If this directory of the repository already has a hub project, the command lists it and asks whether +to use it or make another, since a project cannot be deleted. A script gets a refusal that names the +projects: use `--project-id ID`, or `--another` to make another project. + +Outside a terminal, the command does neither step: it stops and says what is needed. A script or +a CI job signs in with an access token: make one on the hub's account page, under Computers and +tokens, and set `FXTR_HUB_TOKEN` to it. + +To push to a hub project that exists already, give its id, which the project's page on the hub +shows: + +```bash +uv run fxtr remote add team https://hub.example.com --project-id HUB-PROJECT-ID +``` + +`remote add` writes the remote to `pyproject.toml` and updates the project's virtual environment. +Commit the file, and every checkout of the repository pushes to the same project, with no setup +beyond signing in. `fxtr run` refuses uncommitted changes, so commit it before your next run; a push +of a job you have already run does not need it. Add `--local` to write +it to `fxtr.local.toml` instead, for this computer only. The remote names the hub project by its +id, so moving or renaming the project's directory in the repository changes nothing. + +A project can have any number of remotes, and you can push the same job to each: + +```bash +uv run fxtr remote add archive --create --another --project-name "Lab archive" +uv run fxtr push JOB --remote archive +uv run fxtr remote list # * marks the default +uv run fxtr remote set-default archive +uv run fxtr remote rename archive old-archive +uv run fxtr remote remove old-archive # the jobs it holds stay there +``` + +The default remote is the one a push or a pull uses when it names none. The first remote you add +becomes the default. `set-default --local` sets this computer's default, which overrides the +committed one. A project with exactly one remote and no default uses that one. + +A remote is a table, which `remote add` writes and you can also write by hand: + +```toml pyproject.toml +[tool.fxtr] +modules = ["my_experiments.steps"] +default_remote = "team" + +[tool.fxtr.remotes.team] +kind = "hub" +url = "https://hub.example.com" +project = "HUB-PROJECT-ID" # from the project's page on the hub +git_remote = "origin" # the default + +[tool.fxtr.remotes.registry] +kind = "oci" +repository = "ghcr.io/OWNER/PROJECT-jobs" # lowercase +git_remote = "origin" # the default +annotations = { "org.opencontainers.image.source" = "https://github.com/OWNER/PROJECT" } +``` + +In `fxtr.local.toml`, `default_remote` goes at the top of the file and a remote is a +`[remotes.NAME]` table. A name can be configured in only one of the two files. fxtr checks a remote's settings when a push +or a pull uses it. + + + The kind of remote: `hub` or `oci`. + + + + The git remote that a push sends the job's commits to, and that a pull fetches them from. + + +A `hub` remote has these settings. The URL must be `https`, except `http` to `localhost`, +`127.0.0.1`, or `::1` for a hub running on your computer: your credential is sent with every +request, and it goes only where no one on the way can read it. Log in to that hub's URL with +`fxtr hub login URL`. + + + The hub's origin. + + + + The id of the hub project, shown on the project's page on the hub. + + +An `oci` remote has these settings, and needs the `oci` extra: add it to the +project's fxtr dependency, for example `fxtr[runner,oci]`. +`fxtr remote add registry ghcr.io/OWNER/PROJECT-jobs --kind oci` adds one with its +repository; write its other settings into its table. + + + The registry repository that holds the jobs, as `HOST/PATH`, with no tag. + + + + More annotations for each push, as names to strings. Names that fxtr writes itself + (`org.opencontainers.image.created`, and names that start with `org.transluce.fxtr.`) are + refused. + + + + The only credential file to read for this remote, relative to the project root. + + + + Talk to the registry over plain HTTP, for a local registry. + + +## Push and pull + +Only a job that nothing is running can be pushed. + +```bash +uv run fxtr push # choose from the newest jobs +uv run fxtr push JOB # publish the job +uv run fxtr push JOB --tag paper-v1 # add a tag; repeat --tag for more +``` + +With no job, the command shows the newest jobs and asks which to push. Press Enter for the first +one listed; a job that is still running is shown, but cannot be chosen: + +``` + 1 word_count (word-count-v1) succeeded 4 minutes ago 3f2a91c0 + 2 word_count (root) stopped 2 hours ago 88be1042 + - sweep (root) running 2 hours ago c01d77e2 +Push which job to hub? [1]: +``` + +Outside a terminal, as in a script or a CI job, it lists the jobs and stops without pushing. A +script names the job; `fxtr jobs list` starts each line with a job's id, newest first: + +```bash +uv run fxtr push "$(uv run fxtr jobs list --limit 1 | cut -d' ' -f1)" +``` + +A hub push creates only the tags you supply. An OCI push with no tags generates +`-