-
Notifications
You must be signed in to change notification settings - Fork 50
feat: Add cache control support in langchain orchestration client #1950
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
davidkna-sap
wants to merge
6
commits into
main
Choose a base branch
from
davidkna-sap_lc-o-cache
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.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
1c43343
feat: Add cache control support in langchain orchestration client
davidkna-sap 56e7739
vale
davidkna-sap 66d9399
fix checks and improve token usage handling
davidkna-sap ee57171
cleanup
davidkna-sap 06ad0a5
cleanup
davidkna-sap f97b34d
temp fix
davidkna-sap 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,7 @@ | ||
| --- | ||
| "@sap-ai-sdk/langchain": minor | ||
| --- | ||
|
|
||
| [feat] Add `cache_control` call option to the LangChain orchestration client. | ||
| When the `cache_control` option is set (directly or via the `orchestrationPromptCachingMiddleware()` middleware), a cache breakpoint is automatically applied to the request. | ||
|
|
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 @@ | ||
| --- | ||
| "@sap-ai-sdk/langchain": patch | ||
| --- | ||
|
|
||
| [feat] Expose `cached_tokens` and `cache_creation_tokens` in `usage_metadata.input_token_details` for LangChain orchestration responses. | ||
|
|
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,8 @@ | ||
| --- | ||
| "@sap-ai-sdk/langchain": minor | ||
| --- | ||
|
|
||
| [feat] Export `orchestrationPromptCachingMiddleware()` middleware for the LangChain Orchestration client from `@sap-ai-sdk/langchain/orchestration/prompt-caching-middleware`. | ||
| It enables automatic cache control for orchestration requests. | ||
| The middleware requires the optional `langchain` peer dependency to be installed. | ||
|
|
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 |
|---|---|---|
|
|
@@ -20,6 +20,10 @@ | |
| "types": "./dist/index.d.ts", | ||
| "default": "./dist/index.js" | ||
| }, | ||
| "./orchestration/prompt-caching-middleware": { | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I added this as explicit export to avoid having to dynamically import |
||
| "types": "./dist/orchestration/prompt-caching-middleware.d.ts", | ||
| "default": "./dist/orchestration/prompt-caching-middleware.js" | ||
| }, | ||
| "./internal.js": { | ||
| "types": "./dist/internal.d.ts", | ||
| "default": "./dist/internal.js" | ||
|
|
@@ -49,9 +53,16 @@ | |
| "devDependencies": { | ||
| "@langchain/core": "^1.1.16", | ||
| "@langchain/langgraph": "^1.4.1", | ||
| "langchain": "^1.4.4", | ||
| "zod": "^4.4.3" | ||
| }, | ||
| "peerDependencies": { | ||
| "@langchain/core": "^1.1.16" | ||
| "@langchain/core": "^1.1.16", | ||
| "langchain": "^1.4.4" | ||
| }, | ||
| "peerDependenciesMeta": { | ||
| "langchain": { | ||
| "optional": true | ||
| } | ||
| } | ||
| } | ||
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
196 changes: 196 additions & 0 deletions
196
packages/langchain/src/orchestration/prompt-caching-middleware.test.ts
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,196 @@ | ||
| import { jest } from '@jest/globals'; | ||
| import { AIMessage, HumanMessage } from '@langchain/core/messages'; | ||
| import { createAgent } from 'langchain'; | ||
| import { AzureOpenAiChatClient } from '../openai/chat.js'; | ||
| import { OrchestrationClient } from './client.js'; | ||
| import { orchestrationPromptCachingMiddleware } from './prompt-caching-middleware.js'; | ||
| import type { LanguageModelLike } from '@langchain/core/language_models/base'; | ||
|
|
||
| function getBindToolsOptions( | ||
| model: LanguageModelLike | ||
| ): Record<string, unknown> | undefined { | ||
| const bindToolsMock = (model as any).bindTools as jest.Mock; | ||
| return bindToolsMock.mock.calls.at(-1)?.[1] as | ||
| | Record<string, unknown> | ||
| | undefined; | ||
| } | ||
|
|
||
| function stubModel<T extends LanguageModelLike>(model: T): T { | ||
| const bindToolsMock = jest.fn().mockReturnValue(model); | ||
| const invokeMock = jest | ||
| .fn() | ||
| .mockResolvedValue(new AIMessage('Response from model') as never); | ||
|
|
||
| Object.assign(model as object, { | ||
| bindTools: bindToolsMock, | ||
| invoke: invokeMock | ||
| }); | ||
|
|
||
| return model; | ||
| } | ||
|
|
||
| function createSupportedModel(): LanguageModelLike { | ||
| return stubModel( | ||
| new OrchestrationClient({ | ||
| promptTemplating: { | ||
| model: { | ||
| name: 'gpt-5.4-nano', | ||
| params: {} | ||
| } | ||
| } | ||
| }) | ||
| ); | ||
| } | ||
|
|
||
| function createUnsupportedModel(): LanguageModelLike { | ||
| return stubModel(new AzureOpenAiChatClient({ modelName: 'gpt-5.4-nano' })); | ||
| } | ||
|
|
||
| describe('orchestrationPromptCachingMiddleware', () => { | ||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| it('adds cache_control to modelSettings when conditions are met', async () => { | ||
| const model = createSupportedModel(); | ||
| const middleware = orchestrationPromptCachingMiddleware({ | ||
| ttl: '5m', | ||
| minMessagesToCache: 3 | ||
| }); | ||
|
|
||
| const agent = createAgent({ model, middleware: [middleware] }); | ||
|
|
||
| await agent.invoke({ | ||
| messages: [ | ||
| new HumanMessage('Hello'), | ||
| new AIMessage('Hi there!'), | ||
| new HumanMessage('How are you?') | ||
| ] | ||
| }); | ||
|
|
||
| expect(model.bindTools).toHaveBeenCalled(); | ||
| expect(getBindToolsOptions(model)).toHaveProperty('cache_control'); | ||
| expect(getBindToolsOptions(model)?.cache_control).toEqual({ | ||
| type: 'ephemeral', | ||
| ttl: '5m' | ||
| }); | ||
| }); | ||
|
|
||
| it('does not add cache_control when message count is below threshold', async () => { | ||
| const model = createSupportedModel(); | ||
| const middleware = orchestrationPromptCachingMiddleware({ | ||
| ttl: '1h', | ||
| minMessagesToCache: 5 | ||
| }); | ||
|
|
||
| const agent = createAgent({ model, middleware: [middleware] }); | ||
|
|
||
| await agent.invoke({ | ||
| messages: [new HumanMessage('Hello'), new AIMessage('Hi there!')] | ||
| }); | ||
|
|
||
| expect(model.bindTools).toHaveBeenCalled(); | ||
| expect(getBindToolsOptions(model)?.cache_control).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('skips cache_control when enableCaching is false', async () => { | ||
| const model = createSupportedModel(); | ||
| const middleware = orchestrationPromptCachingMiddleware({ | ||
| enableCaching: false, | ||
| minMessagesToCache: 1 | ||
| }); | ||
|
|
||
| const agent = createAgent({ model, middleware: [middleware] }); | ||
|
|
||
| await agent.invoke({ | ||
| messages: [ | ||
| new HumanMessage('Hello'), | ||
| new AIMessage('Hi there!'), | ||
| new HumanMessage('How are you?') | ||
| ] | ||
| }); | ||
|
|
||
| expect(getBindToolsOptions(model)?.cache_control).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('includes the system message in the threshold count', async () => { | ||
| const model = createSupportedModel(); | ||
| const middleware = orchestrationPromptCachingMiddleware({ | ||
| ttl: '1h', | ||
| minMessagesToCache: 3 | ||
| }); | ||
|
|
||
| const agent = createAgent({ | ||
| model, | ||
| systemPrompt: 'You are a helpful assistant', | ||
| middleware: [middleware] | ||
| }); | ||
|
|
||
| // Only 2 messages, but system prompt pushes the total to 3. | ||
| await agent.invoke({ | ||
| messages: [new HumanMessage('Hello'), new AIMessage('Hi there!')] | ||
| }); | ||
|
|
||
| expect(getBindToolsOptions(model)).toHaveProperty('cache_control'); | ||
| expect(getBindToolsOptions(model)?.cache_control).toEqual({ | ||
| type: 'ephemeral', | ||
| ttl: '1h' | ||
| }); | ||
| }); | ||
|
|
||
| describe('non-Orchestration models', () => { | ||
| it('warns and skips caching for non-OrchestrationClient models by default', async () => { | ||
| const model = createUnsupportedModel(); | ||
| const middleware = orchestrationPromptCachingMiddleware({ | ||
| minMessagesToCache: 1 | ||
| }); | ||
|
|
||
| const agent = createAgent({ model, middleware: [middleware] }); | ||
|
|
||
| await expect( | ||
| agent.invoke({ messages: [new HumanMessage('Hello')] }) | ||
| ).resolves.toBeDefined(); | ||
|
|
||
| expect(getBindToolsOptions(model)?.cache_control).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('throws when unsupportedModelBehavior is raise', async () => { | ||
| const model = createUnsupportedModel(); | ||
| const middleware = orchestrationPromptCachingMiddleware({ | ||
| unsupportedModelBehavior: 'raise', | ||
| minMessagesToCache: 1 | ||
| }); | ||
|
|
||
| const agent = createAgent({ model, middleware: [middleware] }); | ||
|
|
||
| await expect( | ||
| agent.invoke({ messages: [new HumanMessage('Hello')] }) | ||
| ).rejects.toThrow( | ||
| "Unsupported model 'AzureOpenAiChatClient'. orchestrationPromptCachingMiddleware requires an OrchestrationClient" | ||
| ); | ||
| }); | ||
|
|
||
| it('prefers runtime context unsupportedModelBehavior over middleware options', async () => { | ||
| const model = createUnsupportedModel(); | ||
| const middleware = orchestrationPromptCachingMiddleware({ | ||
| unsupportedModelBehavior: 'warn', | ||
| minMessagesToCache: 1 | ||
| }); | ||
|
|
||
| const agent = createAgent({ model, middleware: [middleware] }); | ||
|
|
||
| await expect( | ||
| agent.invoke( | ||
| { messages: [new HumanMessage('Hello')] }, | ||
| { | ||
| context: { | ||
| unsupportedModelBehavior: 'raise' | ||
| } | ||
| } | ||
| ) | ||
| ).rejects.toThrow( | ||
| "Unsupported model 'AzureOpenAiChatClient'. orchestrationPromptCachingMiddleware requires an OrchestrationClient" | ||
| ); | ||
| }); | ||
| }); | ||
| }); |
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.
To be reverted after merge of SAP/cloud-sdk-js#6694