Connecting your own model
System One and System Two are functions. A request goes in, an answer comes out.
Every sandbox so far answers Sam's card with recordedModel(), answers a real model gave once. Sam's app will call a model of its own before the birthday dinner. First Sam wants to see exactly what the card asks, and to try the card with a few rules of their own.
You will learn
- How to write System One as a function:
model.judge - What a
ModelRequestcarries - How to answer later with a promise, and see what is on its way with
intent.pending() - How a request nobody needs any more is stopped, with an
AbortSignal - What happens to a request that fails
- How to ask a System One model like Jev:
useChoice,useScore,useWhether,shape,describe
System One is a function
Sam's System One, written by hand in index.intent.tsx. A formal dinner makes a formal card, and anything else a warm one.
/** @jsxImportSource @reintent/core */
import { action, choices, createContext, host, useChoiceStatus, type Id } from '@reintent/core';
export type Person = { to: string; age: number; from: string };
export const TONES = ['warm', 'funny', 'formal'] as const;
export type Tone = (typeof TONES)[number];
export const GRANDMA: Person = { to: 'Grandma', age: 90, from: 'Sam' };
/** What a button does: the intent gives it to every evaluation (index.intent.tsx). */
export const Decide = createContext<(id: Id, value: unknown) => void>('Decide', { key: () => undefined });
/** What “no preference” does: forget the person's decision, so the choice resolves on its own again. */
export const Forget = createContext<(id: Id) => void>('Forget', { key: () => undefined });
export const LOOK: Record<Tone, { background: string; accent: string }> = {
warm: { background: '#fdebd3', accent: '#b5562b' },
funny: { background: '#fff2a8', accent: '#7a4fd6' },
formal: { background: '#f1eee8', accent: '#2b2b2b' },
};
export function title(p: Person, tone: Tone) {
if (tone === 'formal') return `Many happy returns, ${p.to}.`;
if (tone === 'warm') return `Happy ${p.age}th birthday, ${p.to}!`;
return `${p.age} laps around the sun, ${p.to}!`;
}
/** The card's tone, and which layer it came from: System One weighs it; a person's decision is above its judgment. */
export function useToneStatus() {
return useChoiceStatus(choices<Tone>(...TONES), {
of: 'card',
name: 'tone',
defaultValue: 'warm',
question: 'Which tone suits a birthday card for Grandma, turning 90?',
ask: ['model'],
});
}
export function useTone() {
return useToneStatus().value;
}
export function Card(p: Person) {
const tone = useTone();
return host('div', {
style: {
maxWidth: 380,
padding: '1.5em',
borderRadius: 12,
background: LOOK[tone].background,
color: '#3a2a1c',
},
children: [
host('h1', { style: { color: LOOK[tone].accent }, children: title(p, tone) }),
host('p', { children: 'Wishing you a wonderful day.' }),
host('p', { style: { textAlign: 'right', fontStyle: 'italic' }, children: `— ${p.from}` }),
],
});
}
export function Buttons() {
const tone = useToneStatus();
const row = <T extends string>(name: string, values: readonly T[], now: { value: T; source: string }) =>
host('p', {
children: [
...values.map((v) =>
// A person's decision is pressed; a value the card took on its own is only marked.
host('button', {
disabled: now.source === 'decision' && v === now.value,
...(now.source !== 'decision' &&
v === now.value && { style: { textDecoration: 'underline dotted' } }),
onClick: action.decide({ of: 'card', name }, v),
children: v,
}),
),
// The person's way of not deciding: forget the decision, and the card picks again.
host('button', {
disabled: now.source !== 'decision',
onClick: action.forget({ of: 'card', name }),
style: {
marginLeft: 12,
borderStyle: 'dashed',
fontStyle: 'italic',
...(now.source === 'decision' && { background: 'transparent' }),
},
children: 'no preference',
}),
],
});
return host('div', { children: [row('tone', TONES, tone)] });
}
export default function App() {
return host('div', { children: [<Card {...GRANDMA} />, <Buttons />] });
}
Starting…
Starting…
Nothing logged.
createIntent({ model }) takes a Model, an object with one function for each kind of request, each of them optional. judge gives System One's answers, and generate and reprogram give System Two's (Reprogramming the intent). judge returns weights, one for each possibility, and the intent writes them into the choice the way it writes a real model's answer.
The function gets a ModelRequest. It logs the request's prompt, kinds and facts, and What happened shows the line. A ModelRequest carries:
effectis'judge', andidandkeyname the choice (card#tone);promptis the question given tojudge;kindsare the possibilities, by tag;usesis what the judgment reads, when the intent lists it;factsis what a person has said of the whole card, once something is said;stampis the inputs of the answer in one string, the canonical JSON ofprompt,kinds,usesandfacts, in full. The intent keeps the answer under it.
The request has no program in it, not even its name: a reprogramming that leaves the tone's question, possibilities and inputs as they were leaves its answer standing.
Say “It is for a formal family dinner.” in the panel. The function is called again with the sentence in facts, and the card turns formal. These fields are the inputs of the answer (What a judgment reads). The intent asks again when one of them changes, and they are all the function ever sees.
A real model goes in the same place
A judge for a real model turns the request into a prompt, sends it, and turns the reply into weights. recordedModel() returns the same kind of object, with functions that answer from recordings (Recording the model's answers).
Answering later
A real model takes a while to write. Sam's System Two here takes a second and a half:
/** @jsxImportSource @reintent/core */
import { createIntent, type Id, type ModelRequest } from '@reintent/core';
import App, { Decide, Forget } from './App.intent';
const wait = (ms: number) => new Promise<void>((done) => setTimeout(done, ms));
function judge(r: ModelRequest) {
const formal = r.facts?.some((f) => f.includes('formal'));
return formal ? { warm: 0.2, funny: 0.1, formal: 0.7 } : { warm: 0.7, funny: 0.2, formal: 0.1 };
}
/** Sam's System Two, written by hand: it takes a while, so it answers with a promise. */
async function generate(r: ModelRequest) {
await wait(1500);
const { to, age, tone } = r.uses as { to: string; age: number; tone: string };
if (tone === 'formal') return `On your ${age}th birthday, ${to}, we wish you health and joy.`;
if (tone === 'funny') return `${age} years young, ${to}, and still the best dancer at the party.`;
return `${age} years of you, ${to}, and every one a gift.`;
}
const intent = createIntent({
program: <App />,
model: { judge, generate },
provide: [
[Decide, (id: Id, value: unknown) => intent.decide(id, value)],
[Forget, (id: Id) => intent.forget(id)],
],
});
// The host accepts trees before their model requests run.
intent.connect({ commit() {} });
intent.realize();
console.log(intent.pending().map((s) => [s.effect, s.key, s.status])); // → [ [ 'generate', 'card#message', 'running' ] ]
Starting…
Starting…
Nothing logged.
generate gets the request of a useGenerate. Its prompt is the instruction, with uses and facts as before. It returns the value, or a promise of it. After a connected host accepts a tree, a synchronous answer is written immediately and the connection commits the updated tree. A promise is written when it resolves, and the connection commits again. Until then the card shows …, as in Quick start. A judge may return a promise the same way.
intent.pending() lists the requests still waiting for an answer and the ones that failed, each with its effect, key, stamp and status. Logged right after the first evaluation, it holds the message, 'running'. Press formal under the card: the message has new inputs, so it is a new request, and the card shows … again until the answer comes.
A request nobody needs any more
Each call gets a second argument, a ModelCall, with an AbortSignal. It aborts once no shown evaluation needs the request: the inputs changed while it ran, the program was replaced, or every view of the card went away. Two views that need the same request share it, and it aborts only when neither does. Pass the signal to fetch or a model SDK, and the call stops:
const model: Model = {
async generate(request, { signal }) {
const reply = await fetch('/api/generate', {
method: 'POST',
body: JSON.stringify({ prompt: request.prompt, facts: request.facts }),
signal,
});
return (await reply.json()).text;
},
};A call that rejects once aborted is as if it was never made: the intent asks again when an evaluation needs the request. A provider that keeps going and answers anyway still answered that request, so the answer is kept under its stamp. If Sam goes back to those inputs, the card shows it without asking again.
When a request fails
Sam's model is offline the evening before the dinner:
import { createIntent } from '@reintent/core';
import { Card, GRANDMA } from './App.intent';
const intent = createIntent({
program: <Card {...GRANDMA} />,
model: {
judge: () => {
throw new Error('the model is offline');
},
},
});
const connection = intent.connect({ commit() {} });
const tone = intent.realize().reads[0];
console.log(tone.value, tone.source); // → 'warm' 'default'
console.log(intent.pending().map((s) => [s.status, s.error])); // → [ [ 'failed', 'the model is offline' ] ]
intent.realize();
console.log(intent.pending().length); // → 1
intent.tell('It is for a formal family dinner.');
intent.realize();
console.log(intent.pending().length); // → 2
connection.disconnect();A function that throws, or a promise that rejects, marks its request 'failed', with its error, and the request stays in intent.pending(). The choice takes the layer below, here its default, and the card still shows. Evaluating again sends nothing new. Once the inputs change, here a sentence said, the intent sends a new request.
A failed generate looks pending to the intent
useGenerate returns status: 'pending' both while its request runs and after it failed. A host that tells the two apart reads the request's status in intent.pending().
A System One model: Jev
Jev is a System One model. It answers typed questions with probabilities and never writes text. A question tells it more when it says what kind of question it is and what each possibility means, so a read can say both. shape is a Shape: 'ordered' for levels in the order listed, 'whether' for a proposition that holds or does not. describe gives a sentence for each tag. Both go into the ModelRequest and into its stamp, so a new description is a new question.
@reintent/lib/jev writes each question in one line: the choice's identity, the question, and the options with what each means. useChoice reads one of the options, useScore a level in the order written, useWhether a boolean. Each is a choice underneath, which a person can decide like any other. <Ask state> gives the questions inside what they read, as Jev's state:
import { Ask, useChoice, useScore, useWhether } from '@reintent/lib/jev';
function Ticket() {
const tone = useChoice('ticket#tone', 'What is the tone of this message?', {
angry: 'An upset or hostile message',
calm: 'A neutral or polite message',
});
const urgency = useScore('ticket#urgency', 'How urgent is this message?', {
later: 'Can wait',
week: 'Needs attention this week',
today: 'Needs attention today',
});
const billing = useWhether('ticket#billing', 'Is this message about billing?');
// …
}
<Ask state={message}>
<Ticket />
</Ask>;The identity is a ChoiceId: 'ticket#tone', an Id or an entity's handle. The options are Criteria, and a null description leaves the name to say it. QuestionOptions holds the rest: defaultValue, ask and uses.
jev({ apiKey }) is a judge for createIntent({ model }), with options in JevOptions. The requests one evaluation sends on the same inputs go to Jev in one call. jevQuestion turns each request into a JevQuestion by its shape: a choice with the descriptions as its criteria, a score for 'ordered', a noul for 'whether'. jevJudgment turns a JevAnswer back into a Judgment, the weights with Jev's confidence, which a read returns as confidence.
decisionJudge(decide) asks a decision model the same way, with decide a Decide: a state and named questions in, an answer for each out, as bass's /api/ai/decide takes them. Behind it may be Jev, a chat model or a cascade. The questions of one state go in one decision, each a DecisionQuestion answered by a DecisionAnswer, and where the model gives no confidence it comes from the probabilities.
Beside each question it asks whether the state asks anything of it. A question it asks nothing of is answered with SILENT, a judgment with no weights: the choice rests on the program's word or Code's prior, as before anything was said, and it is not asked again when only its case changes. decisionJudge(decide, { beyond }) takes a BeyondOf: one way of asking for the share outside K for every choice, or a function of the request. Give false for a choice System Two has nothing to write for, and it takes the nearest of K.
When more than one sentence was said, each answer is a HeardJudgment: its weights still rest on everything said, and heard says whether the last sentence is part of what it asks. A sentence no question heard can then go to System Two whole, though what was said before still weighs every choice. decisionJudge(decide, { world }) takes a WorldOf: the questions that read the world, whose uses (a radio, a closure) ask of them though nobody said anything. Give it only where the world alone is reason to move the choice.
A choice's question can also be answered with something none of its options is. A choice gets an option for it, something else, and its probability comes back under BEYOND, the share outside the possibilities. With beyond: 'noul', a companion noul asks whether any of them fits. What a choice does with that share is in design note 0115.
Recap
createIntent({ model })takes aModel:judgereturns weights,generatereturns a value, and either may return a promise.- A
ModelRequestcarriesprompt,kinds,uses,factsand theirstamp: the inputs its answer is for, and nothing else. intent.pending()lists the requests running and the ones that failed.- Each call gets a
signalthat aborts once no shown evaluation needs the request. - A failed request leaves the choice to the layer below. New inputs send a new request.
shapeanddescribetell System One what kind of question it is and what each possibility means.@reintent/lib/jevasks the way Jev asks:useChoice,useScore,useWhether,Askandjev.
Last updated on
Edit on GitHub