66 * 発行した API キーは環境変数 GOOGLE_API_KEY に設定してください。
77 */
88
9- import { GoogleGenerativeAI } from '@google/generative-ai' ;
10- import { GoogleAIFileManager } from '@google/generative-ai/server' ;
9+ import { GoogleGenAI } from '@google/genai' ;
1110import { setTimeout } from 'node:timers/promises' ;
1211import { renderMarkdown , splitMarkdown } from './markdown' ;
1312
1413export class GeminiTranslator {
15- readonly #genAI: GoogleGenerativeAI ;
16- readonly #fileManager: GoogleAIFileManager ;
14+ readonly #client: GoogleGenAI ;
1715
1816 constructor ( apiKey : string ) {
19- this . #genAI = new GoogleGenerativeAI ( apiKey ) ;
20- this . #fileManager = new GoogleAIFileManager ( apiKey ) ;
17+ this . #client = new GoogleGenAI ( { apiKey } ) ;
2118 }
2219
2320 async translate ( content : string , prh : string ) : Promise < string > {
@@ -30,7 +27,6 @@ ${content}
3027あなたはこのMarkdownファイルを段落ごとに分割したテキストを受け取ります。
3128次のルールに従って、受け取ったテキストを翻訳してください。
3229
33- - 入出力の形式 入力: { text: "## Hello" } 出力: { text: "## こんにちは" }
3430- 見出しのレベルを維持する。
3531- 改行やインデントの数を維持する。
3632- 英単語の前後にスペースを入れない。
@@ -43,32 +39,32 @@ ${prh}
4339
4440` . trim ( ) ;
4541
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-
5742 const blocks = splitMarkdown ( content ) ;
5843 const translated = [ ] ;
5944
6045 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 ,
6758 } ,
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
7268 }
7369 return renderMarkdown ( translated ) ;
7470 }
0 commit comments