Skip to content

Commit e471f83

Browse files
committed
Extract adding cache control to a helper
1 parent 386d129 commit e471f83

File tree

2 files changed

+26
-15
lines changed

2 files changed

+26
-15
lines changed

backend/src/main-prompt.ts

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ import {
3636
} from './tools'
3737
import { trimMessagesToFitTokenLimit } from './util/messages'
3838
import { checkTerminalCommand } from './check-terminal-command'
39-
import { toContentString } from 'common/util/messages'
39+
import { withCacheControl, toContentString } from 'common/util/messages'
4040

4141
export const mainPrompt = async (
4242
ws: WebSocket,
@@ -782,20 +782,7 @@ function getMessagesSubset(messages: Message[], otherTokens: number) {
782782
// Cache up to the last message!
783783
const lastMessage = messagesSubset[messagesSubset.length - 1]
784784
if (lastMessage) {
785-
if (typeof lastMessage.content === 'string') {
786-
// Transform to a content array
787-
;(lastMessage as any).content = [
788-
{
789-
type: 'text',
790-
text: lastMessage.content,
791-
cache_control: { type: 'ephemeral' as const },
792-
},
793-
]
794-
} else {
795-
lastMessage.content[lastMessage.content.length - 1].cache_control = {
796-
type: 'ephemeral' as const,
797-
}
798-
}
785+
messagesSubset[messagesSubset.length - 1] = withCacheControl(lastMessage)
799786
} else {
800787
logger.debug(
801788
{

common/src/util/messages.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,27 @@ export function toContentString(msg: Message): string {
4747
if (typeof content === 'string') return content
4848
return content.map((item) => (item as any)?.text ?? '').join('\n')
4949
}
50+
51+
export function withCacheControl(msg: Message): Message {
52+
if (typeof msg.content === 'string') {
53+
return {
54+
...msg,
55+
content: [
56+
{
57+
type: 'text',
58+
text: msg.content,
59+
cache_control: { type: 'ephemeral' as const },
60+
},
61+
],
62+
}
63+
} else {
64+
return {
65+
...msg,
66+
content: msg.content.map((item, i) =>
67+
i === msg.content.length - 1
68+
? { ...item, cache_control: { type: 'ephemeral' as const } }
69+
: item
70+
),
71+
}
72+
}
73+
}

0 commit comments

Comments
 (0)