Reintent

Generating a value

What the card shows while System Two writes, which results do, what a result is kept for, and a choice with an open end.

In Quick start System Two writes the card's message, and the card shows … until it comes. A real model takes a few seconds, and Sam wants the card to say it is writing. The message is read aloud at the birthday dinner from a small card, so a long one won't do. And the line above Sam's name has two good options, “With love,” and “Love always,”, with room for words of Sam's own.

You will learn

  • How to show that System Two is still writing: status
  • How to turn a result down: check
  • What a result is kept for, and how the card goes back to an earlier one
  • How a declared choice leaves an open end for System Two: or

While System Two writes

The card from Quick start, with a System Two that takes a second:

/** @jsxImportSource @reintent/core */
import { action, choices, createContext, host, useChoiceStatus, useGenerate, 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' };
export const JOKES = ['pun', 'tease'] as const;
export type Joke = (typeof JOKES)[number];

/** What a button does: the intent gives it to every evaluation (index.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, joke?: Joke) {
  if (tone === 'formal') return `Many happy returns, ${p.to}.`;
  if (tone === 'warm') return `Happy ${p.age}th birthday, ${p.to}!`;
  return joke === 'tease'
    ? `${p.to}, you don’t look a day over ${p.age - 1}!`
    : `${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;
}

/** Which joke: a question only a funny card has. */
export function useJokeStatus(tone: Tone) {
  return tone === 'funny'
    ? useChoiceStatus(choices<Joke>(...JOKES), { of: 'card', name: 'joke', defaultValue: 'pun' })
    : undefined;
}

export function useJoke(tone: Tone) {
  return useJokeStatus(tone)?.value;
}

export function Card(p: Person) {
  const tone = useTone();
  const joke = useJoke(tone);
  // The words nobody listed: System Two writes them, once for each set of inputs.
  const message = useGenerate<string>({
    of: 'card',
    name: 'message',
    instruction:
      'Write the message inside a birthday card: two short sentences in this tone, no greeting and no signature.',
    uses: { to: p.to, age: p.age, tone, joke },
  });
  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, joke) }),
      // Pending: System Two is still writing for these inputs.
      message.status === 'pending'
        ? host('p', { style: { opacity: 0.5, fontStyle: 'italic' }, children: 'System Two is writing…' })
        : host('p', { children: message.value }),
      host('p', { style: { textAlign: 'right', fontStyle: 'italic' }, children: `— ${p.from}` }),
    ],
  });
}

export function Buttons() {
  const tone = useToneStatus();
  const joke = useJokeStatus(tone.value);
  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), joke && row('joke', JOKES, joke)] });
}

export default function App() {
  return host('div', { children: [<Card {...GRANDMA} />, <Buttons />] });
}
ChoicesC

Starting…

Realizationλ

Starting…

What happened

Nothing logged.

useGenerate returns { value, status }. status is 'pending' until there is a result for these inputs, and then 'ready'. While it is pending, value is undefined, and the card draws a faded “System Two is writing…”.

Click funny. The card says System Two is writing, and a second later it shows the funny message. Click warm, and the warm message is there at once.

System Two is a function

In the sandbox above, model.generate in index.intent.tsx is System Two. The intent calls it for every useGenerate that has no result yet, with a ModelRequest: the instruction as prompt, the uses, and the sentences said with intent.tell as facts. It returns the value, or a promise of it. This one answers from the recordings a second later, the way a real model takes its time. Connecting your own model covers the rest.

A result that won't do

The same card, with a limit on the message:

/** @jsxImportSource @reintent/core */
import { action, choices, createContext, host, useChoiceStatus, useGenerate, 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' };
export const JOKES = ['pun', 'tease'] as const;
export type Joke = (typeof JOKES)[number];

/** What a button does: the intent gives it to every evaluation (index.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, joke?: Joke) {
  if (tone === 'formal') return `Many happy returns, ${p.to}.`;
  if (tone === 'warm') return `Happy ${p.age}th birthday, ${p.to}!`;
  return joke === 'tease'
    ? `${p.to}, you don’t look a day over ${p.age - 1}!`
    : `${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;
}

/** Which joke: a question only a funny card has. */
export function useJokeStatus(tone: Tone) {
  return tone === 'funny'
    ? useChoiceStatus(choices<Joke>(...JOKES), { of: 'card', name: 'joke', defaultValue: 'pun' })
    : undefined;
}

export function useJoke(tone: Tone) {
  return useJokeStatus(tone)?.value;
}

export function Card(p: Person) {
  const tone = useTone();
  const joke = useJoke(tone);
  // The words nobody listed: System Two writes them, once for each set of inputs.
  const message = useGenerate<string>({
    of: 'card',
    name: 'message',
    instruction:
      'Write the message inside a birthday card: two short sentences in this tone, no greeting and no signature.',
    uses: { to: p.to, age: p.age, tone, joke },
    // Read aloud at dinner, from a small card: a longer message does not do.
    check: (m) => (m.length > 200 ? [`${m.length} characters: too long for the card`] : []),
  });
  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, joke) }),
      // A message that does not do counts as pending: the card has a line of its own.
      host('p', { children: message.value ?? 'Wishing you a wonderful day.' }),
      host('p', { style: { textAlign: 'right', fontStyle: 'italic' }, children: `— ${p.from}` }),
    ],
  });
}

