6
6
* 発行した API キーは環境変数 GOOGLE_API_KEY に設定してください。
7
7
*/
8
8
9
- import { GoogleGenerativeAI } from '@google/generative-ai' ;
10
- import { GoogleAIFileManager } from '@google/generative-ai/server' ;
9
+ import { GoogleGenAI } from '@google/genai' ;
11
10
import { setTimeout } from 'node:timers/promises' ;
12
11
import { renderMarkdown , splitMarkdown } from './markdown' ;
13
12
14
13
export class GeminiTranslator {
15
- readonly #genAI: GoogleGenerativeAI ;
16
- readonly #fileManager: GoogleAIFileManager ;
14
+ readonly #client: GoogleGenAI ;
17
15
18
16
constructor ( apiKey : string ) {
19
- this . #genAI = new GoogleGenerativeAI ( apiKey ) ;
20
- this . #fileManager = new GoogleAIFileManager ( apiKey ) ;
17
+ this . #client = new GoogleGenAI ( { apiKey } ) ;
21
18
}
22
19
23
20
async translate ( content : string , prh : string ) : Promise < string > {
@@ -30,7 +27,6 @@ ${content}
30
27
あなたはこのMarkdownファイルを段落ごとに分割したテキストを受け取ります。
31
28
次のルールに従って、受け取ったテキストを翻訳してください。
32
29
33
- - 入出力の形式 入力: { text: "## Hello" } 出力: { text: "## こんにちは" }
34
30
- 見出しのレベルを維持する。
35
31
- 改行やインデントの数を維持する。
36
32
- 英単語の前後にスペースを入れない。
@@ -43,32 +39,32 @@ ${prh}
43
39
44
40
` . trim ( ) ;
45
41
46
- const model = this . #genAI. getGenerativeModel ( {
47
- model : 'gemini-2.0-flash' ,
48
- generationConfig : {
49
- responseMimeType : 'application/json' ,
50
- temperature : 0.2 ,
51
- } ,
52
- systemInstruction,
53
- } ) ;
54
-
55
- const chatSession = model . startChat ( { } ) ;
56
-
57
42
const blocks = splitMarkdown ( content ) ;
58
43
const translated = [ ] ;
59
44
60
45
for ( const block of blocks ) {
61
- const { response } = await chatSession . sendMessage ( [
62
- {
63
- text : '次のテキストに含まれる英語を日本語に翻訳してください。\n\n' ,
64
- } ,
65
- {
66
- text : JSON . stringify ( { text : block } ) ,
46
+ const prompt = `
47
+ 次のテキストに含まれる英語を日本語に翻訳してください。
48
+
49
+ ${ block }
50
+ ` . trim ( ) ;
51
+
52
+ const response = await this . #client. models . generateContent ( {
53
+ model : 'gemini-2.0-flash' ,
54
+ contents : [ prompt ] ,
55
+ config : {
56
+ systemInstruction,
57
+ temperature : 0.1 ,
67
58
} ,
68
- ] ) ;
69
- const { text : translatedText } = JSON . parse ( response . text ( ) ) ;
70
- translated . push ( translatedText ) ;
71
- await setTimeout ( 3000 ) ;
59
+ } ) ;
60
+
61
+ if ( response . text ) {
62
+ translated . push ( response . text ) ;
63
+ } else {
64
+ translated . push ( '' ) ; // Fallback in case of no response
65
+ }
66
+
67
+ await setTimeout ( 3000 ) ; // Rate limiting
72
68
}
73
69
return renderMarkdown ( translated ) ;
74
70
}
0 commit comments