-
Notifications
You must be signed in to change notification settings - Fork 754
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
9 changed files
with
4,517 additions
and
2,313 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
import { Models, getUserConfig } from '../../config/index.mjs' | ||
import { pushRecord, setAbortController } from './shared.mjs' | ||
import { isEmpty } from 'lodash-es' | ||
import { getToken } from '../../utils/jwt-token-generator.mjs' | ||
import { createParser } from '../../utils/eventsource-parser.mjs' | ||
|
||
async function fetchSSE(resource, options) { | ||
const { onMessage, onStart, onEnd, onError, ...fetchOptions } = options | ||
const resp = await fetch(resource, fetchOptions).catch(async (err) => { | ||
await onError(err) | ||
}) | ||
if (!resp) return | ||
if (!resp.ok) { | ||
await onError(resp) | ||
return | ||
} | ||
|
||
const parser = createParser((event) => { | ||
if (event.type === 'event') { | ||
onMessage(event) | ||
} | ||
}) | ||
|
||
let hasStarted = false | ||
const reader = resp.body.getReader() | ||
let result | ||
while (!(result = await reader.read()).done) { | ||
const chunk = result.value | ||
if (!hasStarted) { | ||
hasStarted = true | ||
await onStart(new TextDecoder().decode(chunk)) | ||
} | ||
parser.feed(chunk) | ||
} | ||
await onEnd() | ||
} | ||
|
||
/** | ||
* @param {Runtime.Port} port | ||
* @param {string} question | ||
* @param {Session} session | ||
* @param {string} modelName | ||
*/ | ||
export async function generateAnswersWithChatGLMApi(port, question, session, modelName) { | ||
const { controller, messageListener, disconnectListener } = setAbortController(port) | ||
const config = await getUserConfig() | ||
|
||
const prompt = [] | ||
for (const record of session.conversationRecords.slice(-config.maxConversationContextLength)) { | ||
prompt.push({ role: 'user', content: record.question }) | ||
prompt.push({ role: 'assistant', content: record.answer }) | ||
} | ||
prompt.push({ role: 'user', content: question }) | ||
|
||
let answer = '' | ||
await fetchSSE( | ||
`https://open.bigmodel.cn/api/paas/v3/model-api/${Models[modelName].value}/sse-invoke`, | ||
{ | ||
method: 'POST', | ||
signal: controller.signal, | ||
headers: { | ||
'Content-Type': 'application/json; charset=UTF-8', | ||
Accept: 'text/event-stream', | ||
Authorization: getToken(config.chatglmApiKey), | ||
}, | ||
body: JSON.stringify({ | ||
prompt: prompt, | ||
// temperature: config.temperature, | ||
// top_t: 0.7, | ||
// request_id: string | ||
// incremental: true, | ||
// return_type: "json_string", | ||
// ref: {"enable": "true", "search_query": "history"}, | ||
}), | ||
onMessage(event) { | ||
console.debug('sse event', event) | ||
|
||
// Handle different types of events | ||
switch (event.event) { | ||
case 'add': | ||
// In the case of an "add" event, append the completion to the answer | ||
if (event.data) { | ||
answer += event.data | ||
port.postMessage({ answer: answer, done: false, session: null }) | ||
} | ||
break | ||
case 'error': | ||
case 'interrupted': | ||
case 'finish': | ||
pushRecord(session, question, answer) | ||
console.debug('conversation history', { content: session.conversationRecords }) | ||
port.postMessage({ answer: null, done: true, session: session }) | ||
break | ||
default: | ||
break | ||
} | ||
}, | ||
async onStart() {}, | ||
async onEnd() { | ||
port.postMessage({ done: true }) | ||
port.onMessage.removeListener(messageListener) | ||
port.onDisconnect.removeListener(disconnectListener) | ||
}, | ||
async onError(resp) { | ||
port.onMessage.removeListener(messageListener) | ||
port.onDisconnect.removeListener(disconnectListener) | ||
if (resp instanceof Error) throw resp | ||
const error = await resp.json().catch(() => ({})) | ||
throw new Error( | ||
!isEmpty(error) ? JSON.stringify(error) : `${resp.status} ${resp.statusText}`, | ||
) | ||
}, | ||
}, | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import jwt from 'jsonwebtoken' | ||
|
||
let jwtToken = null | ||
let tokenExpiration = null // Declare tokenExpiration in the module scope | ||
|
||
function generateToken(apiKey, timeoutSeconds) { | ||
const parts = apiKey.split('.') | ||
if (parts.length !== 2) { | ||
throw new Error('Invalid API key') | ||
} | ||
|
||
const ms = Date.now() | ||
const currentSeconds = Math.floor(ms / 1000) | ||
const [id, secret] = parts | ||
const payload = { | ||
api_key: id, | ||
exp: currentSeconds + timeoutSeconds, | ||
timestamp: currentSeconds, | ||
} | ||
|
||
jwtToken = jwt.sign(payload, secret, { | ||
header: { | ||
alg: 'HS256', | ||
typ: 'JWT', | ||
sign_type: 'SIGN', | ||
}, | ||
}) | ||
tokenExpiration = ms + timeoutSeconds * 1000 | ||
} | ||
|
||
function shouldRegenerateToken() { | ||
const ms = Date.now() | ||
return !jwtToken || ms >= tokenExpiration | ||
} | ||
|
||
function getToken(apiKey) { | ||
if (shouldRegenerateToken()) { | ||
generateToken(apiKey, 86400) // Hard-coded to regenerate the token every 24 hours | ||
} | ||
return jwtToken | ||
} | ||
|
||
export { getToken } |