export function Buttons() {
  const tone = useToneStatus();
  const joke = useJokeStatus(tone.value);
  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), joke && row('joke', JOKES, joke)] });
}

export default function App() {
  return host('div', { children: [<Card {...GRANDMA} />, <Buttons />] });
}
ChoicesC

Starting…

Realizationλ

Starting…

What happened

Nothing logged.

check(value) returns the reasons a result won't do, and an empty list when it does. A result with a reason counts as pending, so value is undefined. Click formal. System Two's formal message has 235 characters (What happened shows the message), so the card uses its own line, message.value ?? 'Wishing you a wonderful day.'. Click warm. That message has 175 characters, and it is back on the card.

The card needs a line of its own

System Two is asked once for each set of inputs. A result that fails check stays where it is, and System Two is asked again only when the inputs change. Until then the card shows its fallback.

What a result is kept for

A result is kept for its inputs: the instruction, the uses, and what has been said with intent.tell. Go back to the first sandbox and click warm, then say “She loves a good joke.” above the panel. The tone stays warm, and the inputs have changed, so System Two writes a warm message that knows about her jokes. Take the sentence back. The first warm message returns, with no new call in What happened. Going back to earlier inputs finds the result written for them.

Put everything the message depends on in uses

Leave the tone out of uses, and every tone has the same inputs. The warm message would then stay on the card after it turns formal.

A reprogramming keeps the results

A judgment is kept for its question, its possibilities, its uses and the sentences said; a generated result for its instruction, its uses and the sentences said. Neither is given the program, so after a reprogramming the same inputs find the same answers, and only a choice whose question or possibilities changed is judged again.

Generating candidates

generate<T>(instruction, { n, uses, check }) describes a Generation<T>: an open choice whose values System Two writes. Read it with useChoose or useChoiceStatus, using the same identity as any other choice:

const line = useChoose(
  generate<string>('A greeting line for Ann', { n: 3 }),
  { of: 'card', name: 'line', defaultValue: '…' },
);

System Two receives n in its ModelRequest. For n > 1, return an array of values (or a promise of it), for example ['Hello Ann', 'Welcome Ann', 'Hi Ann']. n defaults to 1; then return one value, even when that value is itself an array. useGenerate is the one-candidate sugar and keeps its { value, status } result.

The program fixes T. check runs on each candidate and keeps the valid ones; it also checks a person's own value. As with choices, candidates are identified by tagOf: strings by their text, tagged objects by kind, and other values by JSON. Repeated tags keep the first valid candidate. There can therefore be fewer than n usable candidates. If none pass, the read keeps its fallback without repeatedly calling System Two. A new input stamp or a regenerate() step in a <World onUnresolved> can try again.

The candidates have equal weights. One candidate resolves immediately. Several candidates follow the surrounding <World>: without a preference or judgment, the root's rule keeps the fallback. To ask System One to weigh them, give the choice a question and ask: ['model']:

const line = useChoose(generate<string>('A greeting line for Ann', { n: 3 }), {
  of: 'card',
  name: 'line',
  defaultValue: '…',
  question: 'Which greeting suits a birthday dinner?',
  ask: ['model'],
});

System One is asked after the candidates arrive, with their tags as kinds. Its weights, constraints and preferences go through the usual cascade. intent.decide can pick a candidate by its tag, or supply a new value of T, which is taken as written. A read of the choice says where its value came from: source is 'generated' for System Two's candidates, and 'belief' once System One has weighed them. A decision made before generation needs no model call. intent.preview, intent.explore, and the alternatives panel can range over the cached candidates; inspection alone never calls System Two.

The generated layer caches the candidate set by identity, instruction, n, uses and facts. Returning to earlier inputs reuses their set. Regeneration replaces the set under the same stamp, without replacing a person's decision. The default n = 1 keeps existing cache stamps and model handlers compatible.

A choice with an open end

The line above Sam's name is a choice between “With love,” and “Love always,”. Sam may want words of their own, and nobody can list those. An entity's declaration gives a choice an open end with or:

