/
SimpleChatModel.ts
206 lines (181 loc) · 6.86 KB
/
SimpleChatModel.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import { findLast } from 'lodash'
import {
type ChatMessage,
type ContextItem,
type Message,
ModelProvider,
type SerializedChatInteraction,
type SerializedChatTranscript,
errorToChatError,
isCodyIgnoredFile,
toRangeData,
} from '@sourcegraph/cody-shared'
import type { Repo } from '../../context/repo-fetcher'
import { getChatPanelTitle } from './chat-helpers'
export class SimpleChatModel {
public readonly maxChars: number
constructor(
public modelID: string,
private messages: ChatMessage[] = [],
public readonly sessionID: string = new Date(Date.now()).toUTCString(),
private customChatTitle?: string,
private selectedRepos?: Repo[]
) {
this.maxChars = ModelProvider.getMaxCharsByModel(this.modelID)
}
public get charsLeft(): number {
let used = 0
for (const msg of this.messages) {
if (used > this.maxChars) {
return 0
}
used += msg.speaker.length + (msg.text?.length || 0) + 3
}
return this.maxChars - used
}
public isEmpty(): boolean {
return this.messages.length === 0
}
public setLastMessageContext(newContextUsed: ContextItem[]): void {
const lastMessage = this.messages.at(-1)
if (!lastMessage) {
throw new Error('no last message')
}
if (lastMessage.speaker !== 'human') {
throw new Error('Cannot set new context used for bot message')
}
lastMessage.contextFiles = newContextUsed.filter(c => !isCodyIgnoredFile(c.uri))
}
public addHumanMessage(message: Omit<ChatMessage, 'speaker'>): void {
if (this.messages.at(-1)?.speaker === 'human') {
throw new Error('Cannot add a user message after a user message')
}
this.messages.push({ ...message, speaker: 'human' })
}
public addBotMessage(message: Omit<Message, 'speaker'>): void {
const lastMessage = this.messages.at(-1)
let error: any
// If there is no text, it could be a placeholder message for an error
if (lastMessage?.speaker === 'assistant') {
if (lastMessage?.text) {
throw new Error('Cannot add a bot message after a bot message')
}
error = this.messages.pop()?.error
}
this.messages.push({
...message,
speaker: 'assistant',
error,
})
}
public addErrorAsBotMessage(error: Error): void {
const lastMessage = this.messages.at(-1)
// Remove the last assistant message if any
const lastAssistantMessage: ChatMessage | undefined =
lastMessage?.speaker === 'assistant' ? this.messages.pop() : undefined
// Then add a new assistant message with error added
this.messages.push({
...(lastAssistantMessage ?? {}),
speaker: 'assistant',
error: errorToChatError(error),
})
}
public getLastHumanMessage(): ChatMessage | undefined {
return findLast(this.messages, message => message.speaker === 'human')
}
public getLastSpeakerMessageIndex(speaker: 'human' | 'assistant'): number | undefined {
return this.messages.findLastIndex(message => message.speaker === speaker)
}
/**
* Removes all messages from the given index when it matches the expected speaker.
*
* expectedSpeaker must match the speaker of the message at the given index.
* This helps ensuring the intented messages are being removed.
*/
public removeMessagesFromIndex(index: number, expectedSpeaker: 'human' | 'assistant'): void {
if (this.isEmpty()) {
throw new Error('SimpleChatModel.removeMessagesFromIndex: not message to remove')
}
const speakerAtIndex = this.messages.at(index)?.speaker
if (speakerAtIndex !== expectedSpeaker) {
throw new Error(
`SimpleChatModel.removeMessagesFromIndex: expected ${expectedSpeaker}, got ${speakerAtIndex}`
)
}
// Removes everything from the index to the last element
this.messages.splice(index)
}
public getMessages(): readonly ChatMessage[] {
return this.messages
}
public getChatTitle(): string {
if (this.customChatTitle) {
return this.customChatTitle
}
const lastHumanMessage = this.getLastHumanMessage()
return getChatPanelTitle(lastHumanMessage?.text ?? '')
}
public getCustomChatTitle(): string | undefined {
return this.customChatTitle
}
public setCustomChatTitle(title: string): void {
this.customChatTitle = title
}
public getSelectedRepos(): Repo[] | undefined {
return this.selectedRepos ? this.selectedRepos.map(r => ({ ...r })) : undefined
}
public setSelectedRepos(repos: Repo[] | undefined): void {
this.selectedRepos = repos ? repos.map(r => ({ ...r })) : undefined
}
/**
* Serializes to the transcript JSON format.
*/
public toSerializedChatTranscript(): SerializedChatTranscript {
const interactions: SerializedChatInteraction[] = []
for (let i = 0; i < this.messages.length; i += 2) {
const humanMessage = this.messages[i]
const assistantMessage = this.messages.at(i + 1)
interactions.push(messageToSerializedChatInteraction(humanMessage, assistantMessage))
}
const result: SerializedChatTranscript = {
id: this.sessionID,
chatModel: this.modelID,
chatTitle: this.getCustomChatTitle(),
lastInteractionTimestamp: this.sessionID,
interactions,
}
if (this.selectedRepos) {
result.enhancedContext = {
selectedRepos: this.selectedRepos.map(r => ({ ...r })),
}
}
return result
}
}
function messageToSerializedChatInteraction(
humanMessage: ChatMessage,
assistantMessage?: ChatMessage
): SerializedChatInteraction {
if (humanMessage?.speaker !== 'human') {
throw new Error('expected human message, got bot')
}
if (humanMessage.speaker !== 'human') {
throw new Error(`expected human message to have speaker == 'human', got ${humanMessage.speaker}`)
}
if (assistantMessage && assistantMessage.speaker !== 'assistant') {
throw new Error(
`expected bot message to have speaker == 'assistant', got ${assistantMessage.speaker}`
)
}
return { humanMessage, assistantMessage: assistantMessage ?? null }
}
export function prepareChatMessage(message: ChatMessage): ChatMessage {
return {
...message,
contextFiles: message.contextFiles?.map(item => ({
...item,
// De-hydrate because vscode.Range serializes to `[start, end]` in JSON.
range: toRangeData(item.range),
})),
}
}