-
Notifications
You must be signed in to change notification settings - Fork 522
feat: Add responses.compact-wired session feature #760
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| '@openai/agents-openai': patch | ||
| '@openai/agents-core': patch | ||
| --- | ||
|
|
||
| feat: Add responses.compact-wired session feature |
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,2 +1,3 @@ | ||
| tmp/ | ||
| *.db | ||
| .agents-sessions/ |
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 |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| import { | ||
| Agent, | ||
| OpenAIResponsesCompactionSession, | ||
| run, | ||
| withTrace, | ||
| } from '@openai/agents'; | ||
| import { fetchImageData } from './tools'; | ||
| import { FileSession } from './sessions'; | ||
|
|
||
| async function main() { | ||
| const session = new OpenAIResponsesCompactionSession({ | ||
| model: 'gpt-5.2', | ||
| // This compaction decorator handles only compaction logic. | ||
| // The underlying session is responsible for storing the history. | ||
| underlyingSession: new FileSession(), | ||
| // (optional customization) This example demonstrates the simplest compaction logic, | ||
| // but you can also estimate the context window size using sessionItems (all items) | ||
| // and trigger compaction at the optimal time. | ||
| shouldTriggerCompaction: ({ compactionCandidateItems }) => { | ||
| // Set a low threshold to observe compaction in action. | ||
| return compactionCandidateItems.length >= 4; | ||
| }, | ||
| }); | ||
|
|
||
| const agent = new Agent({ | ||
| name: 'Assistant', | ||
| model: 'gpt-5.2', | ||
| instructions: | ||
| 'Keep answers short. This example demonstrates responses.compact with a custom session. For every user turn, call fetch_image_data with the provided label. Do not include raw image bytes or data URLs in your final answer.', | ||
| modelSettings: { toolChoice: 'required' }, | ||
| tools: [fetchImageData], | ||
| }); | ||
|
|
||
| // To see compaction debug logs, run with: | ||
| // DEBUG=openai-agents:openai:compaction pnpm -C examples/memory start:oai-compact | ||
| await withTrace('memory:compactSession:main', async () => { | ||
| const prompts = [ | ||
| 'Call fetch_image_data with label "alpha". Then explain compaction in 1 sentence.', | ||
| 'Call fetch_image_data with label "beta". Then add a fun fact about space in 1 sentence.', | ||
| 'Call fetch_image_data with label "gamma". Then add a fun fact about oceans in 1 sentence.', | ||
| 'Call fetch_image_data with label "delta". Then add a fun fact about volcanoes in 1 sentence.', | ||
| 'Call fetch_image_data with label "epsilon". Then add a fun fact about deserts in 1 sentence.', | ||
| ]; | ||
|
|
||
| for (const prompt of prompts) { | ||
| const result = await run(agent, prompt, { session, stream: true }); | ||
| console.log(`\nUser: ${prompt}`); | ||
|
|
||
| for await (const event of result.toStream()) { | ||
| if (event.type === 'raw_model_stream_event') { | ||
| continue; | ||
| } | ||
| if (event.type === 'agent_updated_stream_event') { | ||
| continue; | ||
| } | ||
| if (event.type !== 'run_item_stream_event') { | ||
| continue; | ||
| } | ||
|
|
||
| if (event.item.type === 'tool_call_item') { | ||
| const toolName = (event.item as any).rawItem?.name; | ||
| console.log(`-- Tool called: ${toolName ?? '(unknown)'}`); | ||
| } else if (event.item.type === 'tool_call_output_item') { | ||
| console.log( | ||
| `-- Tool output: ${formatToolOutputForLog((event.item as any).output)}`, | ||
| ); | ||
| } else if (event.item.type === 'message_output_item') { | ||
| console.log(`Assistant: ${event.item.content.trim()}`); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| const compactedHistory = await session.getItems(); | ||
| console.log('\nHitory including both compaction and newer items:'); | ||
| for (const item of compactedHistory) { | ||
| console.log(`- ${item.type}`); | ||
| } | ||
|
|
||
| // You can manually run compaction this way: | ||
| await session.runCompaction({ force: true }); | ||
|
|
||
| const finalHistory = await session.getItems(); | ||
| console.log('\nStored history after final compaction:'); | ||
| for (const item of finalHistory) { | ||
| console.log(`- ${item.type}`); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| function formatToolOutputForLog(output: unknown): string { | ||
| if (output === null) { | ||
| return 'null'; | ||
| } | ||
| if (output === undefined) { | ||
| return 'undefined'; | ||
| } | ||
| if (typeof output === 'string') { | ||
| return output.length > 200 ? `${output.slice(0, 200)}…` : output; | ||
| } | ||
| if (Array.isArray(output)) { | ||
| const parts = output.map((part) => formatToolOutputPartForLog(part)); | ||
| return `[${parts.join(', ')}]`; | ||
| } | ||
| if (typeof output === 'object') { | ||
| const keys = Object.keys(output as Record<string, unknown>).sort(); | ||
| return `{${keys.slice(0, 10).join(', ')}${keys.length > 10 ? ', …' : ''}}`; | ||
| } | ||
| return String(output); | ||
| } | ||
|
|
||
| function formatToolOutputPartForLog(part: unknown): string { | ||
| if (!part || typeof part !== 'object') { | ||
| return String(part); | ||
| } | ||
| const record = part as Record<string, unknown>; | ||
| const type = typeof record.type === 'string' ? record.type : 'unknown'; | ||
| if (type === 'text' && typeof record.text === 'string') { | ||
| return `text(${record.text.length} chars)`; | ||
| } | ||
| if (type === 'image' && typeof record.image === 'string') { | ||
| return `image(${record.image.length} chars)`; | ||
| } | ||
| return type; | ||
| } | ||
|
|
||
| main().catch((error) => { | ||
| console.error(error); | ||
| process.exit(1); | ||
| }); |
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
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.
If this type of Session extends the regular session can't we just call compaction inside the
addItempart of Session rather than introducing a new subtype? My understanding was that the point of Session was that it would decide what to store and how to store it.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.
When you use
responses.compactAPI with an external session store, your code has to clear all items (at least all non-user-message items) associated with the session ID first, then re-insert everything (N user messages + 1 compaction item). Because of that, it doesn’t fit well withaddItems/getItemsmethod customization.That said, it's still feasible to do above in
addItemsmethod. Another benefit of the current design is that you can use this new subclass as a decorator-design-pattern style wrapper around your existing session store. This enables developers to reuse this single logic without having similar logic within their code.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.
I didn't change this for the above reason.