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

Feat: chat regenerate and proceed #26

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
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
25 changes: 17 additions & 8 deletions src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,11 @@ export interface Conversation {

class ChatGPT {
protected http: Quester
protected _endpoint: string
// stores access tokens for up to 10 seconds before needing to refresh
protected _accessTokenCache = new ExpiryMap<string, string>(10 * 1000)

constructor(ctx: Context, public config: ChatGPT.Config) {
this.http = ctx.http.extend(config)
this._endpoint = trimSlash(config.endpoint)
}

async getIsAuthenticated() {
Expand All @@ -46,13 +44,13 @@ class ChatGPT {
* @param message - The plaintext message to send.
* @param opts.conversationId - Optional ID of the previous message in a conversation
*/
async sendMessage(conversation: Conversation): Promise<Required<Conversation>> {
async sendMessage(conversation: Conversation, action: ChatGPT.Action): Promise<Required<Conversation>> {
const { conversationId, messageId = uuidv4(), message } = conversation

const accessToken = await this.refreshAccessToken()

const body: types.ConversationJSONBody = {
action: 'next',
action,
conversation_id: conversationId,
messages: [
{
Expand All @@ -68,11 +66,9 @@ class ChatGPT {
parent_message_id: messageId,
}

const url = this._endpoint + '/backend-api/conversation'

let data: internal.Readable
try {
const resp = await this.http.axios<internal.Readable>(url, {
const resp = await this.http.axios<internal.Readable>('/backend-api/conversation', {
method: 'POST',
responseType: 'stream',
data: body,
Expand Down Expand Up @@ -148,7 +144,7 @@ class ChatGPT {
}

try {
const res = await this.http.get(this._endpoint + '/api/auth/session', {
const res = await this.http.get('/api/auth/session', {
headers: {
cookie: `__Secure-next-auth.session-token=${this.config.sessionToken}`,
},
Expand All @@ -170,9 +166,14 @@ class ChatGPT {
}

namespace ChatGPT {
export type Action = 'next' | 'variant' | 'continue'
export type Actions = Record<string, Action>

export interface Config {
sessionToken: string
endpoint: string
keywordContinue: string[]
keywordVariant: string[]
markdown?: boolean
headers?: Dict<string>
proxyAgent?: string
Expand All @@ -186,6 +187,14 @@ namespace ChatGPT {
}),
proxyAgent: Schema.string().role('link').description('使用的代理服务器地址。'),
markdown: Schema.boolean().hidden().default(false),
keywordContinue: Schema.union([
Schema.array(String),
Schema.transform(String, (prefix) => [prefix]),
] as const).description('触发机器人继续回答的关键词。').default(['继续说', '请继续', '继续']),
keywordVariant: Schema.union([
Schema.array(String),
Schema.transform(String, (prefix) => [prefix]),
] as const).description('触发机器人重新回答的关键词。').default(['重新说', '重试']),
}).description('登录设置')
}

Expand Down
17 changes: 12 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import ChatGPT from './api'
import ChatGPT, { Conversation } from './api'
import { Context, Logger, Schema, Session, SessionError } from 'koishi'

const logger = new Logger('chatgpt')
Expand Down Expand Up @@ -37,13 +37,18 @@ export const Config: Schema<Config> = Schema.intersect([
}),
])

const conversations = new Map<string, { messageId: string; conversationId: string }>()
const conversations = new Map<string, Conversation>()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not really good to use type Conversation here, as we don't save messages in the map.
If you stick with a type, you can split them into two types, but I argue with that.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is your specific idea? My idea is to use the Conversation type here and save it in a Map. I can't think of any other idea at the moment.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think just to revert this type would be good to me.
Otherwise you should write something like:

export interface Conversation {
  messageId: string
  conversationId: string
}

export interface ConversationMessage extends Conversation {
  message: string
}

That would be much much redundant.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So how do I save the chat context, which is necessary in the implementation of variant?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or

Suggested change
const conversations = new Map<string, Conversation>()
const conversations = new Map<string, Omit<Conversation, 'message'>>()

while Omit is a built-in type of typescript.


export function apply(ctx: Context, config: Config) {
ctx.i18n.define('zh', require('./locales/zh-CN'))

const api = new ChatGPT(ctx, config)

const actions: ChatGPT.Actions = {
...Object.fromEntries(config.keywordContinue.map((value) => [value, 'continue'])),
...Object.fromEntries(config.keywordVariant.map((value) => [value, 'variant']))
}

const getContextKey = (session: Session, config: Config) => {
switch (config.interaction) {
case 'user':
Expand Down Expand Up @@ -93,9 +98,11 @@ export function apply(ctx: Context, config: Config) {

try {
// send a message and wait for the response
const { conversationId, messageId } = conversations.get(key) ?? {}
const response = await api.sendMessage({ message: input, conversationId, messageId })
conversations.set(key, { conversationId: response.conversationId, messageId: response.messageId })
let request: Conversation = conversations.get(key)
let action: ChatGPT.Action = input in actions ? actions[input] : 'next'
Comment on lines +101 to +102
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also always use const, unless you really really need to change it in runtime, otherwise keep it immutable.


const response = await api.sendMessage({ message: input, ...request}, action)
conversations.set(key, { message: request?.message, conversationId: response.conversationId, messageId: response.messageId })
return response.message
} catch (error) {
logger.warn(error)
Expand Down