1
1
use crate :: config:: AppConfig ;
2
- use chat_gpt_rs:: prelude:: * ;
3
2
use dotenv:: dotenv;
3
+ use std:: error:: Error ;
4
4
use std:: fs:: File ;
5
5
use std:: time:: Duration ;
6
6
use std:: { env, thread} ;
7
7
use tokio:: time:: timeout;
8
+ use openai_api_rs:: v1:: api:: Client ;
9
+ use openai_api_rs:: v1:: chat_completion:: { self , ChatCompletionRequest } ;
10
+ use openai_api_rs:: v1:: common:: GPT3_5_TURBO ;
8
11
9
- pub async fn get_reply < ' a > ( personality : & ' a str , user_text : & ' a str , has_mention : bool ) -> Result < String > {
12
+
13
+ pub async fn call_gpt ( prompt : & str , user_text : & str ) -> Result < String , Box < dyn Error > > {
14
+ dotenv ( ) . ok ( ) ;
15
+ let api_key = env:: var ( "OPEN_AI_API_KEY" ) . expect ( "OPEN_AI_API_KEY is not set" ) ;
16
+ let client = Client :: new ( api_key) ;
17
+ let req = ChatCompletionRequest :: new (
18
+ GPT3_5_TURBO . to_string ( ) ,
19
+ vec ! [
20
+ chat_completion:: ChatCompletionMessage {
21
+ role: chat_completion:: MessageRole :: system,
22
+ content: chat_completion:: Content :: Text ( String :: from( prompt) ) ,
23
+ name: None ,
24
+ } ,
25
+ chat_completion:: ChatCompletionMessage {
26
+ role: chat_completion:: MessageRole :: user,
27
+ content: chat_completion:: Content :: Text ( String :: from( user_text) ) ,
28
+ name: None ,
29
+ } ,
30
+ ] ,
31
+ )
32
+ . presence_penalty ( -0.5 )
33
+ . frequency_penalty ( 0.0 )
34
+ . top_p ( 0.9 ) ;
35
+
36
+ let chat_completion_future = async {
37
+ client. chat_completion ( req)
38
+ } ;
39
+
40
+ // タイムアウトを設定
41
+ match timeout ( Duration :: from_secs ( 30 ) , chat_completion_future) . await {
42
+ Ok ( result) => match result {
43
+ Ok ( response) => {
44
+ // 正常なレスポンスの処理
45
+ match & response. choices [ 0 ] . message . content {
46
+ Some ( content) => Ok ( content. to_string ( ) ) ,
47
+ None => Err ( "No content found in response" . into ( ) ) , // 適切なエラーメッセージを返す
48
+ }
49
+ } ,
50
+ Err ( e) => Err ( e. into ( ) ) , // APIErrorをBox<dyn Error>に変換
51
+ } ,
52
+ Err ( _) => Err ( "Timeout after 30 seconds" . into ( ) ) ,
53
+ }
54
+ }
55
+
56
+ pub async fn get_reply < ' a > ( personality : & ' a str , user_text : & ' a str , has_mention : bool ) -> Result < String , Box < dyn Error > > {
10
57
dotenv ( ) . ok ( ) ;
11
58
let file = File :: open ( "../config.yml" ) . unwrap ( ) ;
12
59
let config: AppConfig = serde_yaml:: from_reader ( file) . unwrap ( ) ;
13
60
let answer_length = config. gpt . answer_length ;
14
- let api_key = env:: var ( "OPEN_AI_API_KEY" ) . expect ( "OPEN_AI_API_KEY is not set" ) ;
15
-
16
- let token = Token :: new ( & api_key) ;
17
- let api = Api :: new ( token) ;
18
61
19
62
let start_delimiter = "<<" ;
20
63
let end_delimiter = ">>" ;
@@ -41,117 +84,19 @@ pub async fn get_reply<'a>(personality: &'a str, user_text: &'a str, has_mention
41
84
prompt_temp = format ! ( "これはあなたの人格です。'{personality}'\n この人格を演じて次の行の文章に対して{answer_length}文字程度で返信してください。" ) ;
42
85
}
43
86
if !has_mention {
44
- prompt = format ! ( "{prompt_temp}次の行の文章はSNSでの投稿です。あなたがたまたま見かけたものであなた宛の文章ではないのでその点に注意して解凍してください 。" )
87
+ prompt = format ! ( "{prompt_temp}次の行の文章はSNSでの投稿です。あなたがたまたま見かけたものであなた宛の文章ではないのでその点に注意して回答してください 。" )
45
88
} else {
46
89
prompt = prompt_temp
47
90
}
48
91
49
- let request = Request {
50
- model : Model :: Gpt35Turbo ,
51
- messages : vec ! [
52
- Message {
53
- role: "system" . to_string( ) ,
54
- content: prompt,
55
- } ,
56
- Message {
57
- role: "user" . to_string( ) ,
58
- content: user_text. to_string( ) ,
59
- } ,
60
- ] ,
61
- presence_penalty : Some ( -0.5 ) ,
62
- frequency_penalty : Some ( 0.0 ) ,
63
- top_p : Some ( 0.9 ) ,
64
-
65
- ..Default :: default ( )
66
- } ;
67
- // let response = api.chat(request).await?;
68
- let reply;
69
- let result = timeout ( Duration :: from_secs ( 30 ) , api. chat ( request) ) . await ;
70
- match result {
71
- Ok ( response) => {
72
- // 非同期処理が完了した場合の処理
73
- reply = response. unwrap ( ) . choices [ 0 ] . message . content . clone ( ) ;
74
- println ! ( "{:?}" , reply) ;
92
+ match call_gpt ( & prompt, & user_text. to_string ( ) ) . await {
93
+ Ok ( reply) => {
94
+ println ! ( "Reply: {}" , reply) ;
75
95
Ok ( reply)
76
- }
77
- Err ( _) => {
78
- eprintln ! ( "**********Timeout occurred while calling api.chat" ) ;
79
- reply = "" . to_string ( ) ;
80
- Ok ( reply)
81
- }
82
- }
83
- }
84
-
85
- use regex:: Regex ;
86
-
87
- fn split_text ( text : & str , max_length : usize ) -> Vec < String > {
88
- let re = Regex :: new ( r"[^。\n]*[。\n]" ) . unwrap ( ) ;
89
- let sentences: Vec < & str > = re. find_iter ( text) . map ( |m| m. as_str ( ) ) . collect ( ) ;
90
-
91
- let mut result = Vec :: new ( ) ;
92
- let mut current = String :: new ( ) ;
93
- for sentence in sentences {
94
- if current. len ( ) + sentence. len ( ) > max_length {
95
- result. push ( current. trim ( ) . to_string ( ) ) ;
96
- current. clear ( ) ;
97
- }
98
- current += sentence;
99
- }
100
- if !current. is_empty ( ) {
101
- result. push ( current. trim ( ) . to_string ( ) ) ;
102
- }
103
- result
104
- }
105
-
106
- pub async fn get_summary < ' a > ( text : & ' a str ) -> Result < String > {
107
- dotenv ( ) . ok ( ) ;
108
- let api_key = env:: var ( "OPEN_AI_API_KEY" ) . expect ( "OPEN_AI_API_KEY is not set" ) ;
109
-
110
- let token = Token :: new ( & api_key) ;
111
- let api = Api :: new ( token) ;
112
-
113
- let prompt = format ! (
114
- "あなたは優秀な新聞記者のお嬢様です。次の文章を読んで要約しお嬢様のような口調で日本語で10行にまとめてください。行頭には必ず'・'を入れて行末には必ず改行を入れてください。"
115
- ) ;
116
-
117
- let mut summary = String :: from ( "" ) ;
118
- let split_texts = split_text ( text, 2048 ) ;
119
- for _text in split_texts {
120
- loop {
121
- let request = Request {
122
- model : Model :: Gpt35Turbo ,
123
- messages : vec ! [
124
- Message {
125
- role: "system" . to_string( ) ,
126
- content: prompt. clone( ) ,
127
- } ,
128
- Message {
129
- role: "user" . to_string( ) ,
130
- content: _text. to_string( ) ,
131
- } ,
132
- ] ,
133
- presence_penalty : Some ( -0.5 ) ,
134
- frequency_penalty : Some ( 0.0 ) ,
135
- top_p : Some ( 0.9 ) ,
136
-
137
- ..Default :: default ( )
138
- } ;
139
- let result = timeout ( Duration :: from_secs ( 30 ) , api. chat ( request) ) . await ;
140
- match result {
141
- Ok ( response) => {
142
- // 非同期処理が完了した場合の処理
143
- let _summary = response. unwrap ( ) . choices [ 0 ] . message . content . clone ( ) ;
144
- summary = format ! ( "{}{}" , summary, _summary) ;
145
- println ! ( "summary:{}:{}" , summary. len( ) , summary) ;
146
- break ;
147
- }
148
- Err ( _) => {
149
- eprintln ! ( "**********Timeout occurred while calling api.chat" ) ;
150
- thread:: sleep ( Duration :: from_secs ( 3 ) ) ;
151
- }
152
- }
153
- }
96
+ } ,
97
+ Err ( e) => {
98
+ println ! ( "Error: {}" , e) ;
99
+ Ok ( "" . to_string ( ) )
100
+ } ,
154
101
}
155
- summary = summary. replace ( "。・" , "\n ・" ) ;
156
- Ok ( summary)
157
102
}
0 commit comments