Skip to content

Commit

Permalink
fix: 修复部份 bug (Chanzhaoyu#131)
Browse files Browse the repository at this point in the history
* fix: 主题模式图标不一致的问题[Chanzhaoyu#125]

* fix: 修复样式问题[Chanzhaoyu#123][Chanzhaoyu#126]

* perf: 优化代码和添加类型
  • Loading branch information
Chanzhaoyu committed Feb 25, 2023
1 parent 628187f commit 1406292
Show file tree
Hide file tree
Showing 9 changed files with 66 additions and 74 deletions.
35 changes: 16 additions & 19 deletions service/src/chatgpt.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
import * as dotenv from 'dotenv'
import 'isomorphic-fetch'
import type { ChatGPTAPI, ChatMessage, SendMessageOptions } from 'chatgpt'
import { ChatGPTUnofficialProxyAPI } from 'chatgpt'
import type { ChatMessage, SendMessageOptions } from 'chatgpt'
import { ChatGPTAPI, ChatGPTUnofficialProxyAPI } from 'chatgpt'
import { SocksProxyAgent } from 'socks-proxy-agent'
import fetch from 'node-fetch'
import { sendResponse } from './utils'
import type { ApiModel, ChatContext, ChatGPTAPIOptions, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from './types'

dotenv.config()

let apiModel: 'ChatGPTAPI' | 'ChatGPTUnofficialProxyAPI' | undefined

interface ChatContext {
conversationId?: string
parentMessageId?: string
}

const timeoutMs: number = !isNaN(+process.env.TIMEOUT_MS) ? +process.env.TIMEOUT_MS : 30 * 1000

let apiModel: ApiModel

if (!process.env.OPENAI_API_KEY && !process.env.OPENAI_ACCESS_TOKEN)
throw new Error('Missing OPENAI_API_KEY or OPENAI_ACCESS_TOKEN environment variable')

Expand All @@ -25,32 +21,34 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
// To use ESM in CommonJS, you can use a dynamic import
(async () => {
// More Info: https://github.com/transitive-bullshit/chatgpt-api
const { ChatGPTAPI } = await import('chatgpt')

if (process.env.OPENAI_API_KEY) {
api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY })
const options: ChatGPTAPIOptions = {
apiKey: process.env.OPENAI_API_KEY,
debug: false,
}

api = new ChatGPTAPI({ ...options })
apiModel = 'ChatGPTAPI'
}
else {
const options = {
debug: true,
const options: ChatGPTUnofficialProxyAPIOptions = {
accessToken: process.env.OPENAI_ACCESS_TOKEN,
debug: false,
}

if (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) {
const agent = new SocksProxyAgent({
hostname: process.env.SOCKS_PROXY_HOST,
port: process.env.SOCKS_PROXY_PORT,
})
globalThis.console.log(`Using socks proxy: ${process.env.SOCKS_PROXY_HOST}:${process.env.SOCKS_PROXY_PORT}`)
options.fetch = (url, options) => {
return fetch(url, { agent, ...options })
}
}

if (process.env.API_REVERSE_PROXY) {
if (process.env.API_REVERSE_PROXY)
options.apiReverseProxyUrl = process.env.API_REVERSE_PROXY
globalThis.console.log(`Using api reverse proxy: ${process.env.API_REVERSE_PROXY}`)
}

api = new ChatGPTUnofficialProxyAPI({
accessToken: process.env.OPENAI_ACCESS_TOKEN,
Expand Down Expand Up @@ -82,7 +80,6 @@ async function chatReply(
}
}

/** 实验性质的函数,用于处理聊天过程中的中间结果 */
async function chatReplyProcess(
message: string,
lastContext?: { conversationId?: string; parentMessageId?: string },
Expand Down Expand Up @@ -119,7 +116,7 @@ async function chatConfig() {
reverseProxy: process.env.API_REVERSE_PROXY,
timeoutMs,
socksProxy: (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) ? (`${process.env.SOCKS_PROXY_HOST}:${process.env.SOCKS_PROXY_PORT}`) : '-',
},
} as ModelConfig,
})
}

Expand Down
1 change: 0 additions & 1 deletion service/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ router.post('/chat', async (req, res) => {
}
})

/** 实验性质的函数,用于处理聊天过程中的中间结果 */
router.post('/chat-process', async (req, res) => {
res.setHeader('Content-type', 'application/octet-stream')

Expand Down
30 changes: 30 additions & 0 deletions service/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { FetchFn, openai } from 'chatgpt'

export interface ChatContext {
conversationId?: string
parentMessageId?: string
}

export interface ChatGPTAPIOptions {
apiKey: string
debug?: boolean
completionParams?: Partial<openai.CompletionParams>
}

export interface ChatGPTUnofficialProxyAPIOptions {
accessToken: string
apiReverseProxyUrl?: string
model?: string
debug?: boolean
headers?: Record<string, string>
fetch?: FetchFn
}

export interface ModelConfig {
apiModel?: ApiModel
reverseProxy?: string
timeoutMs?: number
socksProxy?: string
}

export type ApiModel = 'ChatGPTAPI' | 'ChatGPTUnofficialProxyAPI' | undefined
1 change: 0 additions & 1 deletion src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ export function fetchChatConfig<T = any>() {
})
}

/** 实验性质的函数,用于处理聊天过程中的中间结果 */
export function fetchChatAPIProcess<T = any>(
params: {
prompt: string
Expand Down
19 changes: 11 additions & 8 deletions src/views/chat/components/Message/Text.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,32 @@
import { computed } from 'vue'
import { marked } from 'marked'
import hljs from 'highlight.js'
import { useBasicLayout } from '@/hooks/useBasicLayout'
interface Props {
inversion?: boolean
error?: boolean
text?: string
loading?: boolean
}
const props = defineProps<Props>()
const { isMobile } = useBasicLayout()
marked.setOptions({
renderer: new marked.Renderer(),
highlight(code) {
return hljs.highlightAuto(code).value
},
})
interface Props {
inversion?: boolean
error?: boolean
text?: string
loading?: boolean
}
const wrapClass = computed(() => {
return [
'text-wrap',
'p-3',
'min-w-[20px]',
'rounded-md',
isMobile.value ? 'p-2' : 'p-3',
props.inversion ? 'bg-[#d2f9d1]' : 'bg-[#f4f6f8]',
props.inversion ? 'dark:bg-[#a1dc95]' : 'dark:bg-[#1e1e20]',
{ 'text-red-500': props.error },
Expand Down
11 changes: 5 additions & 6 deletions src/views/chat/components/Message/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ interface Props {
interface Emit {
(ev: 'regenerate'): void
(ev: 'copy'): void
(ev: 'delete'): void
}
Expand All @@ -33,15 +32,15 @@ function handleRegenerate() {
<template>
<div class="flex w-full mb-6 overflow-hidden" :class="[{ 'flex-row-reverse': inversion }]">
<div
class="flex items-center justify-center rounded-full overflow-hidden flex-shrink-0 w-[32px] h-[32px]"
:class="[inversion ? 'ml-3' : 'mr-3']"
class="flex items-center justify-center flex-shrink-0 h-8 overflow-hidden rounded-full basis-8"
:class="[inversion ? 'ml-2' : 'mr-2']"
>
<AvatarComponent :image="inversion" />
</div>
<div class="flex flex-col flex-1 text-sm" :class="[inversion ? 'items-end' : 'items-start']">
<span class="text-xs text-[#b4bbc4]">
<div class="overflow-hidden text-sm " :class="[inversion ? 'items-end' : 'items-start']">
<p class="text-xs text-[#b4bbc4]" :class="[inversion ? 'text-right' : 'text-left']">
{{ dateTime }}
</span>
</p>
<div
class="flex items-end gap-2 mt-2"
:class="[inversion ? 'flex-row-reverse' : 'flex-row']"
Expand Down
37 changes: 1 addition & 36 deletions src/views/chat/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ async function onConversation() {
if (lastIndex !== -1)
chunk = responseText.substring(lastIndex)
try {
globalThis.console.log(`trunk = ${chunk}`)
const data = JSON.parse(chunk)
updateChat(
+uuid,
Expand All @@ -117,23 +116,6 @@ async function onConversation() {
}
},
})
/*
const { data } = await fetchChatAPI<Chat.ConversationResponse>(message, options, controller.signal)
updateChat(
+uuid,
dataSources.value.length - 1,
{
dateTime: new Date().toLocaleString(),
text: data.text ?? '',
inversion: false,
error: false,
loading: false,
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
requestOptions: { prompt: message, options: { ...options } },
},
)
scrollToBottom()
*/
}
catch (error: any) {
let errorMessage = error?.message ?? 'Something went wrong, please try again later.'
Expand Down Expand Up @@ -206,7 +188,6 @@ async function onRegenerate(index: number) {
if (lastIndex !== -1)
chunk = responseText.substring(lastIndex)
try {
globalThis.console.log(`trunk = ${chunk}`)
const data = JSON.parse(chunk)
updateChat(
+uuid,
Expand All @@ -227,22 +208,6 @@ async function onRegenerate(index: number) {
}
},
})
/*
const { data } = await fetchChatAPI<Chat.ConversationResponse>(message, options, controller.signal)
updateChat(
+uuid,
index,
{
dateTime: new Date().toLocaleString(),
text: data.text ?? '',
inversion: false,
error: false,
loading: false,
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
requestOptions: { prompt: message, ...options },
},
)
*/
}
catch (error: any) {
let errorMessage = error?.message ?? 'Something went wrong, please try again later.'
Expand Down Expand Up @@ -345,7 +310,7 @@ onUnmounted(() => {
<template>
<div class="flex flex-col h-full" :class="wrapClass">
<main class="flex-1 overflow-hidden">
<div ref="scrollRef" class="h-full p-4 overflow-hidden overflow-y-auto" :class="[{ 'p-2': isMobile }]">
<div ref="scrollRef" class="h-full overflow-hidden overflow-y-auto" :class="[isMobile ? 'p-2' : 'p-4']">
<template v-if="!dataSources.length">
<div class="flex items-center justify-center mt-4 text-center text-neutral-300">
<SvgIcon icon="ri:bubble-chart-fill" class="mr-2 text-3xl" />
Expand Down
2 changes: 1 addition & 1 deletion src/views/chat/layout/header/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ function handleUpdateCollapsed() {
</script>

<template>
<header class="fixed top-0 left-0 right-0 z-30 border-b dark:border-neutral-800 bg-white/80 dark:bg-black/30 backdrop-blur">
<header class="fixed top-0 left-0 right-0 z-30 border-b dark:border-neutral-800 bg-white/80 dark:bg-black/20 backdrop-blur">
<div class="relative flex items-center justify-between h-14">
<button class="flex items-center justify-center w-11 h-11" @click="handleUpdateCollapsed">
<SvgIcon v-if="collapsed" class="text-2xl" icon="ri:align-justify" />
Expand Down
4 changes: 2 additions & 2 deletions src/views/chat/layout/sider/Footer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ function handleThemeChange(key: 'light' | 'dark' | 'auto') {
<NDropdown :options="options" placement="top" trigger="click" @select="handleThemeChange">
<HoverButton>
<span class="text-xl text-[#4f555e] dark:text-white">
<SvgIcon v-if="theme === 'dark'" icon="ri:sun-foggy-line" />
<SvgIcon v-if="theme === 'light'" icon="ri:moon-foggy-line" />
<SvgIcon v-if="theme === 'dark'" icon="ri:moon-foggy-line" />
<SvgIcon v-if="theme === 'light'" icon="ri:sun-foggy-line" />
<SvgIcon v-if="theme === 'auto'" icon="ri:contrast-line" />
</span>
</HoverButton>
Expand Down

0 comments on commit 1406292

Please sign in to comment.