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: 增加了生成图片的功能 #410

Closed
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
6 changes: 6 additions & 0 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,12 @@ For all parameter variables, check [here](#docker-parameter-example) or see:

[✓] Formatting and beautifying code-like message types

[✓] Access rights control

[✓] Data import and export

[✓] Save message to local image

[✓] Multilingual interface

[✓] Interface themes
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ API_REVERSE_PROXY=

[✓] 对代码等消息类型的格式化美化处理

[✓] 访问权限控制

[✓] 数据导入、导出

[✓] 保存消息到本地图片

[✓] 界面多语言

[✓] 界面主题
Expand Down
1 change: 1 addition & 0 deletions service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"express": "^4.18.2",
"isomorphic-fetch": "^3.0.0",
"node-fetch": "^3.3.0",
"openai": "^3.2.1",
"socks-proxy-agent": "^7.0.0"
},
"devDependencies": {
Expand Down
54 changes: 54 additions & 0 deletions service/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

43 changes: 41 additions & 2 deletions service/src/chatgpt/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { ChatGPTAPIOptions, ChatMessage, SendMessageOptions } from 'chatgpt
import { ChatGPTAPI, ChatGPTUnofficialProxyAPI } from 'chatgpt'
import { SocksProxyAgent } from 'socks-proxy-agent'
import fetch from 'node-fetch'
import { Configuration, OpenAIApi } from 'openai'
import { sendResponse } from '../utils'
import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'

Expand All @@ -28,6 +29,7 @@ if (!process.env.OPENAI_API_KEY && !process.env.OPENAI_ACCESS_TOKEN)
throw new Error('Missing OPENAI_API_KEY or OPENAI_ACCESS_TOKEN environment variable')

let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
let openAiApi: OpenAIApi;

(async () => {
// More Info: https://github.com/transitive-bullshit/chatgpt-api
Expand All @@ -41,8 +43,14 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
debug: false,
}

if (process.env.OPENAI_API_BASE_URL && process.env.OPENAI_API_BASE_URL.trim().length > 0)
const openAiConfiguration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
})

if (process.env.OPENAI_API_BASE_URL && process.env.OPENAI_API_BASE_URL.trim().length > 0) {
options.apiBaseUrl = process.env.OPENAI_API_BASE_URL
openAiConfiguration.basePath = process.env.OPENAI_API_BASE_URL
}

if (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) {
const agent = new SocksProxyAgent({
Expand All @@ -52,9 +60,12 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
options.fetch = (url, options) => {
return fetch(url, { agent, ...options })
}
openAiConfiguration.baseOptions.httpAgent = agent
openAiConfiguration.baseOptions.httpsAgent = agent
}

api = new ChatGPTAPI({ ...options })
openAiApi = new OpenAIApi(openAiConfiguration)
apiModel = 'ChatGPTAPI'
}
else {
Expand All @@ -81,6 +92,34 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
}
})()

async function generateImage(message: string) {
if (!message)
return sendResponse({ type: 'Fail', message: 'Message is empty' })

if (!process.env.OPENAI_API_KEY)
return sendResponse({ type: 'Fail', message: 'Need OPENAI_API_KEY' })

try {
const response = await openAiApi.createImage({
prompt: message,
n: 1,
size: '512x512',
})

if (!response.data.data)
return sendResponse({ type: 'Fail', message: 'Failed to generate image' })

return sendResponse({ type: 'Success', data: response.data.data[0] })
}
catch (error: any) {
const code = error.statusCode
global.console.log(error)
if (Reflect.has(ErrorCodeMessage, code))
return sendResponse({ type: 'Fail', message: ErrorCodeMessage[code] })
return sendResponse({ type: 'Fail', message: error.message ?? 'Please check the back-end console' })
}
}

