@@ -127,6 +127,20 @@ export default function ChatBOX(props: {
127127 ( models [ data . model ] ?. price ?. completion ?? 0 ) ;
128128 }
129129 const content = client . processFetchResponse ( data ) ;
130+
131+ // estimate user's input message token
132+ let aboveToken = 0 ;
133+ for ( const msg of chatStore . history
134+ . filter ( ( { hide } ) => ! hide )
135+ . slice ( chatStore . postBeginIndex , - 1 ) ) {
136+ aboveToken += msg . token ;
137+ }
138+ if ( data . usage . prompt_tokens ) {
139+ const userMessageToken = data . usage . prompt_tokens - aboveToken ;
140+ console . log ( "set user message token" ) ;
141+ chatStore . history . slice ( - 1 ) [ 0 ] . token = userMessageToken ;
142+ }
143+
130144 chatStore . history . push ( {
131145 role : "assistant" ,
132146 content,
@@ -143,9 +157,9 @@ export default function ChatBOX(props: {
143157 client . sysMessageContent = chatStore . systemMessageContent ;
144158 client . tokens_margin = chatStore . tokenMargin ;
145159 client . messages = chatStore . history
146- . slice ( chatStore . postBeginIndex )
147160 // only copy non hidden message
148161 . filter ( ( { hide } ) => ! hide )
162+ . slice ( chatStore . postBeginIndex )
149163 // only copy content and role attribute to client for posting
150164 . map ( ( { content, role } ) => {
151165 return {
@@ -156,20 +170,6 @@ export default function ChatBOX(props: {
156170 client . model = chatStore . model ;
157171 client . max_tokens = chatStore . maxTokens ;
158172
159- // todo move code
160- const max = chatStore . maxTokens - chatStore . tokenMargin ;
161- let sum = 0 ;
162- chatStore . postBeginIndex = chatStore . history . filter (
163- ( { hide } ) => ! hide
164- ) . length ;
165- for ( const msg of chatStore . history . slice ( ) . reverse ( ) ) {
166- sum += msg . token ;
167- if ( sum > max ) break ;
168- chatStore . postBeginIndex -= 1 ;
169- }
170- chatStore . postBeginIndex =
171- chatStore . postBeginIndex < 0 ? 0 : chatStore . postBeginIndex ;
172-
173173 try {
174174 setShowGenerating ( true ) ;
175175 const response = await client . _fetch ( chatStore . streamMode ) ;
@@ -186,20 +186,6 @@ export default function ChatBOX(props: {
186186 chatStore . tokenMargin = client . tokens_margin ;
187187 chatStore . totalTokens = client . total_tokens ;
188188
189- // todo move code
190- const max = chatStore . maxTokens - chatStore . tokenMargin ;
191- let sum = 0 ;
192- chatStore . postBeginIndex = chatStore . history . filter (
193- ( { hide } ) => ! hide
194- ) . length ;
195- for ( const msg of chatStore . history . slice ( ) . reverse ( ) ) {
196- sum += msg . token ;
197- if ( sum > max ) break ;
198- chatStore . postBeginIndex -= 1 ;
199- }
200- chatStore . postBeginIndex =
201- chatStore . postBeginIndex < 0 ? 0 : chatStore . postBeginIndex ;
202-
203189 console . log ( "postBeginIndex" , chatStore . postBeginIndex ) ;
204190 setChatStore ( { ...chatStore } ) ;
205191 } catch ( error ) {
0 commit comments