Skip to content

Commit

Permalink
feat: add account balance request, #37
Browse files Browse the repository at this point in the history
  • Loading branch information
orangelckc committed Mar 21, 2023
1 parent 41852bb commit 30f9660
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 24 deletions.
2 changes: 1 addition & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
VITE_CONFIG_PATH=com.ChatGPT-Desktop
VITE_APP_NAME=ChatGPT
VITE_OPEN_AI_URL=https://api.openai.com/v1/chat/completions
VITE_OPEN_AI_URL=https://api.openai.com
VITE_OPEN_AI_API_KEY=
3 changes: 2 additions & 1 deletion .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ module.exports = {
plugins: ['vue', '@typescript-eslint', 'prettier'],
rules: {
'vue/multi-word-component-names': 'off',
'@typescript-eslint/no-explicit-any': 'off'
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-non-null-assertion': 'off'
}
}
59 changes: 44 additions & 15 deletions src/api/openAi.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Body } from '@tauri-apps/api/http'
import { Message } from '@arco-design/web-vue'
import { request } from '.'
import { OPEN_AI_MODEL } from '@/constants'
import { OPENAI_CHAT_URL, OPEN_AI_MODEL, OPENAI_CREDIT_URL } from '@/constants'
import {
fetchEventSource,
type EventSourceMessage
Expand All @@ -17,16 +17,17 @@ import type { MessageData, SessionData } from '@/types'
export const getOpenAIResultApi = async (messages: MessageData[]) => {
if (!messages.length) return

const { apiKey } = useSettingsStore()
const apiKey = getOpenAIKey()
if (!apiKey) return

return await request(import.meta.env.VITE_OPEN_AI_URL, {
return await request(OPENAI_CHAT_URL, {
method: 'POST',
body: Body.json({
model: OPEN_AI_MODEL,
messages
}),
headers: {
Authorization: `Bearer ${apiKey || import.meta.env.VITE_OPEN_AI_API_KEY}`
Authorization: `Bearer ${apiKey}`
}
})
}
Expand All @@ -38,11 +39,13 @@ export const getOpenAIResultApi = async (messages: MessageData[]) => {
export const getOpenAIResultStreamApi = async (messages: MessageData[]) => {
if (!messages.length) return

const { apiKey } = useSettingsStore()
const apiKey = getOpenAIKey()
if (!apiKey) return

const { updateSessionData } = useSessionStore()
const { sessionDataList } = storeToRefs(useSessionStore())

await fetchEventSource(import.meta.env.VITE_OPEN_AI_URL, {
await fetchEventSource(OPENAI_CHAT_URL, {
method: 'POST',
body: JSON.stringify({
model: OPEN_AI_MODEL,
Expand All @@ -51,7 +54,7 @@ export const getOpenAIResultStreamApi = async (messages: MessageData[]) => {
stream: true
}),
headers: {
Authorization: `Bearer ${apiKey || import.meta.env.VITE_OPEN_AI_API_KEY}`,
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
Accept: 'application/json'
},
Expand Down Expand Up @@ -85,18 +88,26 @@ export const getOpenAIResultStreamApi = async (messages: MessageData[]) => {
})
}

/**
* 获取账号余额信息
*/
export const getOpenAICreditApi = async () => {
const apiKey = getOpenAIKey()
if (!apiKey) return

return await request(OPENAI_CREDIT_URL, {
method: 'GET',
headers: {
Authorization: `Bearer ${apiKey}`
}
})
}

/**
* 获取 ai 回答
* @param value 消息内容
*/
export const getAiMessage = async (value?: string) => {
const { apiKey } = useSettingsStore()

if (!apiKey && !import.meta.env.VITE_OPEN_AI_API_KEY) {
Message.warning('请先填写 OpenAi API Key')
return
}

const { isThinking, sessionDataList } = storeToRefs(useSessionStore())
const { updateSessionData } = useSessionStore()

Expand All @@ -105,6 +116,10 @@ export const getAiMessage = async (value?: string) => {

if (!currentRole) return

// 检测是否有余额
const credit = await getOpenAICreditApi()
if (!credit) return

const messages: MessageData[] = []

const { currentSession, sessionDataList } = useSessionStore()
Expand Down Expand Up @@ -178,10 +193,24 @@ export const getAiMessage = async (value?: string) => {

isThinking.value = false
} catch ({ message }: any) {
sessionDataList.value.at(-1)!.message.content = message
sessionDataList.value.at(-1)!.message.content = message as any

updateSessionData(sessionDataList.value.at(-1)!)

isThinking.value = false
}
}

/**
* 获取apiKey
*/
const getOpenAIKey = () => {
const { apiKey } = useSettingsStore()

if (!apiKey && !import.meta.env.VITE_OPEN_AI_API_KEY) {
Message.warning('请先填写 OpenAi API Key')
return false
}

return apiKey || import.meta.env.VITE_OPEN_AI_API_KEY
}
9 changes: 3 additions & 6 deletions src/api/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,16 @@ export const request = async (url: string, options?: FetchOptions) => {
timeout: 1000 * 60,
headers: {
...headers,
'Content-Type': 'application/json',
'user-agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'
}
})

const { error, usage, choices } = data

const { error } = data
if (error) throw new Error(error.message)

return {
usage,
message: choices[0].message
}
return data
} catch (error: any) {
dialogErrorMessage('请求出错:' + error.message)
}
Expand Down
27 changes: 26 additions & 1 deletion src/components/Function/components/SettingsModal.vue
Original file line number Diff line number Diff line change
@@ -1,12 +1,34 @@
<script setup lang="ts">
import { useSettingsStore } from '@/stores'
import ShortcutKey from './ShortcutKey.vue'
import { getOpenAICreditApi } from '@/api'
defineProps<{ visible: boolean; setVisible: () => void }>()
const props = defineProps<{ visible: boolean; setVisible: () => void }>()
const { apiKey, autoStart, isMemory, isRememberPosition } = storeToRefs(
useSettingsStore()
)
const totalCredit = ref(0)
const usedCredit = ref(0)
const getCredit = async () => {
const credit = await getOpenAICreditApi()
if (!credit) return
totalCredit.value = parseFloat(credit.total_granted.toFixed(2))
usedCredit.value = parseFloat(credit.total_available.toFixed(2))
}
// TODO 优化,这里可能需要防抖
watch(apiKey, getCredit)
watch(
() => props.visible,
(val) => {
val && getCredit()
}
)
</script>

<template>
Expand Down Expand Up @@ -43,6 +65,9 @@ const { apiKey, autoStart, isMemory, isRememberPosition } = storeToRefs(
placeholder="API Key"
allow-clear
/>
<p class="text-3 text-right text-[var(--color-text-3)]" v-if="apiKey">
账户余额&dollar; {{ usedCredit }} / {{ totalCredit }}
</p>
</div>
</a-modal>
</template>
8 changes: 8 additions & 0 deletions src/constants/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,11 @@ export enum DEFAULT_ROLE {
export const DEFAULT_SHORTCUT_KEY = ['Alt', 'X']

export const OPEN_AI_MODEL = 'gpt-3.5-turbo-0301'

export const OPENAI_CHAT_URL = `${
import.meta.env.VITE_OPEN_AI_URL
}/v1/chat/completions`

export const OPENAI_CREDIT_URL = `${
import.meta.env.VITE_OPEN_AI_URL
}/dashboard/billing/credit_grants`

0 comments on commit 30f9660

Please sign in to comment.