11import React , { useEffect , useState } from "react" ;
22import { getLatestState } from "~utils/state" ;
33import { ChatMessage , ChatMessageContext } from "~provider/chat" ;
4+ import { SettingContext } from "~provider/setting" ;
45
56const ChatUserMessage = ( props ) => {
67 const { chatScrollRef } = React . useContext ( ChatMessageContext ) ;
@@ -25,6 +26,7 @@ const ChatUserMessage = (props) => {
2526
2627const ChatAssistantMessage = ( props ) => {
2728 const [ message , setMessage ] = useState ( "" ) ;
29+ const { settingObject : { openaiKey } } = React . useContext ( SettingContext ) ;
2830 const { messages, setMessages, chatScrollRef, isLoading, setIsLoading } = React . useContext ( ChatMessageContext ) ;
2931
3032 useEffect ( ( ) => {
@@ -38,7 +40,7 @@ const ChatAssistantMessage = (props) => {
3840 function handleMessages ( ) {
3941 const threshold = 4096 - 512 ;
4042
41- let limitMessages = [ ]
43+ let limitMessages = [ ] ;
4244 let currentLength = 0 ;
4345
4446 for ( let i = messages . length - 1 ; i >= 1 ; i -- ) {
@@ -55,9 +57,10 @@ const ChatAssistantMessage = (props) => {
5557 }
5658
5759 const callOpenAI = function ( ) {
60+ // check openaiKey
5861 const myHeaders = new Headers ( ) ;
5962 myHeaders . append ( "Content-Type" , "application/json" ) ;
60- myHeaders . append ( "Authorization" , " Bearer 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" ) ;
63+ myHeaders . append ( "Authorization" , ` Bearer ${ openaiKey } ` ) ;
6164
6265 const raw = JSON . stringify ( {
6366 "model" : "gpt-3.5-turbo-0301" ,
@@ -78,7 +81,13 @@ const ChatAssistantMessage = (props) => {
7881 const stream = response . body ;
7982 const reader = stream . getReader ( ) ;
8083
81- // read from the stream
84+ if ( ! response . ok ) {
85+ setMessage ( "请检查 API Key 是否正确,「Settings -> OpenAI Key`」" ) ;
86+ setIsLoading ( false ) ;
87+
88+ return
89+ }
90+
8291 function readStream ( ) {
8392 reader . read ( ) . then ( async ( { done, value } ) => {
8493 if ( done ) {
@@ -130,11 +139,6 @@ const ChatAssistantMessage = (props) => {
130139 }
131140
132141 readStream ( ) ;
133-
134- } )
135- . catch ( error => {
136- setIsLoading ( false ) ;
137- console . log ( "error" , error ) ;
138142 } ) ;
139143
140144 } ;
0 commit comments