code: from unittest.mock import MagicMock, patch
  
  import pytest
  
  try:
      import google.ai.generativelanguage as genai
  
      has_google = True
  except ImportError:
      has_google = False
  
  from llama_index.legacy.response_synthesizers.google.generativeai import (
      GoogleTextSynthesizer,
      set_google_config,
  )
  from llama_index.legacy.schema import NodeWithScore, TextNode
  
  SKIP_TEST_REASON = "Google GenerativeAI is not installed"
  
  
  if has_google:
      import llama_index.legacy.vector_stores.google.generativeai.genai_extension as genaix
  
      set_google_config(
          api_endpoint="No-such-endpoint-to-prevent-hitting-real-backend",
          testing=True,
      )
  
  
  @pytest.mark.skipif(not has_google, reason=SKIP_TEST_REASON)
  @patch("google.auth.credentials.Credentials")
  def test_set_google_config(mock_credentials: MagicMock) -> None:
      set_google_config(auth_credentials=mock_credentials)
      config = genaix.get_config()
      assert config.auth_credentials == mock_credentials
  
  
  @pytest.mark.skipif(not has_google, reason=SKIP_TEST_REASON)
  @patch("google.ai.generativelanguage.GenerativeServiceClient.generate_answer")
  def test_get_response(mock_generate_answer: MagicMock) -> None:
      # Arrange
      mock_generate_answer.return_value = genai.GenerateAnswerResponse(
          answer=genai.Candidate(
              content=genai.Content(parts=[genai.Part(text="42")]),
              grounding_attributions=[
                  genai.GroundingAttribution(
                      content=genai.Content(
                          parts=[genai.Part(text="Meaning of life is 42.")]
                      ),
                      source_id=genai.AttributionSourceId(
                          grounding_passage=genai.AttributionSourceId.GroundingPassageId(
                              passage_id="corpora/123/documents/456/chunks/789",
                              part_index=0,
                          )
                      ),
                  ),
              ],
              finish_reason=genai.Candidate.FinishReason.STOP,
          ),
          answerable_probability=0.7,
      )
  
      # Act
      synthesizer = GoogleTextSynthesizer.from_defaults(
          temperature=0.5,
          answer_style=genai.GenerateAnswerRequest.AnswerStyle.ABSTRACTIVE,
          safety_setting=[
              genai.SafetySetting(
                  category=genai.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
                  threshold=genai.SafetySetting.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
              )
          ],
      )
      response = synthesizer.get_response(
          query_str="What is the meaning of life?",
          text_chunks=[
              "It's 42",
          ],
      )
  
      # Assert
      assert response.answer == "42"
      assert response.attributed_passages == ["Meaning of life is 42."]
      assert response.answerable_probability == pytest.approx(0.7)
  
      assert mock_generate_answer.call_count == 1
      request = mock_generate_answer.call_args.args[0]
      assert request.contents[0].parts[0].text == "What is the meaning of life?"
  
      assert request.answer_style == genai.GenerateAnswerRequest.AnswerStyle.ABSTRACTIVE
  
      assert len(request.safety_settings) == 1
      assert (
          request.safety_settings[0].category
          == genai.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT
      )
      assert (
          request.safety_settings[0].threshold
          == genai.SafetySetting.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE
      )
  
      assert request.temperature == 0.5
  
      passages = request.inline_passages.passages
      assert len(passages) == 1
      passage = passages[0]
      assert passage.content.parts[0].text == "It's 42"
  
  
  @pytest.mark.skipif(not has_google, reason=SKIP_TEST_REASON)
  @patch("google.ai.generativelanguage.GenerativeServiceClient.generate_answer")
  def test_synthesize(mock_generate_answer: MagicMock) -> None:
      # Arrange
      mock_generate_answer.return_value = genai.GenerateAnswerResponse(
          answer=genai.Candidate(
              content=genai.Content(parts=[genai.Part(text="42")]),
              grounding_attributions=[
                  genai.GroundingAttribution(
                      content=genai.Content(
                          parts=[genai.Part(text="Meaning of life is 42")]
                      ),
                      source_id=genai.AttributionSourceId(
                          grounding_passage=genai.AttributionSourceId.GroundingPassageId(
                              passage_id="corpora/123/documents/456/chunks/777",
                              part_index=0,
                          )
                      ),
                  ),
                  genai.GroundingAttribution(
                      content=genai.Content(parts=[genai.Part(text="Or maybe not")]),
                      source_id=genai.AttributionSourceId(
                          grounding_passage=genai.AttributionSourceId.GroundingPassageId(
                              passage_id="corpora/123/documents/456/chunks/888",
                              part_index=0,
                          )
                      ),
                  ),
              ],
              finish_reason=genai.Candidate.FinishReason.STOP,
          ),
          answerable_probability=0.9,
      )
  
      # Act
      synthesizer = GoogleTextSynthesizer.from_defaults()
      response = synthesizer.synthesize(
          query="What is the meaning of life?",
          nodes=[
              NodeWithScore(
                  node=TextNode(text="It's 42"),
                  score=0.5,
              ),
          ],
          additional_source_nodes=[
              NodeWithScore(
                  node=TextNode(text="Additional node"),
                  score=0.4,
              ),
          ],
      )
  
      # Assert
      assert response.response == "42"
      assert len(response.source_nodes) == 4
  
      first_attributed_source = response.source_nodes[0]
      assert first_attributed_source.node.text == "Meaning of life is 42"
      assert first_attributed_source.score is None
  
      second_attributed_source = response.source_nodes[1]
      assert second_attributed_source.node.text == "Or maybe not"
      assert second_attributed_source.score is None
  
      first_input_source = response.source_nodes[2]
      assert first_input_source.node.text == "It's 42"
      assert first_input_source.score == pytest.approx(0.5)
  
      first_additional_source = response.source_nodes[3]
      assert first_additional_source.node.text == "Additional node"
      assert first_additional_source.score == pytest.approx(0.4)
  
      assert response.metadata is not None
      assert response.metadata.get("answerable_probability", None) == pytest.approx(0.9)
  
  
  @pytest.mark.skipif(not has_google, reason=SKIP_TEST_REASON)
  @patch("google.ai.generativelanguage.GenerativeServiceClient.generate_answer")
  def test_synthesize_with_max_token_blocking(mock_generate_answer: MagicMock) -> None:
      # Arrange
      mock_generate_answer.return_value = genai.GenerateAnswerResponse(
          answer=genai.Candidate(
              content=genai.Content(parts=[]),
              grounding_attributions=[],
              finish_reason=genai.Candidate.FinishReason.MAX_TOKENS,
          ),
      )
  
      # Act
      synthesizer = GoogleTextSynthesizer.from_defaults()
      with pytest.raises(Exception) as e:
          synthesizer.synthesize(
              query="What is the meaning of life?",
              nodes=[
                  NodeWithScore(
                      node=TextNode(text="It's 42"),
                      score=0.5,
                  ),
              ],
          )
  
      # Assert
      assert "Maximum token" in str(e.value)
  
  
  @pytest.mark.skipif(not has_google, reason=SKIP_TEST_REASON)
  @patch("google.ai.generativelanguage.GenerativeServiceClient.generate_answer")
  def test_synthesize_with_safety_blocking(mock_generate_answer: MagicMock) -> None:
      # Arrange
      mock_generate_answer.return_value = genai.GenerateAnswerResponse(
          answer=genai.Candidate(
              content=genai.Content(parts=[]),
              grounding_attributions=[],
              finish_reason=genai.Candidate.FinishReason.SAFETY,
          ),
      )
  
      # Act
      synthesizer = GoogleTextSynthesizer.from_defaults()
      with pytest.raises(Exception) as e:
          synthesizer.synthesize(
              query="What is the meaning of life?",
              nodes=[
                  NodeWithScore(
                      node=TextNode(text="It's 42"),
                      score=0.5,
                  ),
              ],
          )
  
      # Assert
      assert "safety" in str(e.value)
  
  
  @pytest.mark.skipif(not has_google, reason=SKIP_TEST_REASON)
  @patch("google.ai.generativelanguage.GenerativeServiceClient.generate_answer")
  def test_synthesize_with_recitation_blocking(mock_generate_answer: MagicMock) -> None:
      # Arrange
      mock_generate_answer.return_value = genai.GenerateAnswerResponse(
          answer=genai.Candidate(
              content=genai.Content(parts=[]),
              grounding_attributions=[],
              finish_reason=genai.Candidate.FinishReason.RECITATION,
          ),
      )
  
      # Act
      synthesizer = GoogleTextSynthesizer.from_defaults()
      with pytest.raises(Exception) as e:
          synthesizer.synthesize(
              query="What is the meaning of life?",
              nodes=[
                  NodeWithScore(
                      node=TextNode(text="It's 42"),
                      score=0.5,
                  ),
              ],
          )
  
      # Assert
      assert "recitation" in str(e.value)
  
  
  @pytest.mark.skipif(not has_google, reason=SKIP_TEST_REASON)
  @patch("google.ai.generativelanguage.GenerativeServiceClient.generate_answer")
  def test_synthesize_with_unknown_blocking(mock_generate_answer: MagicMock) -> None:
      # Arrange
      mock_generate_answer.return_value = genai.GenerateAnswerResponse(
          answer=genai.Candidate(
              content=genai.Content(parts=[]),
              grounding_attributions=[],
              finish_reason=genai.Candidate.FinishReason.OTHER,
          ),
      )
  
      # Act
      synthesizer = GoogleTextSynthesizer.from_defaults()
      with pytest.raises(Exception) as e:
          synthesizer.synthesize(
              query="What is the meaning of life?",
              nodes=[
                  NodeWithScore(
                      node=TextNode(text="It's 42"),
                      score=0.5,
                  ),
              ],
          )
  
      # Assert
      assert "Unexpected" in str(e.value)
  
