Coverage for src/refinire/core/gemini.py: 80%

20 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-15 18:51 +0900

1""" 

2Gemini model implementation for OpenAI Agents 

3OpenAI AgentsのためのGeminiモデル実装 

4""" 

5import os 

6from typing import Any, Dict, List, Optional, Union 

7from agents.models.openai_chatcompletions import OpenAIChatCompletionsModel 

8from openai import AsyncOpenAI 

9 

10 

11class GeminiModel(OpenAIChatCompletionsModel): 

12 """ 

13 Gemini model implementation that extends OpenAI's chat completions model 

14 OpenAIのチャット補完モデルを拡張したGeminiモデルの実装 

15 """ 

16 

17 def __init__( 

18 self, 

19 model: str = "gemini-2.0-flash", 

20 temperature: float = 0.3, 

21 api_key: str = None, 

22 base_url: str = "https://generativelanguage.googleapis.com/v1beta/openai/", 

23 **kwargs: Any, 

24 ) -> None: 

25 """ 

26 Initialize the Gemini model with OpenAI compatible interface 

27 OpenAI互換インターフェースでGeminiモデルを初期化する 

28 

29 Args: 

30 model (str): Name of the Gemini model to use (e.g. "gemini-2.0-flash") 

31 使用するGeminiモデルの名前(例:"gemini-2.0-flash") 

32 temperature (float): Sampling temperature between 0 and 1 

33 サンプリング温度(0から1の間) 

34 api_key (str): Gemini API key 

35 Gemini APIキー 

36 base_url (str): Base URL for the Gemini API 

37 Gemini APIのベースURL 

38 **kwargs: Additional arguments to pass to the OpenAI API 

39 OpenAI APIに渡す追加の引数 

40 """ 

41 if base_url == None: 

42 base_url = "https://generativelanguage.googleapis.com/v1beta/openai/" 

43 

44 # api_key が None の場合は環境変数から取得 

45 if api_key is None: 

46 api_key = os.environ.get("GOOGLE_API_KEY") 

47 if api_key is None: 

48 raise ValueError("Google API key is required. Get one from https://ai.google.dev/") 

49 

50 # Create AsyncOpenAI client with Gemini base URL 

51 # GeminiのベースURLでAsyncOpenAIクライアントを作成 

52 openai_client = AsyncOpenAI(base_url=base_url, api_key=api_key) 

53 

54 # Store parameters for later use in API calls 

55 # 後でAPIコールで使用するためにパラメータを保存 

56 self.temperature = temperature 

57 self.kwargs = kwargs 

58 

59 # Initialize the parent class with our custom client 

60 # カスタムクライアントで親クラスを初期化 

61 super().__init__( 

62 model=model, 

63 openai_client=openai_client 

64 ) 

65 

66 # Override methods that make API calls to include our parameters 

67 # APIコールを行うメソッドをオーバーライドして、パラメータを含める 

68 async def _create_chat_completion(self, *args, **kwargs): 

69 """Override to include temperature and other parameters""" 

70 kwargs["temperature"] = self.temperature 

71 kwargs.update(self.kwargs) 

72 return await super()._create_chat_completion(*args, **kwargs)