Choose better results and keep context You can keep chat context, sample several candidates, select one result, cache responses, and observe steps. Add each option only when your feature needs that control. typescript academy academy/topics/gen-memory-sampling-hooks website/content-src/academy/course.mjs academy Choose better results and keep context
Unit 3 · Build a reliable AI-powered feature

Choose better results and keep context

You can keep chat context, sample several candidates, select one result, cache responses, and observe steps. Add each option only when your feature needs that control.

9 focused minutesNot started
Worked example

See the idea in context

const result = await program.forward(llm, input, { mem, sampleCount: 3, resultPicker });
  1. Carry relevant memory

    mem supplies conversation context owned by your application.

  2. Request candidates

    sampleCount asks for three possible results instead of one.

  3. Select with a rule

    resultPicker turns extra samples into a deliberate quality choice.

Run itIn your own project
npm install @ax-llm/ax

import { ai, ax } from '@ax-llm/ax';

const llm = ai({ name: 'openai', apiKey: process.env.OPENAI_APIKEY! });
const classify = ax('review:string -> sentiment:class "positive, negative, neutral"');

const result = await classify.forward(llm, {
  review: 'Useful and boring in the best way.',
});

Set OPENAI_APIKEY in your environment before running provider-backed code.

In the ax repo

From a clone of the ax repo:

npm run example -- typescript src/examples/typescript/generation/axgen-openai.ts
Active practice

Show that you can use it

Answer 2 in a row to learn this · attempt 1
Keep exploring

Source-backed follow-up