forked from cline/cline
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
feat: add prompt caching support for LiteLLM (#5791) #6074
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
MuriloFP
wants to merge
3
commits into
RooCodeInc:main
Choose a base branch
from
MuriloFP:feat/issue-5791-litellm-prompt-caching
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.
+262
−10
Open
Changes from 1 commit
Commits
Show all changes
3 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
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,130 @@ | ||
import { describe, it, expect, vi, beforeEach } from "vitest" | ||
import OpenAI from "openai" | ||
import { Anthropic } from "@anthropic-ai/sdk" | ||
|
||
import { LiteLLMHandler } from "../lite-llm" | ||
import { ApiHandlerOptions } from "../../../shared/api" | ||
import { litellmDefaultModelId, litellmDefaultModelInfo } from "@roo-code/types" | ||
|
||
// Mock vscode first to avoid import errors | ||
vi.mock("vscode", () => ({})) | ||
|
||
// Mock OpenAI | ||
vi.mock("openai", () => { | ||
const mockStream = { | ||
[Symbol.asyncIterator]: vi.fn(), | ||
} | ||
|
||
const mockCreate = vi.fn().mockReturnValue({ | ||
withResponse: vi.fn().mockResolvedValue({ data: mockStream }), | ||
}) | ||
|
||
return { | ||
default: vi.fn().mockImplementation(() => ({ | ||
chat: { | ||
completions: { | ||
create: mockCreate, | ||
}, | ||
}, | ||
})), | ||
} | ||
}) | ||
|
||
// Mock model fetching | ||
vi.mock("../fetchers/modelCache", () => ({ | ||
getModels: vi.fn().mockImplementation(() => { | ||
return Promise.resolve({ | ||
[litellmDefaultModelId]: litellmDefaultModelInfo, | ||
}) | ||
}), | ||
})) | ||
|
||
describe("LiteLLMHandler", () => { | ||
let handler: LiteLLMHandler | ||
let mockOptions: ApiHandlerOptions | ||
let mockOpenAIClient: any | ||
|
||
beforeEach(() => { | ||
vi.clearAllMocks() | ||
mockOptions = { | ||
litellmApiKey: "test-key", | ||
litellmBaseUrl: "http://localhost:4000", | ||
litellmModelId: litellmDefaultModelId, | ||
} | ||
handler = new LiteLLMHandler(mockOptions) | ||
mockOpenAIClient = new OpenAI() | ||
}) | ||
|
||
describe("prompt caching", () => { | ||
it("should add cache control headers when litellmUsePromptCache is enabled", async () => { | ||
const optionsWithCache: ApiHandlerOptions = { | ||
...mockOptions, | ||
litellmUsePromptCache: true, | ||
} | ||
handler = new LiteLLMHandler(optionsWithCache) | ||
|
||
const systemPrompt = "You are a helpful assistant" | ||
const messages: Anthropic.Messages.MessageParam[] = [ | ||
{ role: "user", content: "Hello" }, | ||
{ role: "assistant", content: "Hi there!" }, | ||
{ role: "user", content: "How are you?" }, | ||
] | ||
|
||
// Mock the stream response | ||
const mockStream = { | ||
async *[Symbol.asyncIterator]() { | ||
yield { | ||
choices: [{ delta: { content: "I'm doing well!" } }], | ||
usage: { | ||
prompt_tokens: 100, | ||
completion_tokens: 50, | ||
cache_creation_input_tokens: 20, | ||
cache_read_input_tokens: 30, | ||
}, | ||
} | ||
}, | ||
} | ||
|
||
mockOpenAIClient.chat.completions.create.mockReturnValue({ | ||
withResponse: vi.fn().mockResolvedValue({ data: mockStream }), | ||
}) | ||
|
||
const generator = handler.createMessage(systemPrompt, messages) | ||
const results = [] | ||
for await (const chunk of generator) { | ||
results.push(chunk) | ||
} | ||
|
||
// Verify that create was called with cache control headers | ||
const createCall = mockOpenAIClient.chat.completions.create.mock.calls[0][0] | ||
|
||
// Check system message has cache control | ||
expect(createCall.messages[0]).toMatchObject({ | ||
role: "system", | ||
content: systemPrompt, | ||
cache_control: { type: "ephemeral" }, | ||
}) | ||
|
||
// Check that the last two user messages have cache control | ||
const userMessageIndices = createCall.messages | ||
.map((msg: any, idx: number) => (msg.role === "user" ? idx : -1)) | ||
.filter((idx: number) => idx !== -1) | ||
|
||
const lastUserIdx = userMessageIndices[userMessageIndices.length - 1] | ||
|
||
expect(createCall.messages[lastUserIdx]).toMatchObject({ | ||
cache_control: { type: "ephemeral" }, | ||
}) | ||
|
||
// Verify usage includes cache tokens | ||
const usageChunk = results.find((chunk) => chunk.type === "usage") | ||
expect(usageChunk).toMatchObject({ | ||
type: "usage", | ||
inputTokens: 100, | ||
outputTokens: 50, | ||
cacheWriteTokens: 20, | ||
cacheReadTokens: 30, | ||
}) | ||
}) | ||
}) | ||
}) |
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
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.
Consider adding an assertion for the second last user message as well, to fully verify that cache control headers are applied to both the last two user messages.