Skip to content
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

Fix prompt length calculation #548

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 7 additions & 20 deletions src/chatgpt-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ import { fetchSSE } from './fetch-sse'

const CHATGPT_MODEL = 'gpt-3.5-turbo'

const USER_LABEL_DEFAULT = 'User'
const ASSISTANT_LABEL_DEFAULT = 'ChatGPT'

export class ChatGPTAPI {
protected _apiKey: string
protected _apiBaseUrl: string
Expand Down Expand Up @@ -362,9 +359,6 @@ export class ChatGPTAPI {
const { systemMessage = this._systemMessage } = opts
let { parentMessageId } = opts

const userLabel = USER_LABEL_DEFAULT
const assistantLabel = ASSISTANT_LABEL_DEFAULT

const maxNumTokens = this._maxModelTokens - this._maxResponseTokens
let messages: types.openai.ChatCompletionRequestMessage[] = []

Expand All @@ -388,23 +382,16 @@ export class ChatGPTAPI {
let numTokens = 0

do {
const prompt = nextMessages
.reduce((prompt, message) => {
switch (message.role) {
case 'system':
return prompt.concat([`Instructions:\n${message.content}`])
case 'user':
return prompt.concat([`${userLabel}:\n${message.content}`])
default:
return prompt.concat([`${assistantLabel}:\n${message.content}`])
}
}, [] as string[])
.join('\n\n')
let nextNumTokensEstimate = 3
for (let message of nextMessages) {
nextNumTokensEstimate += 4 + (await this._getTokenCount(message.role))
nextNumTokensEstimate += await this._getTokenCount(message.content)
if (message.name) nextNumTokensEstimate -= 1
}

const nextNumTokensEstimate = await this._getTokenCount(prompt)
const isValidPrompt = nextNumTokensEstimate <= maxNumTokens

if (prompt && !isValidPrompt) {
if (!isValidPrompt) {
break
}

Expand Down