async function chatReplyProcess(
message: string,
lastContext?: { conversationId?: string; parentMessageId?: string },
Expand Down Expand Up @@ -131,4 +170,4 @@ async function chatConfig() {

export type { ChatContext, ChatMessage }

export { chatReplyProcess, chatConfig }
export { chatReplyProcess, chatConfig, generateImage }
12 changes: 11 additions & 1 deletion service/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import express from 'express'
import type { ChatContext, ChatMessage } from './chatgpt'
import { chatConfig, chatReplyProcess } from './chatgpt'
import { chatConfig, chatReplyProcess, generateImage } from './chatgpt'
import { auth } from './middleware/auth'

const app = express()
Expand Down Expand Up @@ -35,6 +35,16 @@ router.post('/chat-process', auth, async (req, res) => {
}
})

router.post('/generate-image', async (req, res) => {
try {
const { prompt } = req.body as { prompt: string }
res.send(await generateImage(prompt))
}
catch (error) {
res.send(error)
}
})

router.post('/config', async (req, res) => {
try {
const response = await chatConfig()
Expand Down
11 changes: 11 additions & 0 deletions src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@ export function fetchChatConfig<T = any>() {
})
}

export function fetchGenerateImage<T = any>(
prompt: string,
signal?: GenericAbortSignal,
) {
return post<T>({
url: '/generate-image',
data: { prompt },
signal,
})
}

export function fetchChatAPIProcess<T = any>(
params: {
prompt: string
Expand Down
64 changes: 34 additions & 30 deletions src/components/common/Setting/General.vue
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const themeOptions: { label: string; key: Theme; icon: string }[] = [
]

const languageOptions: { label: string; key: Language; value: Language }[] = [
{ label: '中文', key: 'zh-CN', value: 'zh-CN' },
{ label: '简体中文', key: 'zh-CN', value: 'zh-CN' },
{ label: '繁體中文', key: 'zh-TW', value: 'zh-TW' },
{ label: 'English', key: 'en-US', value: 'en-US' },
]
Expand Down Expand Up @@ -151,38 +151,41 @@ function handleImportButtonClick(): void {
<div class="flex items-center space-x-4">
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.chatHistory') }}</span>

<NButton @click="exportData">
<template #icon>
<SvgIcon icon="ri:download-2-fill" />
</template>
{{ $t('common.export') }}
</NButton>

<input id="fileInput" type="file" style="display:none" @change="importData">
<NButton @click="handleImportButtonClick">
<template #icon>
<SvgIcon icon="ri:upload-2-fill" />
</template>
{{ $t('common.import') }}
</NButton>

<NPopconfirm placement="bottom" @positive-click="clearData">
<template #trigger>
<NButton>
<template #icon>
<SvgIcon icon="ri:close-circle-line" />
</template>
{{ $t('common.clear') }}
</NButton>
</template>
{{ $t('chat.clearHistoryConfirm') }}
</NPopconfirm>
<div class="flex flex-wrap items-center gap-4">
<NButton size="small" @click="exportData">
<template #icon>
<SvgIcon icon="ri:download-2-fill" />
</template>
{{ $t('common.export') }}
</NButton>

<input id="fileInput" type="file" style="display:none" @change="importData">
<NButton size="small" @click="handleImportButtonClick">
<template #icon>
<SvgIcon icon="ri:upload-2-fill" />
</template>
{{ $t('common.import') }}
</NButton>

<NPopconfirm placement="bottom" @positive-click="clearData">
<template #trigger>
<NButton size="small">
<template #icon>
<SvgIcon icon="ri:close-circle-line" />
</template>
{{ $t('common.clear') }}
</NButton>
</template>
{{ $t('chat.clearHistoryConfirm') }}
</NPopconfirm>
</div>
</div>
<div class="flex items-center space-x-4">
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.theme') }}</span>
<div class="flex items-center space-x-4">
<div class="flex flex-wrap items-center gap-4">
<template v-for="item of themeOptions" :key="item.key">
<NButton
size="small"
:type="item.key === theme ? 'primary' : undefined"
@click="appStore.setTheme(item.key)"
>
Expand All @@ -195,9 +198,10 @@ function handleImportButtonClick(): void {
</div>
<div class="flex items-center space-x-4">
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.language') }}</span>
<div class="flex items-center space-x-4">
<div class="flex flex-wrap items-center gap-4">
<template v-for="item of languageOptions" :key="item.key">
<NButton
size="small"
:type="item.key === language ? 'primary' : undefined"
@click="appStore.setLanguage(item.key)"
>
Expand All @@ -208,7 +212,7 @@ function handleImportButtonClick(): void {
</div>
<div class="flex items-center space-x-4">
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.resetUserInfo') }}</span>
<NButton @click="handleReset">
<NButton size="small" @click="handleReset">
{{ $t('common.reset') }}
</NButton>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/components/common/Setting/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const show = computed({

<template>
<NModal v-model:show="show" :auto-focus="false">
<NCard role="dialog" aria-modal="true" :bordered="false" style="width: 100%; max-width: 640px">
<NCard role="dialog" aria-modal="true" :bordered="false" style="width: 95%; max-width: 640px">
<NTabs v-model:value="active" type="line" animated>
<NTabPane name="General" tab="General">
<template #tab>
Expand Down
2 changes: 1 addition & 1 deletion src/locales/zh-CN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default {
unauthorizedTips: '未经授权,请先进行验证。',
},
chat: {
placeholder: '来说点什么...(Shift + Enter = 换行)',
placeholder: '来说点什么吧...(Shift + Enter = 换行)',
placeholderMobile: '来说点什么...',
copy: '复制',
copied: '复制成功',
Expand Down
Loading