google.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. from collections.abc import Generator
  2. import google.generativeai.types.content_types as content_types
  3. import google.generativeai.types.generation_types as generation_config_types
  4. import google.generativeai.types.safety_types as safety_types
  5. import pytest
  6. from _pytest.monkeypatch import MonkeyPatch
  7. from google.ai import generativelanguage as glm
  8. from google.ai.generativelanguage_v1beta.types import content as gag_content
  9. from google.generativeai import GenerativeModel
  10. from google.generativeai.client import _ClientManager, configure
  11. from google.generativeai.types import GenerateContentResponse
  12. from google.generativeai.types.generation_types import BaseGenerateContentResponse
  13. current_api_key = ""
  14. class MockGoogleResponseClass:
  15. _done = False
  16. def __iter__(self):
  17. full_response_text = "it's google!"
  18. for i in range(0, len(full_response_text) + 1, 1):
  19. if i == len(full_response_text):
  20. self._done = True
  21. yield GenerateContentResponse(
  22. done=True, iterator=None, result=glm.GenerateContentResponse({}), chunks=[]
  23. )
  24. else:
  25. yield GenerateContentResponse(
  26. done=False, iterator=None, result=glm.GenerateContentResponse({}), chunks=[]
  27. )
  28. class MockGoogleResponseCandidateClass:
  29. finish_reason = "stop"
  30. @property
  31. def content(self) -> gag_content.Content:
  32. return gag_content.Content(parts=[gag_content.Part(text="it's google!")])
  33. class MockGoogleClass:
  34. @staticmethod
  35. def generate_content_sync() -> GenerateContentResponse:
  36. return GenerateContentResponse(done=True, iterator=None, result=glm.GenerateContentResponse({}), chunks=[])
  37. @staticmethod
  38. def generate_content_stream() -> Generator[GenerateContentResponse, None, None]:
  39. return MockGoogleResponseClass()
  40. def generate_content(
  41. self: GenerativeModel,
  42. contents: content_types.ContentsType,
  43. *,
  44. generation_config: generation_config_types.GenerationConfigType | None = None,
  45. safety_settings: safety_types.SafetySettingOptions | None = None,
  46. stream: bool = False,
  47. **kwargs,
  48. ) -> GenerateContentResponse:
  49. global current_api_key
  50. if len(current_api_key) < 16:
  51. raise Exception("Invalid API key")
  52. if stream:
  53. return MockGoogleClass.generate_content_stream()
  54. return MockGoogleClass.generate_content_sync()
  55. @property
  56. def generative_response_text(self) -> str:
  57. return "it's google!"
  58. @property
  59. def generative_response_candidates(self) -> list[MockGoogleResponseCandidateClass]:
  60. return [MockGoogleResponseCandidateClass()]
  61. def make_client(self: _ClientManager, name: str):
  62. global current_api_key
  63. if name.endswith("_async"):
  64. name = name.split("_")[0]
  65. cls = getattr(glm, name.title() + "ServiceAsyncClient")
  66. else:
  67. cls = getattr(glm, name.title() + "ServiceClient")
  68. # Attempt to configure using defaults.
  69. if not self.client_config:
  70. configure()
  71. client_options = self.client_config.get("client_options", None)
  72. if client_options:
  73. current_api_key = client_options.api_key
  74. def nop(self, *args, **kwargs):
  75. pass
  76. original_init = cls.__init__
  77. cls.__init__ = nop
  78. client: glm.GenerativeServiceClient = cls(**self.client_config)
  79. cls.__init__ = original_init
  80. if not self.default_metadata:
  81. return client
  82. @pytest.fixture
  83. def setup_google_mock(request, monkeypatch: MonkeyPatch):
  84. monkeypatch.setattr(BaseGenerateContentResponse, "text", MockGoogleClass.generative_response_text)
  85. monkeypatch.setattr(BaseGenerateContentResponse, "candidates", MockGoogleClass.generative_response_candidates)
  86. monkeypatch.setattr(GenerativeModel, "generate_content", MockGoogleClass.generate_content)
  87. monkeypatch.setattr(_ClientManager, "make_client", MockGoogleClass.make_client)
  88. yield
  89. monkeypatch.undo()