Elffuss BraidHub

kikocis/continue public

main · 4.0 KiBRawPermalink
1import { ChatCompletionCreateParams } from "openai/resources/index";
2
3import { LLMOptions } from "../../index.js";
4import { osModelsEditPrompt } from "../templates/edit.js";
5
6import OpenAI from "./OpenAI.js";
7
8class OpenRouter extends OpenAI {
9 static providerName = "openrouter";
10 static defaultOptions: Partial<LLMOptions> = {
11 apiBase: "https://openrouter.ai/api/v1/",
12 model: "gpt-4o-mini",
13 promptTemplates: {
14 edit: osModelsEditPrompt,
15 },
16 useLegacyCompletionsEndpoint: false,
17 };
18
19 /**
20 * Detect if the model is an Anthropic/Claude model
21 */
22 private isAnthropicModel(model?: string): boolean {
23 if (!model) return false;
24 const modelLower = model.toLowerCase();
25 return modelLower.includes("claude");
26 }
27
28 /**
29 * Add cache_control to message content for Anthropic models
30 */
31 private addCacheControlToContent(content: any, addCaching: boolean): any {
32 if (!addCaching) return content;
33
34 if (typeof content === "string") {
35 return [
36 {
37 type: "text",
38 text: content,
39 cache_control: { type: "ephemeral" },
40 },
41 ];
42 }
43
44 if (Array.isArray(content)) {
45 // For array content, add cache_control to the last text item
46 return content.map((part, idx) => {
47 if (part.type === "text" && idx === content.length - 1) {
48 return {
49 ...part,
50 cache_control: { type: "ephemeral" },
51 };
52 }
53 return part;
54 });
55 }
56
57 return content;
58 }
59
60 /**
61 * Override modifyChatBody to add Anthropic caching when appropriate
62 */
63 protected modifyChatBody(
64 body: ChatCompletionCreateParams,
65 ): ChatCompletionCreateParams {
66 // First apply parent modifications
67 body = super.modifyChatBody(body);
68
69 // Check if we should apply Anthropic caching
70 if (
71 !this.isAnthropicModel(body.model) ||
72 (!this.cacheBehavior && !this.completionOptions.promptCaching)
73 ) {
74 return body;
75 }
76
77 const shouldCacheConversation =
78 this.cacheBehavior?.cacheConversation ||
79 this.completionOptions.promptCaching;
80 const shouldCacheSystemMessage =
81 this.cacheBehavior?.cacheSystemMessage ||
82 this.completionOptions.promptCaching;
83
84 if (!shouldCacheConversation && !shouldCacheSystemMessage) {
85 return body;
86 }
87
88 // Follow the same logic as Anthropic.ts: filter out system messages first
89 const filteredMessages = body.messages.filter(
90 (m: any) => m.role !== "system" && !!m.content,
91 );
92
93 // Find the last two user message indices from the filtered array
94 const lastTwoUserMsgIndices = filteredMessages
95 .map((msg: any, index: number) => (msg.role === "user" ? index : -1))
96 .filter((index: number) => index !== -1)
97 .slice(-2);
98
99 // Create a mapping from filtered indices to original indices
100 let filteredIndex = 0;
101 const filteredToOriginalIndexMap: number[] = [];
102 body.messages.forEach((msg: any, originalIndex: number) => {
103 if (msg.role !== "system" && !!msg.content) {
104 filteredToOriginalIndexMap[filteredIndex] = originalIndex;
105 filteredIndex++;
106 }
107 });
108
109 // Modify messages to add cache_control
110 body.messages = body.messages.map((message: any, idx) => {
111 // Handle system message caching
112 if (message.role === "system" && shouldCacheSystemMessage) {
113 return {
114 ...message,
115 content: this.addCacheControlToContent(message.content, true),
116 };
117 }
118
119 // Handle conversation caching for last two user messages
120 // Check if this message's index (in filtered array) is one of the last two user messages
121 const filteredIdx = filteredToOriginalIndexMap.indexOf(idx);
122 if (
123 message.role === "user" &&
124 shouldCacheConversation &&
125 filteredIdx !== -1 &&
126 lastTwoUserMsgIndices.includes(filteredIdx)
127 ) {
128 return {
129 ...message,
130 content: this.addCacheControlToContent(message.content, true),
131 };
132 }
133
134 return message;
135 });
136
137 return body;
138 }
139}
140
141export default OpenRouter;