Skip to content

Commit

Permalink
feat: 添加上下文关联
Browse files Browse the repository at this point in the history
  • Loading branch information
SaberA1ter committed Apr 5, 2023
1 parent aaef0cd commit db2aaf2
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
8 changes: 7 additions & 1 deletion electron/main/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import { ipcMain } from 'electron'
import { Configuration, OpenAIApi } from 'openai'
import HttpsProxyAgent from 'https-proxy-agent'
import HttpProxyAgent from 'http-proxy-agent'
import { createFailMessage, createSuccessMessage } from '../utils/message'
import { Context, createFailMessage, createSuccessMessage } from '../utils/message'
import { md2Html } from '../utils/markdown'

// 上下文
const context = new Context()

const httpsAgent = new HttpsProxyAgent('http://127.0.0.1:4780')
const httpAgent = new HttpProxyAgent('http://127.0.0.1:4780')
export async function chat(win: Electron.BrowserWindow) {
Expand All @@ -16,19 +19,22 @@ export async function chat(win: Electron.BrowserWindow) {

ipcMain.handle('send-chat', async (e, { content }: { content: string }) => {
try {
const preContext = context.context
const res = await openai.createChatCompletion({
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: '麻烦请用 markdown 回复我。',
},
...preContext,
{ role: 'user', content },
],
}, {
httpAgent,
httpsAgent,
})
context.add(content, res.data.choices[0].message.content)
return createSuccessMessage({
message: md2Html(res.data.choices[0].message.content),
})
Expand Down
32 changes: 32 additions & 0 deletions electron/utils/message.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,35 @@
import type { ChatCompletionRequestMessage } from 'openai'

// 最大上下文数量
const MAX_MESSAGE = 3

export class Context {
private readonly list: ChatCompletionRequestMessage[]

constructor() {
this.list = []
}

public add(userMessage: string, assistantMessage: string) {
if (!userMessage || !assistantMessage)
return
if (this.list.length === MAX_MESSAGE * 2)
this.list.splice(0, 2)

this.list.push({
role: 'user',
content: userMessage,
}, {
role: 'assistant',
content: assistantMessage,
})
}

public get context() {
return [...this.list]
}
}

const errorCodeMap: Record<string, string> = {
401: 'error 401 可能是你的 apiKey 不对劲!',
403: 'error 403 拒绝访问,哒咩!',
Expand Down
1 change: 1 addition & 0 deletions tsconfig.node.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"compilerOptions": {
"target": "ESNext",
"composite": true,
"module": "ESNext",
"moduleResolution": "Node",
Expand Down

0 comments on commit db2aaf2

Please sign in to comment.