apis: llama_index.legacy.vector_stores.google.generativeai.genai_extension.get_config llama_index.legacy.response_synthesizers.google.generativeai.GoogleTextSynthesizer.from_defaults llama_index.legacy.schema.TextNode llama_index.legacy.response_synthesizers.google.generativeai.set_google_config
extract_api: [((663, 722), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not has_google)'], {'reason': 'SKIP_TEST_REASON'}), '(not has_google, reason=SKIP_TEST_REASON)\n', (681, 722), False, 'import pytest\n'), ((724, 768), 'unittest.mock.patch', 'patch', (['"""google.auth.credentials.Credentials"""'], {}), "('google.auth.credentials.Credentials')\n", (729, 768), False, 'from unittest.mock import MagicMock, patch\n'), ((982, 1041), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not has_google)'], {'reason': 'SKIP_TEST_REASON'}), '(not has_google, reason=SKIP_TEST_REASON)\n', (1000, 1041), False, 'import pytest\n'), ((1043, 1120), 'unittest.mock.patch', 'patch', (['"""google.ai.generativelanguage.GenerativeServiceClient.generate_answer"""'], {}), "('google.ai.generativelanguage.GenerativeServiceClient.generate_answer')\n", (1048, 1120), False, 'from unittest.mock import MagicMock, patch\n'), ((3580, 3639), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not has_google)'], {'reason': 'SKIP_TEST_REASON'}), '(not has_google, reason=SKIP_TEST_REASON)\n', (3598, 3639), False, 'import pytest\n'), ((3641, 3718), 'unittest.mock.patch', 'patch', (['"""google.ai.generativelanguage.GenerativeServiceClient.generate_answer"""'], {}), "('google.ai.generativelanguage.GenerativeServiceClient.generate_answer')\n", (3646, 3718), False, 'from unittest.mock import MagicMock, patch\n'), ((6499, 6558), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not has_google)'], {'reason': 'SKIP_TEST_REASON'}), '(not has_google, reason=SKIP_TEST_REASON)\n', (6517, 6558), False, 'import pytest\n'), ((6560, 6637), 'unittest.mock.patch', 'patch', (['"""google.ai.generativelanguage.GenerativeServiceClient.generate_answer"""'], {}), "('google.ai.generativelanguage.GenerativeServiceClient.generate_answer')\n", (6565, 6637), False, 'from unittest.mock import MagicMock, patch\n'), ((7434, 7493), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not has_google)'], {'reason': 'SKIP_TEST_REASON'}), '(not has_google, reason=SKIP_TEST_REASON)\n', (7452, 7493), False, 'import pytest\n'), ((7495, 7572), 'unittest.mock.patch', 'patch', (['"""google.ai.generativelanguage.GenerativeServiceClient.generate_answer"""'], {}), "('google.ai.generativelanguage.GenerativeServiceClient.generate_answer')\n", (7500, 7572), False, 'from unittest.mock import MagicMock, patch\n'), ((8355, 8414), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not has_google)'], {'reason': 'SKIP_TEST_REASON'}), '(not has_google, reason=SKIP_TEST_REASON)\n', (8373, 8414), False, 'import pytest\n'), ((8416, 8493), 'unittest.mock.patch', 'patch', (['"""google.ai.generativelanguage.GenerativeServiceClient.generate_answer"""'], {}), "('google.ai.generativelanguage.GenerativeServiceClient.generate_answer')\n", (8421, 8493), False, 'from unittest.mock import MagicMock, patch\n'), ((9288, 9347), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not has_google)'], {'reason': 'SKIP_TEST_REASON'}), '(not has_google, reason=SKIP_TEST_REASON)\n', (9306, 9347), False, 'import pytest\n'), ((9349, 9426), 'unittest.mock.patch', 'patch', (['"""google.ai.generativelanguage.GenerativeServiceClient.generate_answer"""'], {}), "('google.ai.generativelanguage.GenerativeServiceClient.generate_answer')\n", (9354, 9426), False, 'from unittest.mock import MagicMock, patch\n'), ((540, 641), 'llama_index.legacy.response_synthesizers.google.generativeai.set_google_config', 'set_google_config', ([], {'api_endpoint': '"""No-such-endpoint-to-prevent-hitting-real-backend"""', 'testing': '(True)'}), "(api_endpoint=\n    'No-such-endpoint-to-prevent-hitting-real-backend', testing=True)\n", (557, 641), False, 'from llama_index.legacy.response_synthesizers.google.generativeai import GoogleTextSynthesizer, set_google_config\n'), ((838, 890), 'llama_index.legacy.response_synthesizers.google.generativeai.set_google_config', 'set_google_config', ([], {'auth_credentials': 'mock_credentials'}), '(auth_credentials=mock_credentials)\n', (855, 890), False, 'from llama_index.legacy.response_synthesizers.google.generativeai import GoogleTextSynthesizer, set_google_config\n'), ((904, 923), 'llama_index.legacy.vector_stores.google.generativeai.genai_extension.get_config', 'genaix.get_config', ([], {}), '()\n', (921, 923), True, 'import llama_index.legacy.vector_stores.google.generativeai.genai_extension as genaix\n'), ((5137, 5174), 'llama_index.legacy.response_synthesizers.google.generativeai.GoogleTextSynthesizer.from_defaults', 'GoogleTextSynthesizer.from_defaults', ([], {}), '()\n', (5172, 5174), False, 'from llama_index.legacy.response_synthesizers.google.generativeai import GoogleTextSynthesizer, set_google_config\n'), ((7037, 7074), 'llama_index.legacy.response_synthesizers.google.generativeai.GoogleTextSynthesizer.from_defaults', 'GoogleTextSynthesizer.from_defaults', ([], {}), '()\n', (7072, 7074), False, 'from llama_index.legacy.response_synthesizers.google.generativeai import GoogleTextSynthesizer, set_google_config\n'), ((7965, 8002), 'llama_index.legacy.response_synthesizers.google.generativeai.GoogleTextSynthesizer.from_defaults', 'GoogleTextSynthesizer.from_defaults', ([], {}), '()\n', (8000, 8002), False, 'from llama_index.legacy.response_synthesizers.google.generativeai import GoogleTextSynthesizer, set_google_config\n'), ((8894, 8931), 'llama_index.legacy.response_synthesizers.google.generativeai.GoogleTextSynthesizer.from_defaults', 'GoogleTextSynthesizer.from_defaults', ([], {}), '()\n', (8929, 8931), False, 'from llama_index.legacy.response_synthesizers.google.generativeai import GoogleTextSynthesizer, set_google_config\n'), ((9819, 9856), 'llama_index.legacy.response_synthesizers.google.generativeai.GoogleTextSynthesizer.from_defaults', 'GoogleTextSynthesizer.from_defaults', ([], {}), '()\n', (9854, 9856), False, 'from llama_index.legacy.response_synthesizers.google.generativeai import GoogleTextSynthesizer, set_google_config\n'), ((2786, 2804), 'pytest.approx', 'pytest.approx', (['(0.7)'], {}), '(0.7)\n', (2799, 2804), False, 'import pytest\n'), ((6163, 6181), 'pytest.approx', 'pytest.approx', (['(0.5)'], {}), '(0.5)\n', (6176, 6181), False, 'import pytest\n'), ((6348, 6366), 'pytest.approx', 'pytest.approx', (['(0.4)'], {}), '(0.4)\n', (6361, 6366), False, 'import pytest\n'), ((6477, 6495), 'pytest.approx', 'pytest.approx', (['(0.9)'], {}), '(0.9)\n', (6490, 6495), False, 'import pytest\n'), ((7084, 7108), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (7097, 7108), False, 'import pytest\n'), ((8012, 8036), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (8025, 8036), False, 'import pytest\n'), ((8941, 8965), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (8954, 8965), False, 'import pytest\n'), ((9866, 9890), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (9879, 9890), False, 'import pytest\n'), ((2253, 2413), 'google.ai.generativelanguage.SafetySetting', 'genai.SafetySetting', ([], {'category': 'genai.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT', 'threshold': 'genai.SafetySetting.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE'}), '(category=genai.HarmCategory.\n    HARM_CATEGORY_SEXUALLY_EXPLICIT, threshold=genai.SafetySetting.\n    HarmBlockThreshold.BLOCK_LOW_AND_ABOVE)\n', (2272, 2413), True, 'import google.ai.generativelanguage as genai\n'), ((6860, 6883), 'google.ai.generativelanguage.Content', 'genai.Content', ([], {'parts': '[]'}), '(parts=[])\n', (6873, 6883), True, 'import google.ai.generativelanguage as genai\n'), ((7792, 7815), 'google.ai.generativelanguage.Content', 'genai.Content', ([], {'parts': '[]'}), '(parts=[])\n', (7805, 7815), True, 'import google.ai.generativelanguage as genai\n'), ((8717, 8740), 'google.ai.generativelanguage.Content', 'genai.Content', ([], {'parts': '[]'}), '(parts=[])\n', (8730, 8740), True, 'import google.ai.generativelanguage as genai\n'), ((9647, 9670), 'google.ai.generativelanguage.Content', 'genai.Content', ([], {'parts': '[]'}), '(parts=[])\n', (9660, 9670), True, 'import google.ai.generativelanguage as genai\n'), ((5324, 5348), 'llama_index.legacy.schema.TextNode', 'TextNode', ([], {'text': '"""It\'s 42"""'}), '(text="It\'s 42")\n', (5332, 5348), False, 'from llama_index.legacy.schema import NodeWithScore, TextNode\n'), ((5485, 5517), 'llama_index.legacy.schema.TextNode', 'TextNode', ([], {'text': '"""Additional node"""'}), "(text='Additional node')\n", (5493, 5517), False, 'from llama_index.legacy.schema import NodeWithScore, TextNode\n'), ((7273, 7297), 'llama_index.legacy.schema.TextNode', 'TextNode', ([], {'text': '"""It\'s 42"""'}), '(text="It\'s 42")\n', (7281, 7297), False, 'from llama_index.legacy.schema import NodeWithScore, TextNode\n'), ((8201, 8225), 'llama_index.legacy.schema.TextNode', 'TextNode', ([], {'text': '"""It\'s 42"""'}), '(text="It\'s 42")\n', (8209, 8225), False, 'from llama_index.legacy.schema import NodeWithScore, TextNode\n'), ((9130, 9154), 'llama_index.legacy.schema.TextNode', 'TextNode', ([], {'text': '"""It\'s 42"""'}), '(text="It\'s 42")\n', (9138, 9154), False, 'from llama_index.legacy.schema import NodeWithScore, TextNode\n'), ((10055, 10079), 'llama_index.legacy.schema.TextNode', 'TextNode', ([], {'text': '"""It\'s 42"""'}), '(text="It\'s 42")\n', (10063, 10079), False, 'from llama_index.legacy.schema import NodeWithScore, TextNode\n'), ((1342, 1363), 'google.ai.generativelanguage.Part', 'genai.Part', ([], {'text': '"""42"""'}), "(text='42')\n", (1352, 1363), True, 'import google.ai.generativelanguage as genai\n'), ((3938, 3959), 'google.ai.generativelanguage.Part', 'genai.Part', ([], {'text': '"""42"""'}), "(text='42')\n", (3948, 3959), True, 'import google.ai.generativelanguage as genai\n'), ((1687, 1801), 'google.ai.generativelanguage.AttributionSourceId.GroundingPassageId', 'genai.AttributionSourceId.GroundingPassageId', ([], {'passage_id': '"""corpora/123/documents/456/chunks/789"""', 'part_index': '(0)'}), "(passage_id=\n    'corpora/123/documents/456/chunks/789', part_index=0)\n", (1731, 1801), True, 'import google.ai.generativelanguage as genai\n'), ((4282, 4396), 'google.ai.generativelanguage.AttributionSourceId.GroundingPassageId', 'genai.AttributionSourceId.GroundingPassageId', ([], {'passage_id': '"""corpora/123/documents/456/chunks/777"""', 'part_index': '(0)'}), "(passage_id=\n    'corpora/123/documents/456/chunks/777', part_index=0)\n", (4326, 4396), True, 'import google.ai.generativelanguage as genai\n'), ((4744, 4858), 'google.ai.generativelanguage.AttributionSourceId.GroundingPassageId', 'genai.AttributionSourceId.GroundingPassageId', ([], {'passage_id': '"""corpora/123/documents/456/chunks/888"""', 'part_index': '(0)'}), "(passage_id=\n    'corpora/123/documents/456/chunks/888', part_index=0)\n", (4788, 4858), True, 'import google.ai.generativelanguage as genai\n'), ((1522, 1563), 'google.ai.generativelanguage.Part', 'genai.Part', ([], {'text': '"""Meaning of life is 42."""'}), "(text='Meaning of life is 42.')\n", (1532, 1563), True, 'import google.ai.generativelanguage as genai\n'), ((4118, 4158), 'google.ai.generativelanguage.Part', 'genai.Part', ([], {'text': '"""Meaning of life is 42"""'}), "(text='Meaning of life is 42')\n", (4128, 4158), True, 'import google.ai.generativelanguage as genai\n'), ((4610, 4641), 'google.ai.generativelanguage.Part', 'genai.Part', ([], {'text': '"""Or maybe not"""'}), "(text='Or maybe not')\n", (4620, 4641), True, 'import google.ai.generativelanguage as genai\n')]