feat(core): few-shot demos and optimizers (LabeledFewShot, BootstrapFewShot) - #22
Merged
Merged
Conversation
Predict now accepts demos, and two optimizers turn a labelled trainset into
them, so a program improves from data rather than from prompt edits.
- Predict accepts `{ lm, demos }` alongside the existing `(signature, lm)`
form, plus `withDemos()` / `withLM()` for configured copies.
- buildPrompt renders demos as worked examples: labelled `field: value` on
the text path, JSON on the structured-output path, so a demo always models
the shape the reply is allowed to take. A prompt with no demos is
byte-for-byte what it was before.
- LabeledFewShot selects k of your own labels with no model calls.
- BootstrapFewShot runs the trainset, scores each attempt with a metric, and
promotes the runs that passed; an optional teacher model generates demos a
cheaper student then imitates. Bounded concurrency, early stop once enough
demos are collected, failing rows skipped, progress via callback.
- Both are deterministic given a seed.
Adds examples/optimizer.ts with an `example:optimizer` script, and docs site
section 21.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
# Conflicts: # package.json # packages/core/src/index.ts # packages/core/src/modules/predict.ts # packages/core/src/utils/parsing.ts # site/docs.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Predicthad no few-shot support, andExamplewas exported with zero call sites anywhere in the repo. This wires both up and adds the optimizers that make "TypeScript DSPy" a description rather than an homage.1. Demos in
Predictnew Predict(Sig, { lm, demos })rendersExamples into the prompt as worked examples before the real input. The original(signature, lm)form still works — the second argument is discriminated structurally, and an object carrying only half anILanguageModelis rejected loudly rather than silently falling back to the globally configured model.withDemos()andwithLM()return configured copies, preserving the concrete subclass, soChainOfThought.withDemos()returns aChainOfThoughtand an optimizer never mutates the student it was handed.Demos render in whichever shape the reply is expected to take: labelled
field: valuefor a text provider (exactly whatparseOutput()reads back), JSON for a provider with native structured output — where constrained decoding means labelled examples would model a shape the model is forbidden to emit. All three shipped providers take the structured path, so this is the common case, not an edge one.A prompt built with no demos is byte-for-byte what it was before;
parsing.test.tsis untouched and green.2.
LabeledFewShotSelects k of your own labelled examples. No model calls, so compiling is free and instant.
3.
BootstrapFewShotRuns the module over a labelled trainset, scores each attempt with a metric, and promotes the runs that passed into demos. An optional
teachermodel generates the demos that a cheaper student then imitates — you pay for the strong model once, at compile time.maxBootstrappedDemos— a 500-row trainset does not cost 500 teacher calls to keep 4 demos.errorevent and skipped. A throwingonProgresscallback is swallowed too — an observer must not be able to lose a compile.maxBootstrappedDemos: 0withmaxLabeledDemosset is a labels-only compile that makes no model calls at all.no-consolerespected: progress goes through an optional callback.The
Metrictype is defined locally inoptimizers/types.tsrather than imported from the siblingevaluate/PR, so the two can land in either order and be unified in a follow-up.Verification
npm run build/lint/typecheck/format:check/verify:packagingall clean.predict.test.ts,chain-of-thought.test.ts, andparsing.test.tsunchanged.@ts-dspy/corepackage and asserted that a bootstrapped module's next prompt contains the demos whose metric passed and none of the rows that failed, that two compiles with the same seed produce identical demos, and that a teacher does the compile-time work while the student carries the result.Docs
New section 21
#optimizersinsite/docs.html, plus its TOC entry. No existing section renumbered. README's DSPy framing now mentions that optimization exists.examples/optimizer.tsand anexample:optimizernpm script.🤖 Generated with Claude Code