Repository navigation
docs(examples): standardize core prompting, validation, and context examples #1753
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rafvasq
wants to merge
3
commits into
generative-computing:main
Choose a base branch
from
rafvasq:docs/core-prompting-context-standardize
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+228
−591
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,97 +1,13 @@ | ||
| # Context Examples | ||
|
|
||
| This directory contains examples demonstrating how to work with Mellea's context system: inspecting per-attempt contexts produced by sampling strategies, and shrinking contexts with the `Compactor` protocol. | ||
| Examples demonstrating context tree inspection with sampling strategies and context shrinking using the `Compactor` protocol. | ||
|
|
||
| ## Files | ||
| ## Examples | ||
|
|
||
| ### [contexts_with_sampling.py](./contexts_with_sampling.py) | ||
|
|
||
| Shows how to retrieve and inspect context information when using sampling strategies and validation. | ||
|
|
||
| **Key Features:** | ||
|
|
||
| - Using `RejectionSamplingStrategy` with requirements | ||
| - Accessing `SamplingResult` objects to inspect generation attempts | ||
| - Retrieving context for different generation attempts | ||
| - Examining validation contexts for each requirement | ||
| - Understanding the context tree structure | ||
|
|
||
| **Usage:** | ||
|
|
||
| ``` | ||
| python docs/examples/context/contexts_with_sampling.py | ||
| ``` | ||
|
|
||
| ### [window_compactor.py](./window_compactor.py) | ||
|
|
||
| `WindowCompactor` — opt-in by passing `compactor=` (or the `window_size=` sugar). Demonstrates system-prefix pinning, `pin_system_and_initial_user`, `pin_nothing` (pure last-N), and `size=0` to clear the body. | ||
|
|
||
| ### [threshold_compactor.py](./threshold_compactor.py) | ||
|
|
||
| `ThresholdCompactor` — gate an inner compactor on the conversation's cumulative token size. The reading is taken from the most recent `ModelOutputThunk`'s `total_tokens`, which for a chat backend equals `prompt_tokens` (full conversation history sent to the model) + `completion_tokens` (reply). The gate fires once the running conversation size crosses the threshold; once compaction shrinks the context, the next call produces a smaller reading and the gate closes again. | ||
|
|
||
| ### [custom_compactor.py](./custom_compactor.py) | ||
|
|
||
| Implement the `Compactor` protocol with a plain class (no inheritance). Shows Pattern 1 (wired into `ChatContext`) and Pattern 2 (manual `compact()` call). | ||
|
|
||
| ### [react_compaction.py](./react_compaction.py) | ||
|
|
||
| Compose the ReACT loop with a sync `Compactor`. Two integration points: | ||
|
|
||
| - **Per-add** — wire a `Compactor` onto the `ChatContext` so it runs every time `react()` appends a Message, ToolMessage, or thunk. | ||
| - **Per-turn** — pass `compactor=` to `react()`; it fires once per ReACT iteration after the tool observation. | ||
|
|
||
| `LLMSummarizeCompactor` is also a sync `Compactor` — it hides the async backend call internally (worker thread when called from an already-running event loop) so callers don't have to think about sync vs async. | ||
|
|
||
| Use `pin_react_initiator` (from `mellea.stdlib.components.react`) as the predicate so the goal and tool registration survive compaction. | ||
|
|
||
| ## Concepts Demonstrated | ||
|
|
||
| - **Sampling Results**: Working with `SamplingResult` objects | ||
| - **Context Inspection**: Accessing generation and validation contexts | ||
| - **Multiple Attempts**: Examining different generation attempts | ||
| - **Context Trees**: Understanding how contexts link together | ||
| - **Validation Context**: Inspecting how requirements were evaluated | ||
| - **Compaction Protocol**: Sync `Compactor` for per-`add()` shrinking | ||
| - **Pin Predicates**: Auto-protect leading system messages or the user's initial prompt during compaction | ||
|
|
||
| ## Key APIs | ||
|
|
||
| ```python | ||
| # Get sampling result with full context information | ||
| res = m.instruct( | ||
| "Write a sentence.", | ||
| requirements=[...], | ||
| strategy=RejectionSamplingStrategy(loop_budget=3), | ||
| return_sampling_results=True | ||
| ) | ||
|
|
||
| # Access different generation attempts | ||
| res.sample_generations[index] | ||
| res.sample_contexts[index] | ||
| res.sample_validations[index] | ||
|
|
||
| # Navigate context tree | ||
| gen_ctx.previous_node.node_data | ||
| val_ctx.node_data | ||
| ``` | ||
|
|
||
| ```python | ||
| # Wire a compactor into a ChatContext (Pattern 1 — runs on every add()) | ||
| from mellea.stdlib.context import ChatContext, WindowCompactor, ThresholdCompactor | ||
|
|
||
| ctx = ChatContext(compactor=WindowCompactor(size=5)) # default: pin_system | ||
| ctx = ChatContext(window_size=5) # sugar for the line above | ||
| ctx = ChatContext( | ||
| compactor=ThresholdCompactor(WindowCompactor(size=5), threshold=8000), | ||
| ) | ||
|
|
||
| # Manual compaction (Pattern 2) | ||
| ctx = WindowCompactor(size=0).compact(ctx) # drop body, keep pinned prefix | ||
| ``` | ||
|
|
||
| ## Related Documentation | ||
|
|
||
| - See `mellea/stdlib/context/` for context and compactor implementations | ||
| - See `mellea/stdlib/sampling/` for sampling strategies | ||
| - See `mellea/stdlib/frameworks/react.py` for the ReACT loop | ||
| | File | Description | | ||
| | :--- | :--- | | ||
| | [`contexts_with_sampling.py`](./contexts_with_sampling.py) | Inspecting per-attempt generation contexts, validation contexts, and context tree navigation in sampling results. | | ||
| | [`window_compactor.py`](./window_compactor.py) | Sliding window compaction with system-prefix pinning and custom pin predicates. | | ||
| | [`threshold_compactor.py`](./threshold_compactor.py) | Gating window compaction on cumulative conversation token thresholds. | | ||
| | [`custom_compactor.py`](./custom_compactor.py) | Implementing custom `Compactor` protocols via class implementations and manual invocation. | | ||
| | [`react_compaction.py`](./react_compaction.py) | Composing ReACT agent loops with per-add and per-turn context compaction strategies. | | ||
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
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
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,60 +1,14 @@ | ||
| # Generative Stubs Examples | ||
|
|
||
| This directory contains examples demonstrating the `@generative` decorator for creating type-safe, composable LLM functions. | ||
|
|
||
| ## Files | ||
|
|
||
| ### [generative_stubs.py](./generative_stubs.py) | ||
| Basic introduction to generative stubs with sentiment classification and text summarization. | ||
|
|
||
| **Key Features:** | ||
| - Using `@generative` decorator for type-safe LLM functions | ||
| - Literal types for constrained outputs | ||
| - Docstrings as prompts for the LLM | ||
| - Simple function composition | ||
|
|
||
| ### [generate_with_context.py](./generate_with_context.py) | ||
| Shows how to use generative stubs with custom context and grounding information. | ||
|
|
||
| ### [generative_gsm8k.py](./generative_gsm8k.py) | ||
| Demonstrates using generative stubs for mathematical reasoning tasks (GSM8K dataset). | ||
|
|
||
| ### [generative_stubs_with_requirements.py](./generative_stubs_with_requirements.py) | ||
| Combines generative stubs with requirements for validated outputs. | ||
|
|
||
| ### [investment_advice.py](./investment_advice.py) | ||
| A more complex example using generative stubs for financial analysis. | ||
|
|
||
| ### [inter_module_composition/](inter_module_composition/) | ||
| Subdirectory with examples of composing multiple generative functions together. | ||
|
|
||
| ## Concepts Demonstrated | ||
|
|
||
| - **Type Safety**: Using Python type hints for structured outputs | ||
| - **Docstring Prompts**: Leveraging docstrings as instructions to the LLM | ||
| - **Composition**: Building complex workflows from simple generative functions | ||
| - **Requirements**: Adding validation to generative functions | ||
| - **Context Management**: Using grounding context with generative stubs | ||
|
|
||
| ## Basic Usage | ||
|
|
||
| ```python | ||
| from mellea import generative, start_session | ||
| from typing import Literal | ||
|
|
||
| @generative | ||
| def classify_sentiment(text: str) -> Literal["positive", "negative"]: | ||
| """Classify the sentiment of the given text.""" | ||
|
|
||
| @generative | ||
| def generate_summary(text: str) -> str: | ||
| """Generate a concise summary under 20 words.""" | ||
|
|
||
| with start_session() as m: | ||
| sentiment = classify_sentiment(m, text="I love this!") | ||
| summary = generate_summary(m, text="Long document...") | ||
| ``` | ||
|
|
||
| ## Related Documentation | ||
|
|
||
| - See `mellea/stdlib/components/genstub.py` for implementation | ||
| Examples demonstrating the `@generative` decorator for creating type-safe, composable LLM functions. | ||
|
|
||
| ## Examples | ||
|
|
||
| | File | Description | | ||
| | :--- | :--- | | ||
| | [`generative_stubs.py`](./generative_stubs.py) | Basic sentiment classification and text summarization with `@generative` functions and `Literal` return types. | | ||
| | [`generate_with_context.py`](./generate_with_context.py) | Generative stubs with dynamic context and role modification. | | ||
| | [`generative_gsm8k.py`](./generative_gsm8k.py) | Stepwise chain-of-thought mathematical reasoning on GSM8K problems using structured Pydantic models. | | ||
| | [`generative_stubs_with_requirements.py`](./generative_stubs_with_requirements.py) | Enforcing preconditions and postcondition requirements on generative stub executions. | | ||
| | [`investment_advice.py`](./investment_advice.py) | Multi-step financial advice workflow with semantic preconditions and compliance checks. | | ||
| | [`inter_module_composition/`](./inter_module_composition/) | Modular generative pipeline composing summarization and decision-making modules. | |
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
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
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Most of the deleted usage/concept material is covered in the docs. This part is the exception.
compaction. The context/ README previously carried the only conceptual explanation of the Compactor protocol (window vs threshold vs custom, pin predicates, per-add vs per-turn wiring with react()). After this PR, that story survives only in the example docstrings and the auto-generated API reference (api/mellea/stdlib/context/compactor.mdx) — no concepts/ or how-to/ page mentions compaction at all. Since the README collapse is the right call per #1746, should we either add a short compaction section to concepts/context-and-sessions.md or open a follow-up issue so the conceptual docs catch up?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems to me like this is a documentation gap and deserves a follow up issue to include compaction somewhere on https://docs.mellea.ai/next/concepts/context-and-sessions, instead of laying it out in these examples.