-
Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathvertexai_llm.py
More file actions
630 lines (558 loc) · 23.6 KB
/
vertexai_llm.py
File metadata and controls
630 lines (558 loc) · 23.6 KB
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
# Neo4j Sweden AB [https://neo4j.com]
# #
# 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
# #
# https://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.
# built-in dependencies
from __future__ import annotations
import inspect
import logging
from typing import Any, List, Optional, Sequence, Type, Union, cast, overload
# 3rd party dependencies
from pydantic import BaseModel, ValidationError
# project dependencies
from neo4j_graphrag.exceptions import LLMGenerationError
from neo4j_graphrag.llm.base import LLMInterface, LLMInterfaceV2
from neo4j_graphrag.llm.types import (
BaseMessage,
LLMResponse,
MessageList,
ToolCall,
ToolCallResponse,
)
from neo4j_graphrag.message_history import MessageHistory
from neo4j_graphrag.tool import Tool
from neo4j_graphrag.types import LLMMessage
from neo4j_graphrag.utils.rate_limit import (
RateLimitHandler,
)
from neo4j_graphrag.utils.rate_limit import (
async_rate_limit_handler as async_rate_limit_handler_decorator,
)
from neo4j_graphrag.utils.rate_limit import (
rate_limit_handler as rate_limit_handler_decorator,
)
try:
from vertexai.generative_models import (
Content,
FunctionCall,
FunctionDeclaration,
GenerationResponse,
GenerativeModel,
Part,
ResponseValidationError,
ToolConfig,
)
from vertexai.generative_models import (
Tool as VertexAITool,
)
except ImportError:
GenerativeModel = None # type: ignore[misc, assignment]
ResponseValidationError = None # type: ignore[misc, assignment]
logger = logging.getLogger(__name__)
# Params to exclude when extracting from GenerationConfig for structured output
_GENERATION_CONFIG_SCHEMA_PARAMS = {"response_schema", "response_mime_type"}
def _extract_generation_config_params(
config: Any, exclude_schema: bool = True
) -> dict[str, Any]:
"""Extract valid parameters from a GenerationConfig object.
This function extracts parameters from the internal _raw_generation_config
protobuf and returns them as a dict that can be passed to GenerationConfig().
Args:
config: A GenerationConfig object
exclude_schema: If True, excludes response_schema and response_mime_type
Returns:
Dict of parameter name to value for non-empty params
"""
from vertexai.generative_models import GenerationConfig
if not hasattr(config, "_raw_generation_config"):
return {}
raw = config._raw_generation_config
# Get valid params from GenerationConfig signature
sig = inspect.signature(GenerationConfig.__init__)
valid_params = {
name
for name, _ in sig.parameters.items()
if name != "self"
and (not exclude_schema or name not in _GENERATION_CONFIG_SCHEMA_PARAMS)
}
preserved = {}
for param in valid_params:
val = getattr(raw, param, None)
if val: # Only include non-empty values
# Convert repeated fields (like stop_sequences) to lists
if hasattr(val, "__iter__") and not isinstance(val, (str, bytes, dict)):
val = list(val)
preserved[param] = val
return preserved
# pylint: disable=arguments-differ, redefined-builtin, no-else-return
class VertexAILLM(LLMInterface, LLMInterfaceV2):
"""Interface for large language models on Vertex AI
Args:
model_name (str, optional): Name of the LLM to use. Defaults to "gemini-1.5-flash-001".
model_params (Optional[dict], optional): Additional parameters for LLMInterface(V1) passed to the model when text is sent to it. Defaults to None.
system_instruction: Optional[str], optional): Additional instructions for setting the behavior and context for the model in a conversation. Defaults to None.
rate_limit_handler (Optional[RateLimitHandler], optional): Rate limit handler for LLMInterface(V1). Defaults to None.
**kwargs (Any): Arguments passed to the model when for the class is initialised. Defaults to None.
Raises:
LLMGenerationError: If there's an error generating the response from the model.
Example:
.. code-block:: python
from neo4j_graphrag.llm import VertexAILLM
from vertexai.generative_models import GenerationConfig
generation_config = GenerationConfig(temperature=0.0)
llm = VertexAILLM(
model_name="gemini-1.5-flash-001", generation_config=generation_config
)
llm.invoke("Who is the mother of Paul Atreides?")
"""
supports_structured_output: bool = True
def __init__(
self,
model_name: str = "gemini-1.5-flash-001",
model_params: Optional[dict[str, Any]] = None,
system_instruction: Optional[str] = None,
rate_limit_handler: Optional[RateLimitHandler] = None,
**kwargs: Any,
):
if GenerativeModel is None or ResponseValidationError is None:
raise ImportError(
"""Could not import Vertex AI Python client.
Please install it with `pip install "neo4j-graphrag[google]"`."""
)
LLMInterfaceV2.__init__(
self,
model_name=model_name,
model_params=model_params or {},
rate_limit_handler=rate_limit_handler,
)
self.model_name = model_name
self.system_instruction = system_instruction
self.options = kwargs
# overloads for LLMInterface and LLMInterfaceV2 methods
@overload # type: ignore[no-overload-impl]
def invoke(
self,
input: str,
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
system_instruction: Optional[str] = None,
) -> LLMResponse: ...
@overload
def invoke(
self,
input: List[LLMMessage],
response_format: Optional[Union[Type[BaseModel], dict[str, Any]]] = None,
**kwargs: Any,
) -> LLMResponse: ...
@overload # type: ignore[no-overload-impl]
async def ainvoke(
self,
input: str,
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
system_instruction: Optional[str] = None,
) -> LLMResponse: ...
@overload
async def ainvoke(
self,
input: List[LLMMessage],
response_format: Optional[Union[Type[BaseModel], dict[str, Any]]] = None,
**kwargs: Any,
) -> LLMResponse: ...
# switching logics to LLMInterface or LLMInterfaceV2
def invoke( # type: ignore[no-redef]
self,
input: Union[str, List[LLMMessage]],
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
system_instruction: Optional[str] = None,
response_format: Optional[Union[Type[BaseModel], dict[str, Any]]] = None,
**kwargs: Any,
) -> LLMResponse:
if isinstance(input, str):
return self.__invoke_v1(input, message_history, system_instruction)
elif isinstance(input, list):
return self.__invoke_v2(input, response_format=response_format, **kwargs)
else:
raise ValueError(f"Invalid input type for invoke method - {type(input)}")
async def ainvoke( # type: ignore[no-redef]
self,
input: Union[str, List[LLMMessage]],
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
system_instruction: Optional[str] = None,
response_format: Optional[Union[Type[BaseModel], dict[str, Any]]] = None,
**kwargs: Any,
) -> LLMResponse:
if isinstance(input, str):
return await self.__ainvoke_v1(input, message_history, system_instruction)
elif isinstance(input, list):
return await self.__ainvoke_v2(
input, response_format=response_format, **kwargs
)
else:
raise ValueError(f"Invalid input type for ainvoke method - {type(input)}")
def invoke_with_tools(
self,
input: str,
tools: Sequence[Tool], # Tools definition as a sequence of Tool objects
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
system_instruction: Optional[str] = None,
) -> ToolCallResponse:
return self.__invoke_v1_with_tools(
input, tools, message_history, system_instruction
)
async def ainvoke_with_tools(
self,
input: str,
tools: Sequence[Tool],
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
system_instruction: Optional[str] = None,
) -> ToolCallResponse:
return await self.__ainvoke_v1_with_tools(
input, tools, message_history, system_instruction
)
# legacy and brand new implementations
@rate_limit_handler_decorator
def __invoke_v1(
self,
input: str,
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
system_instruction: Optional[str] = None,
) -> LLMResponse:
"""Sends text to the LLM and returns a response.
Args:
input (str): The text to send to the LLM.
message_history (Optional[Union[List[LLMMessage], MessageHistory]]): A collection previous messages,
with each message having a specific role assigned.
system_instruction (Optional[str]): An option to override the llm system message for this invocation.
Returns:
LLMResponse: The response from the LLM.
"""
model = self._get_model(
system_instruction=system_instruction,
)
try:
if isinstance(message_history, MessageHistory):
message_history = message_history.messages
options = self._get_call_params(input, message_history, tools=None)
response = model.generate_content(**options)
return self._parse_content_response(response)
except ResponseValidationError as e:
raise LLMGenerationError("Error calling VertexAILLM") from e
@rate_limit_handler_decorator
def __invoke_v2(
self,
input: List[LLMMessage],
response_format: Optional[Union[Type[BaseModel], dict[str, Any]]] = None,
**kwargs: Any,
) -> LLMResponse:
"""New invoke method for LLMInterfaceV2.
Args:
input (List[LLMMessage]): Input to the LLM.
response_format (Optional[Union[Type[BaseModel], dict[str, Any]]]): Optional
response format. Can be a Pydantic model class for structured output
or a JSON schema dict.
**kwargs: Additional parameters to pass to GenerationConfig (e.g., temperature,
max_output_tokens, top_p, top_k). These override constructor values.
Returns:
LLMResponse: The response from the LLM.
"""
system_instruction, messages = self.get_messages_v2(input)
model = self._get_model(
system_instruction=system_instruction,
)
try:
options = self._get_call_params_v2(
messages, tools=None, response_format=response_format, **kwargs
)
response = model.generate_content(**options)
return self._parse_content_response(response)
except ResponseValidationError as e:
raise LLMGenerationError("Error calling VertexAILLM") from e
@async_rate_limit_handler_decorator
async def __ainvoke_v1(
self,
input: str,
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
system_instruction: Optional[str] = None,
) -> LLMResponse:
"""Asynchronously sends text to the LLM and returns a response.
Args:
input (str): The text to send to the LLM.
message_history (Optional[Union[List[LLMMessage], MessageHistory]]): A collection previous messages,
with each message having a specific role assigned.
system_instruction (Optional[str]): An option to override the llm system message for this invocation.
Returns:
LLMResponse: The response from the LLM.
"""
try:
if isinstance(message_history, MessageHistory):
message_history = message_history.messages
model = self._get_model(
system_instruction=system_instruction,
)
options = self._get_call_params(input, message_history, tools=None)
response = await model.generate_content_async(**options)
return self._parse_content_response(response)
except ResponseValidationError as e:
raise LLMGenerationError("Error calling VertexAILLM") from e
@async_rate_limit_handler_decorator
async def __ainvoke_v2(
self,
input: list[LLMMessage],
response_format: Optional[Union[Type[BaseModel], dict[str, Any]]] = None,
**kwargs: Any,
) -> LLMResponse:
"""Asynchronously sends text to the LLM and returns a response.
Args:
input (List[LLMMessage]): Input to the LLM.
response_format (Optional[Union[Type[BaseModel], dict[str, Any]]]): Optional
response format. Can be a Pydantic model class for structured output
or a JSON schema dict.
**kwargs: Additional parameters to pass to GenerationConfig (e.g., temperature,
max_output_tokens, top_p, top_k). These override constructor values.
Returns:
LLMResponse: The response from the LLM.
"""
try:
system_instruction, messages = self.get_messages_v2(input)
model = self._get_model(
system_instruction=system_instruction,
)
options = self._get_call_params_v2(
messages, tools=None, response_format=response_format, **kwargs
)
response = await model.generate_content_async(**options)
return self._parse_content_response(response)
except ResponseValidationError as e:
raise LLMGenerationError("Error calling VertexAILLM") from e
def __invoke_v1_with_tools(
self,
input: str,
tools: Sequence[Tool],
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
system_instruction: Optional[str] = None,
) -> ToolCallResponse:
response = self._call_llm(
input,
message_history=message_history,
system_instruction=system_instruction,
tools=tools,
)
return self._parse_tool_response(response)
async def __ainvoke_v1_with_tools(
self,
input: str,
tools: Sequence[Tool],
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
system_instruction: Optional[str] = None,
) -> ToolCallResponse:
response = await self._acall_llm(
input,
message_history=message_history,
system_instruction=system_instruction,
tools=tools,
)
return self._parse_tool_response(response)
# subsdiary methods
def _to_vertexai_function_declaration(self, tool: Tool) -> FunctionDeclaration:
return FunctionDeclaration(
name=tool.get_name(),
description=tool.get_description(),
parameters=tool.get_parameters(exclude=["additional_properties"]),
)
def _get_llm_tools(
self, tools: Optional[Sequence[Tool]]
) -> Optional[list[VertexAITool]]:
if not tools:
return None
return [
VertexAITool(
function_declarations=[
self._to_vertexai_function_declaration(tool) for tool in tools
]
)
]
def _get_model(
self,
system_instruction: Optional[str] = None,
) -> GenerativeModel:
# system_message = [system_instruction] if system_instruction is not None else []
model = GenerativeModel(
model_name=self.model_name,
system_instruction=system_instruction,
)
return model
def get_messages(
self,
input: str,
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
) -> list[Content]:
"""Constructs messages for the Vertex AI model from input and message history."""
messages = []
if message_history:
if isinstance(message_history, MessageHistory):
message_history = message_history.messages
try:
MessageList(messages=cast(list[BaseMessage], message_history))
except ValidationError as e:
raise LLMGenerationError(e.errors()) from e
for message in message_history:
if message.get("role") == "user":
messages.append(
Content(
role="user",
parts=[Part.from_text(message.get("content", ""))],
)
)
elif message.get("role") == "assistant":
messages.append(
Content(
role="model",
parts=[Part.from_text(message.get("content", ""))],
)
)
messages.append(Content(role="user", parts=[Part.from_text(input)]))
return messages
def get_messages_v2(
self,
input: list[LLMMessage],
) -> tuple[str | None, list[Content]]:
"""Constructs messages for the Vertex AI model from input only."""
messages = []
system_instruction = self.system_instruction
for message in input:
role = message.get("role")
if role == "system":
system_instruction = message.get("content")
continue
if role == "user":
messages.append(
Content(
role="user",
parts=[Part.from_text(message.get("content", ""))],
)
)
continue
if role == "assistant":
messages.append(
Content(
role="model",
parts=[Part.from_text(message.get("content", ""))],
)
)
continue
raise ValueError(f"Unknown role: {role}")
return system_instruction, messages
def _get_call_params(
self,
input: str,
message_history: Optional[Union[List[LLMMessage], MessageHistory]],
tools: Optional[Sequence[Tool]],
) -> dict[str, Any]:
options = dict(self.options)
if tools:
# we want a tool back, remove generation_config if defined
options.pop("generation_config", None)
options["tools"] = self._get_llm_tools(tools)
if "tool_config" not in options:
options["tool_config"] = ToolConfig(
function_calling_config=ToolConfig.FunctionCallingConfig(
mode=ToolConfig.FunctionCallingConfig.Mode.ANY,
)
)
else:
# no tools, remove tool_config if defined
options.pop("tool_config", None)
messages = self.get_messages(input, message_history)
options["contents"] = messages
return options
def _get_call_params_v2(
self,
contents: list[Content],
tools: Optional[Sequence[Tool]],
response_format: Optional[Union[Type[BaseModel], dict[str, Any]]] = None,
**kwargs: Any,
) -> dict[str, Any]:
from vertexai.generative_models import GenerationConfig
options = dict(self.options)
if tools:
# we want a tool back, remove generation_config if defined
options.pop("generation_config", None)
options["tools"] = self._get_llm_tools(tools)
if "tool_config" not in options:
options["tool_config"] = ToolConfig(
function_calling_config=ToolConfig.FunctionCallingConfig(
mode=ToolConfig.FunctionCallingConfig.Mode.ANY,
)
)
else:
# no tools, remove tool_config if defined
options.pop("tool_config", None)
# Apply response_format and/or kwargs if provided
if response_format is not None or kwargs:
# Start with ALL existing params from constructor (including schema)
existing_config = options.get("generation_config")
params = _extract_generation_config_params(
existing_config, exclude_schema=False
)
# If response_format provided, override schema (prioritize it)
if response_format is not None:
# Convert to JSON schema
if isinstance(response_format, type) and issubclass(
response_format, BaseModel
):
# if we migrate to new google-genai-sdk, Pydantic models can be passed directly
schema = response_format.model_json_schema()
else:
schema = response_format
params["response_mime_type"] = "application/json"
params["response_schema"] = schema
# Apply kwargs (they override constructor values but preserve schema)
params.update(kwargs)
options["generation_config"] = GenerationConfig(**params)
options["contents"] = contents
return options
async def _acall_llm(
self,
input: str,
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
system_instruction: Optional[str] = None,
tools: Optional[Sequence[Tool]] = None,
) -> GenerationResponse:
model = self._get_model(system_instruction=system_instruction)
options = self._get_call_params(input, message_history, tools)
response = await model.generate_content_async(**options)
return response # type: ignore[no-any-return]
def _call_llm(
self,
input: str,
message_history: Optional[Union[List[LLMMessage], MessageHistory]] = None,
system_instruction: Optional[str] = None,
tools: Optional[Sequence[Tool]] = None,
) -> GenerationResponse:
model = self._get_model(system_instruction=system_instruction)
options = self._get_call_params(input, message_history, tools)
response = model.generate_content(**options)
return response # type: ignore[no-any-return]
def _to_tool_call(self, function_call: FunctionCall) -> ToolCall:
return ToolCall(
name=function_call.name,
arguments=function_call.args,
)
def _parse_tool_response(self, response: GenerationResponse) -> ToolCallResponse:
function_calls = response.candidates[0].function_calls
return ToolCallResponse(
tool_calls=[self._to_tool_call(f) for f in function_calls],
content=None,
)
def _parse_content_response(self, response: GenerationResponse) -> LLMResponse:
return LLMResponse(
content=response.text,
)