/** @jsxImportSource @reintent/core */
import {
  action,
  choices,
  createContext,
  entity,
  host,
  useChoiceStatus,
  useChoose,
  useGenerate,
  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' };
export const JOKES = ['pun', 'tease'] as const;
export type Joke = (typeof JOKES)[number];

/** What a button does: the intent gives it to every evaluation (index.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 });

/** The line above Sam's name: two written out, and an open end that System Two writes. */
export const card = entity('card', {
  closing: {
    kinds: { love: { line: 'With love,' }, always: { line: 'Love always,' } },
    or: {
      kind: 'own',
      instruction:
        'Write the closing line above the signature on a birthday card for Grandma: two to five words in this tone, ending with a comma.',
    },
  },
});
export const CLOSINGS = { love: 'With love,', always: 'Love always,', own: 'Our own words…' } as const;

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, joke?: Joke) {
  if (tone === 'formal') return `Many happy returns, ${p.to}.`;
  if (tone === 'warm') return `Happy ${p.age}th birthday, ${p.to}!`;
  return joke === 'tease'
    ? `${p.to}, you don’t look a day over ${p.age - 1}!`
    : `${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;
}

/** Which joke: a question only a funny card has. */
export function useJokeStatus(tone: Tone) {
  return tone === 'funny'
    ? useChoiceStatus(choices<Joke>(...JOKES), { of: 'card', name: 'joke', defaultValue: 'pun' })
    : undefined;
}

export function useJoke(tone: Tone) {
  return useJokeStatus(tone)?.value;
}

export function Card(p: Person) {
  const tone = useTone();
  const joke = useJoke(tone);
  // The words nobody listed: System Two writes them, once for each set of inputs.
  const message = useGenerate<string>({
    of: 'card',
    name: 'message',
    instruction:
      'Write the message inside a birthday card: two short sentences in this tone, no greeting and no signature.',
    uses: { to: p.to, age: p.age, tone, joke },
  });
  // A declared choice, read by its handle. Its open end is written for this tone.
  const closing = useChoose(card.closing, { uses: { tone } });
  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, joke) }),
      host('p', { children: message.value ?? '…' }),
      host('p', {
        style: { textAlign: 'right', fontStyle: 'italic' },
        children: closing.kind === 'own' ? (closing.value ?? '…') : closing.line,
      }),
      host('p', { style: { textAlign: 'right', fontStyle: 'italic' }, children: p.from }),
    ],
  });
}

export function Buttons() {
  const tone = useToneStatus();
  const joke = useJokeStatus(tone.value);
  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',
        }),
      ],
    });
  const closing = useChoose(card.closing, { uses: { tone: tone.value } });
  const closings = host('p', {
    children: (Object.keys(CLOSINGS) as (keyof typeof CLOSINGS)[]).map((k) =>
      host('button', {
        disabled: closing.kind === k,
        onClick: action.decide({ of: 'card', name: 'closing' }, k),
        children: CLOSINGS[k],
      }),
    ),
  });
  return host('div', {
    children: [row('tone', TONES, tone), joke && row('joke', JOKES, joke), closings],
  });
}

export default function App() {
  return host('div', { children: [<Card {...GRANDMA} />, <Buttons />] });
}
ChoicesC

Starting…

Realizationλ

Starting…

What happened

Nothing logged.

  • closing lists two kinds, each with its line, and or: { kind: 'own', instruction }. That makes own a third possibility in KK.
  • When the choice is own, System Two writes its value from the instruction, like a useGenerate named after the choice and its tail (card#closing.own). The uses given to the read, { tone }, are its inputs.
  • The value is { kind: 'own', value }, and value is undefined while System Two writes. type in or says what kind of value to expect: 'string' (the default), 'number', 'boolean' or 'json'. A value of another type counts as pending, like one that fails check.

Click Our own words…. System Two writes “With all my love,”. Click formal, and it writes a formal one, “With warmest regards and affection,”. Click Love always, and the listed line is back. Declaring an entity's choices covers the rest of the declaration.

The open end is one more possibility

or adds one tag to KK (own here, other when no kind is given), and System Two writes its value. When the declaration has a judge, System One weighs the open end along with the listed kinds. A person decides it like any other kind.

Recap

  • useGenerate returns { value, status }: 'pending' with no value, then 'ready'.
  • generate<T> supplies candidates to the ordinary choice cascade; a question with ask: ['model'] optionally weighs them.
  • model.generate returns one value for n = 1, or an array for n > 1, synchronously or as a promise.
  • check lists why a result won't do. Such a result counts as pending, so the card needs a fallback.
  • A result is kept for its instruction, uses and the sentences said. Earlier inputs find their earlier result.
  • or in a declaration adds an open end to KK. When it is chosen, System Two writes its value.

Last updated on

Edit on GitHub