/
test_generative_models.py
361 lines (327 loc) · 12.5 KB
/
test_generative_models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# -*- coding: utf-8 -*-
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# pylint: disable=protected-access,bad-continuation
import pytest
from typing import Iterable, MutableSequence, Optional
from unittest import mock
import vertexai
from google.cloud.aiplatform import initializer
from vertexai import generative_models
from vertexai.preview import generative_models as preview_generative_models
from vertexai.generative_models._generative_models import (
prediction_service,
gapic_prediction_service_types,
gapic_content_types,
)
_TEST_PROJECT = "test-project"
_TEST_LOCATION = "us-central1"
_RESPONSE_TEXT_PART_STRUCT = {
"text": "The sky appears blue due to a phenomenon called Rayleigh scattering."
}
_RESPONSE_FUNCTION_CALL_PART_STRUCT = {
"function_call": {
"name": "get_current_weather",
"args": {
"fields": {
"key": "location",
"value": {"string_value": "Boston"},
}
},
}
}
_RESPONSE_AFTER_FUNCTION_CALL_PART_STRUCT = {
"text": "The weather in Boston is super nice!"
}
_RESPONSE_SAFETY_RATINGS_STRUCT = [
{"category": "HARM_CATEGORY_HARASSMENT", "probability": "NEGLIGIBLE"},
{"category": "HARM_CATEGORY_HATE_SPEECH", "probability": "NEGLIGIBLE"},
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "probability": "NEGLIGIBLE"},
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "probability": "NEGLIGIBLE"},
]
_RESPONSE_CITATION_STRUCT = {
"start_index": 528,
"end_index": 656,
"uri": "https://www.quora.com/What-makes-the-sky-blue-during-the-day",
}
_REQUEST_TOOL_STRUCT = {
"function_declarations": [
{
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit",
],
},
},
"required": ["location"],
},
}
]
}
_REQUEST_FUNCTION_PARAMETER_SCHEMA_STRUCT = {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit",
],
},
},
"required": ["location"],
}
def mock_generate_content(
self,
request: gapic_prediction_service_types.GenerateContentRequest,
*,
model: Optional[str] = None,
contents: Optional[MutableSequence[gapic_content_types.Content]] = None,
) -> Iterable[gapic_prediction_service_types.GenerateContentResponse]:
is_continued_chat = len(request.contents) > 1
has_retrieval = any(
tool.retrieval or tool.google_search_retrieval for tool in request.tools
)
has_function_declarations = any(
tool.function_declarations for tool in request.tools
)
has_function_request = any(
content.parts[0].function_call for content in request.contents
)
has_function_response = any(
content.parts[0].function_response for content in request.contents
)
if has_function_request:
assert has_function_response
if has_function_response:
assert has_function_request
assert has_function_declarations
if has_function_declarations:
needs_function_call = not has_function_response
if needs_function_call:
response_part_struct = _RESPONSE_FUNCTION_CALL_PART_STRUCT
else:
response_part_struct = _RESPONSE_AFTER_FUNCTION_CALL_PART_STRUCT
elif is_continued_chat:
response_part_struct = {"text": "Other planets may have different sky color."}
else:
response_part_struct = _RESPONSE_TEXT_PART_STRUCT
response = gapic_prediction_service_types.GenerateContentResponse(
candidates=[
gapic_content_types.Candidate(
index=0,
content=gapic_content_types.Content(
# Model currently does not identify itself
# role="model",
parts=[
gapic_content_types.Part(response_part_struct),
],
),
finish_reason=gapic_content_types.Candidate.FinishReason.STOP,
safety_ratings=[
gapic_content_types.SafetyRating(rating)
for rating in _RESPONSE_SAFETY_RATINGS_STRUCT
],
citation_metadata=gapic_content_types.CitationMetadata(
citations=[
gapic_content_types.Citation(_RESPONSE_CITATION_STRUCT),
]
),
grounding_metadata=gapic_content_types.GroundingMetadata(
web_search_queries=[request.contents[0].parts[0].text],
grounding_attributions=[
gapic_content_types.GroundingAttribution(
segment=gapic_content_types.Segment(
start_index=0,
end_index=67,
),
confidence_score=0.69857746,
web=gapic_content_types.GroundingAttribution.Web(
uri="https://math.ucr.edu/home/baez/physics/General/BlueSky/blue_sky.html",
title="Why is the sky blue? - UCR Math",
),
),
],
)
if has_retrieval and request.contents[0].parts[0].text
else None,
),
],
)
return response
def mock_stream_generate_content(
self,
request: gapic_prediction_service_types.GenerateContentRequest,
*,
model: Optional[str] = None,
contents: Optional[MutableSequence[gapic_content_types.Content]] = None,
) -> Iterable[gapic_prediction_service_types.GenerateContentResponse]:
yield mock_generate_content(
self=self, request=request, model=model, contents=contents
)
@pytest.mark.usefixtures("google_auth_mock")
class TestGenerativeModels:
"""Unit tests for the generative models."""
def setup_method(self):
vertexai.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
)
def teardown_method(self):
initializer.global_pool.shutdown(wait=True)
@mock.patch.object(
target=prediction_service.PredictionServiceClient,
attribute="generate_content",
new=mock_generate_content,
)
@pytest.mark.parametrize(
"generative_models",
[generative_models, preview_generative_models],
)
def test_generate_content(self, generative_models: generative_models):
model = generative_models.GenerativeModel("gemini-pro")
response = model.generate_content("Why is sky blue?")
assert response.text
response2 = model.generate_content(
"Why is sky blue?",
generation_config=generative_models.GenerationConfig(
temperature=0.2,
top_p=0.9,
top_k=20,
candidate_count=1,
max_output_tokens=200,
stop_sequences=["\n\n\n"],
),
)
assert response2.text
@mock.patch.object(
target=prediction_service.PredictionServiceClient,
attribute="stream_generate_content",
new=mock_stream_generate_content,
)
@pytest.mark.parametrize(
"generative_models",
[generative_models, preview_generative_models],
)
def test_generate_content_streaming(self, generative_models: generative_models):
model = generative_models.GenerativeModel("gemini-pro")
stream = model.generate_content("Why is sky blue?", stream=True)
for chunk in stream:
assert chunk.text
@mock.patch.object(
target=prediction_service.PredictionServiceClient,
attribute="generate_content",
new=mock_generate_content,
)
@pytest.mark.parametrize(
"generative_models",
[generative_models, preview_generative_models],
)
def test_chat_send_message(self, generative_models: generative_models):
model = generative_models.GenerativeModel("gemini-pro")
chat = model.start_chat()
response1 = chat.send_message("Why is sky blue?")
assert response1.text
response2 = chat.send_message("Is sky blue on other planets?")
assert response2.text
@mock.patch.object(
target=prediction_service.PredictionServiceClient,
attribute="generate_content",
new=mock_generate_content,
)
@pytest.mark.parametrize(
"generative_models",
[generative_models, preview_generative_models],
)
def test_chat_function_calling(self, generative_models: generative_models):
get_current_weather_func = generative_models.FunctionDeclaration(
name="get_current_weather",
description="Get the current weather in a given location",
parameters=_REQUEST_FUNCTION_PARAMETER_SCHEMA_STRUCT,
)
weather_tool = generative_models.Tool(
function_declarations=[get_current_weather_func],
)
model = generative_models.GenerativeModel(
"gemini-pro",
# Specifying the tools once to avoid specifying them in every request
tools=[weather_tool],
)
chat = model.start_chat()
response1 = chat.send_message("What is the weather like in Boston?")
assert (
response1.candidates[0].content.parts[0].function_call.name
== "get_current_weather"
)
response2 = chat.send_message(
generative_models.Part.from_function_response(
name="get_current_weather",
response={
"content": {"weather_there": "super nice"},
},
),
)
assert response2.text == "The weather in Boston is super nice!"
@mock.patch.object(
target=prediction_service.PredictionServiceClient,
attribute="generate_content",
new=mock_generate_content,
)
def test_generate_content_grounding_google_search_retriever(self):
model = preview_generative_models.GenerativeModel("gemini-pro")
google_search_retriever_tool = (
preview_generative_models.Tool.from_google_search_retrieval(
preview_generative_models.grounding.GoogleSearchRetrieval(
disable_attribution=False
)
)
)
response = model.generate_content(
"Why is sky blue?", tools=[google_search_retriever_tool]
)
assert response.text
@mock.patch.object(
target=prediction_service.PredictionServiceClient,
attribute="generate_content",
new=mock_generate_content,
)
def test_generate_content_grounding_vertex_ai_search_retriever(self):
model = preview_generative_models.GenerativeModel("gemini-pro")
google_search_retriever_tool = preview_generative_models.Tool.from_retrieval(
retrieval=preview_generative_models.grounding.Retrieval(
source=preview_generative_models.grounding.VertexAISearch(
datastore=f"projects/{_TEST_PROJECT}/locations/global/collections/default_collection/dataStores/test-datastore",
)
)
)
response = model.generate_content(
"Why is sky blue?", tools=[google_search_retriever_tool]
)
assert response.text