1+ import { AiClient } from "../core/AiClient.ts" ;
2+ import { AiMessageListener } from "../core/AiMessageListener.ts" ;
3+ import { AiModel } from "../core/AiModel.ts" ;
4+ import { AiGlobalConfig } from "../AiGlobalConfig.ts" ;
5+ import { SseClient } from "../core/client/sse/SseClient.ts" ;
6+ import { InnerEditor } from "../../core/AiEditor.ts" ;
7+ import { GiteeModelConfig } from "./GiteeModelConfig.ts" ;
8+
9+
10+ export class GiteeAiModel extends AiModel {
11+
12+ constructor ( editor : InnerEditor , globalConfig : AiGlobalConfig ) {
13+ super ( editor , globalConfig , "gitee" ) ;
14+ this . aiModelConfig = {
15+ max_tokens : 512 ,
16+ temperature : 0.7 ,
17+ top_p : 0.7 ,
18+ top_k : 50 ,
19+ ...globalConfig . models [ "gitee" ]
20+ } as GiteeModelConfig ;
21+ }
22+
23+ createAiClient ( url : string , listener : AiMessageListener ) : AiClient {
24+ const config = this . aiModelConfig as GiteeModelConfig ;
25+ return new SseClient ( {
26+ url,
27+ method : "post" ,
28+ headers : {
29+ "Content-Type" : "application/json" ,
30+ "Authorization" : `Bearer ${ config . apiKey } ` ,
31+ }
32+ } , {
33+ onStart : listener . onStart ,
34+ onStop : listener . onStop ,
35+ onMessage : ( bodyString : string ) => {
36+ console . log ( "onMessage: " , bodyString )
37+
38+ const message = JSON . parse ( bodyString ) as any ;
39+
40+ listener . onMessage ( {
41+ status : message . choices [ 0 ] . finish_reason === "stop" ? 2 : 1 ,
42+ role : "assistant" ,
43+ content : message . choices [ 0 ] . delta ?. content || "" ,
44+ index : message . choices [ 0 ] . index ,
45+ } )
46+ //通知 ai 消费情况
47+ if ( this . globalConfig . onTokenConsume && message . usage ?. [ "total_tokens" ] ) {
48+ this . globalConfig . onTokenConsume ( this . aiModelName , this . aiModelConfig ! , message . usage [ "total_tokens" ] )
49+ }
50+ }
51+ } ) ;
52+ }
53+
54+ wrapPayload ( prompt : string ) {
55+ const config = this . aiModelConfig as GiteeModelConfig ;
56+ const payload = {
57+ "messages" : [
58+ {
59+ "role" : "user" ,
60+ "content" : prompt ,
61+ }
62+ ] ,
63+ stream : true ,
64+ max_tokens : config . max_tokens ,
65+ temperature : config . temperature ,
66+ top_p : config . top_p ,
67+ top_k : config . top_k ,
68+ }
69+ return JSON . stringify ( payload ) ;
70+ }
71+
72+ createAiClientUrl ( ) : string {
73+ const { endpoint} = this . aiModelConfig as GiteeModelConfig ;
74+ return endpoint ;
75+ }
76+
77+
78+ }
0 commit comments