2024-07-10 23:20:06 +01:00
|
|
|
"""
|
2024-07-12 15:12:40 +01:00
|
|
|
Simple LLM service, performs text prompt completion using VertexAI on
|
|
|
|
|
Google Cloud. Input is prompt, output is response.
|
2025-08-19 13:00:22 -07:00
|
|
|
Supports both Google's Gemini models and Anthropic's Claude models.
|
2024-07-10 23:20:06 +01:00
|
|
|
"""
|
|
|
|
|
|
2025-05-24 12:09:43 +01:00
|
|
|
#
|
|
|
|
|
# Somewhat perplexed by the Google Cloud SDK choices. We're going off this
|
|
|
|
|
# one, which uses the google-cloud-aiplatform library:
|
|
|
|
|
# https://cloud.google.com/python/docs/reference/vertexai/1.94.0
|
|
|
|
|
# It seems it is possible to invoke VertexAI from the google-genai
|
|
|
|
|
# SDK too:
|
|
|
|
|
# https://googleapis.github.io/python-genai/genai.html#module-genai.client
|
|
|
|
|
# That would make this code look very much like the GoogleAIStudio
|
|
|
|
|
# code. And maybe not reliant on the google-cloud-aiplatform library?
|
|
|
|
|
#
|
|
|
|
|
# This module's imports bring in a lot of libraries.
|
|
|
|
|
|
2024-07-10 23:20:06 +01:00
|
|
|
from google.oauth2 import service_account
|
2025-08-19 13:00:22 -07:00
|
|
|
import google.auth
|
2025-09-24 16:36:25 +01:00
|
|
|
import google.api_core.exceptions
|
2025-04-22 20:21:38 +01:00
|
|
|
import vertexai
|
2025-07-30 23:18:38 +01:00
|
|
|
import logging
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-05-24 12:09:43 +01:00
|
|
|
# Why is preview here?
|
|
|
|
|
from vertexai.generative_models import (
|
2025-04-22 20:21:38 +01:00
|
|
|
Content, FunctionDeclaration, GenerativeModel, GenerationConfig,
|
2025-05-24 12:09:43 +01:00
|
|
|
HarmCategory, HarmBlockThreshold, Part, Tool, SafetySetting,
|
2024-07-10 23:20:06 +01:00
|
|
|
)
|
|
|
|
|
|
2025-08-19 13:00:22 -07:00
|
|
|
# Added for Anthropic model support
|
|
|
|
|
from anthropic import AnthropicVertex, RateLimitError
|
|
|
|
|
|
2024-08-19 22:15:32 +01:00
|
|
|
from .... exceptions import TooManyRequests
|
2025-04-22 20:21:38 +01:00
|
|
|
from .... base import LlmService, LlmResult
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-07-30 23:18:38 +01:00
|
|
|
# Module logger
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
default_ident = "text-completion"
|
2024-07-23 21:34:03 +01:00
|
|
|
|
2025-08-19 13:00:22 -07:00
|
|
|
default_model = 'gemini-1.5-flash-001'
|
2024-08-21 16:03:56 -07:00
|
|
|
default_region = 'us-central1'
|
|
|
|
|
default_temperature = 0.0
|
|
|
|
|
default_max_output = 8192
|
2024-10-15 20:02:21 +01:00
|
|
|
default_private_key = "private.json"
|
2024-07-15 17:17:04 +01:00
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
class Processor(LlmService):
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-07-18 17:20:42 +01:00
|
|
|
def __init__(self, **params):
|
|
|
|
|
|
2024-08-21 16:03:56 -07:00
|
|
|
region = params.get("region", default_region)
|
|
|
|
|
model = params.get("model", default_model)
|
2024-10-15 00:34:52 +01:00
|
|
|
private_key = params.get("private_key", default_private_key)
|
2024-08-21 16:03:56 -07:00
|
|
|
temperature = params.get("temperature", default_temperature)
|
|
|
|
|
max_output = params.get("max_output", default_max_output)
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-10-15 00:34:52 +01:00
|
|
|
if private_key is None:
|
2025-08-19 13:00:22 -07:00
|
|
|
logger.warning("Private key file not specified, using Application Default Credentials")
|
2024-10-15 00:34:52 +01:00
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
super(Processor, self).__init__(**params)
|
2024-08-26 11:46:36 +01:00
|
|
|
|
2025-09-24 16:36:25 +01:00
|
|
|
# Store default model and configuration parameters
|
|
|
|
|
self.default_model = model
|
|
|
|
|
self.region = region
|
|
|
|
|
self.temperature = temperature
|
|
|
|
|
self.max_output = max_output
|
|
|
|
|
self.private_key = private_key
|
|
|
|
|
|
|
|
|
|
# Model client caches
|
|
|
|
|
self.model_clients = {} # Cache for model instances
|
|
|
|
|
self.generation_configs = {} # Cache for generation configs (Gemini only)
|
|
|
|
|
self.anthropic_client = None # Single Anthropic client (handles multiple models)
|
2025-08-19 13:00:22 -07:00
|
|
|
|
|
|
|
|
# Shared parameters for both model types
|
|
|
|
|
self.api_params = {
|
2024-08-21 16:03:56 -07:00
|
|
|
"temperature": temperature,
|
2024-07-10 23:20:06 +01:00
|
|
|
"top_p": 1.0,
|
|
|
|
|
"top_k": 32,
|
2024-08-21 16:03:56 -07:00
|
|
|
"max_output_tokens": max_output,
|
2024-07-10 23:20:06 +01:00
|
|
|
}
|
|
|
|
|
|
2025-07-30 23:18:38 +01:00
|
|
|
logger.info("Initializing VertexAI...")
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-08-19 13:00:22 -07:00
|
|
|
# Unified credential and project ID loading
|
2024-07-17 17:18:24 +01:00
|
|
|
if private_key:
|
2025-04-22 20:21:38 +01:00
|
|
|
credentials = (
|
|
|
|
|
service_account.Credentials.from_service_account_file(
|
|
|
|
|
private_key
|
|
|
|
|
)
|
|
|
|
|
)
|
2025-08-19 13:00:22 -07:00
|
|
|
project_id = credentials.project_id
|
2024-07-17 17:18:24 +01:00
|
|
|
else:
|
2025-08-19 13:00:22 -07:00
|
|
|
credentials, project_id = google.auth.default()
|
2024-07-17 17:18:24 +01:00
|
|
|
|
2025-08-19 13:00:22 -07:00
|
|
|
if not project_id:
|
|
|
|
|
raise RuntimeError(
|
|
|
|
|
"Could not determine Google Cloud project ID. "
|
|
|
|
|
"Ensure it's set in your environment or service account."
|
2024-07-10 23:20:06 +01:00
|
|
|
)
|
2025-08-19 13:00:22 -07:00
|
|
|
|
2025-09-24 16:36:25 +01:00
|
|
|
# Store credentials and project info for later use
|
|
|
|
|
self.credentials = credentials
|
|
|
|
|
self.project_id = project_id
|
|
|
|
|
|
|
|
|
|
# Initialize Vertex AI SDK for Gemini models
|
|
|
|
|
init_kwargs = {'location': region, 'project': project_id}
|
|
|
|
|
if credentials and private_key: # Pass credentials only if from a file
|
|
|
|
|
init_kwargs['credentials'] = credentials
|
|
|
|
|
|
|
|
|
|
vertexai.init(**init_kwargs)
|
|
|
|
|
|
|
|
|
|
# Pre-initialize Anthropic client if needed (single client handles all Claude models)
|
|
|
|
|
if 'claude' in self.default_model.lower():
|
|
|
|
|
self._get_anthropic_client()
|
|
|
|
|
|
|
|
|
|
# Safety settings for Gemini models
|
|
|
|
|
block_level = HarmBlockThreshold.BLOCK_ONLY_HIGH
|
|
|
|
|
self.safety_settings = [
|
|
|
|
|
SafetySetting(
|
|
|
|
|
category = HarmCategory.HARM_CATEGORY_HARASSMENT,
|
|
|
|
|
threshold = block_level,
|
|
|
|
|
),
|
|
|
|
|
SafetySetting(
|
|
|
|
|
category = HarmCategory.HARM_CATEGORY_HATE_SPEECH,
|
|
|
|
|
threshold = block_level,
|
|
|
|
|
),
|
|
|
|
|
SafetySetting(
|
|
|
|
|
category = HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
|
|
|
|
|
threshold = block_level,
|
|
|
|
|
),
|
|
|
|
|
SafetySetting(
|
|
|
|
|
category = HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
|
|
|
|
|
threshold = block_level,
|
|
|
|
|
),
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
logger.info("VertexAI initialization complete")
|
|
|
|
|
|
|
|
|
|
def _get_anthropic_client(self):
|
|
|
|
|
"""Get or create the Anthropic client (single client for all Claude models)"""
|
|
|
|
|
if self.anthropic_client is None:
|
|
|
|
|
logger.info(f"Initializing AnthropicVertex client")
|
|
|
|
|
anthropic_kwargs = {'region': self.region, 'project_id': self.project_id}
|
|
|
|
|
if self.credentials and self.private_key: # Pass credentials only if from a file
|
|
|
|
|
anthropic_kwargs['credentials'] = self.credentials
|
|
|
|
|
logger.debug(f"Using service account credentials for Anthropic models")
|
2025-08-19 13:00:22 -07:00
|
|
|
else:
|
2025-09-24 16:36:25 +01:00
|
|
|
logger.debug(f"Using Application Default Credentials for Anthropic models")
|
|
|
|
|
|
|
|
|
|
self.anthropic_client = AnthropicVertex(**anthropic_kwargs)
|
|
|
|
|
|
|
|
|
|
return self.anthropic_client
|
|
|
|
|
|
2025-09-25 21:26:11 +01:00
|
|
|
def _get_gemini_model(self, model_name, temperature=None):
|
2025-09-24 16:36:25 +01:00
|
|
|
"""Get or create a Gemini model instance"""
|
|
|
|
|
if model_name not in self.model_clients:
|
|
|
|
|
logger.info(f"Creating GenerativeModel instance for '{model_name}'")
|
|
|
|
|
self.model_clients[model_name] = GenerativeModel(model_name)
|
|
|
|
|
|
2025-09-25 21:26:11 +01:00
|
|
|
# Use provided temperature or fall back to default
|
|
|
|
|
effective_temperature = temperature if temperature is not None else self.temperature
|
|
|
|
|
|
|
|
|
|
# Create generation config with the effective temperature
|
|
|
|
|
generation_config = GenerationConfig(
|
|
|
|
|
temperature=effective_temperature,
|
|
|
|
|
top_p=1.0,
|
|
|
|
|
top_k=10,
|
|
|
|
|
candidate_count=1,
|
|
|
|
|
max_output_tokens=self.max_output,
|
|
|
|
|
)
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-09-25 21:26:11 +01:00
|
|
|
return self.model_clients[model_name], generation_config
|
2025-08-19 13:00:22 -07:00
|
|
|
|
2025-09-25 21:26:11 +01:00
|
|
|
async def generate_content(self, system, prompt, model=None, temperature=None):
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-09-24 16:36:25 +01:00
|
|
|
# Use provided model or fall back to default
|
|
|
|
|
model_name = model or self.default_model
|
2025-09-25 21:26:11 +01:00
|
|
|
# Use provided temperature or fall back to default
|
|
|
|
|
effective_temperature = temperature if temperature is not None else self.temperature
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-09-24 16:36:25 +01:00
|
|
|
logger.debug(f"Using model: {model_name}")
|
2025-09-25 21:26:11 +01:00
|
|
|
logger.debug(f"Using temperature: {effective_temperature}")
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-07-17 17:18:24 +01:00
|
|
|
try:
|
2025-09-24 16:36:25 +01:00
|
|
|
if 'claude' in model_name.lower():
|
2025-08-19 13:00:22 -07:00
|
|
|
# Anthropic API uses a dedicated system prompt
|
2025-09-24 16:36:25 +01:00
|
|
|
logger.debug(f"Sending request to Anthropic model '{model_name}'...")
|
|
|
|
|
client = self._get_anthropic_client()
|
|
|
|
|
|
|
|
|
|
response = client.messages.create(
|
|
|
|
|
model=model_name,
|
2025-08-19 13:00:22 -07:00
|
|
|
system=system,
|
|
|
|
|
messages=[{"role": "user", "content": prompt}],
|
|
|
|
|
max_tokens=self.api_params['max_output_tokens'],
|
2025-09-25 21:26:11 +01:00
|
|
|
temperature=effective_temperature,
|
2025-08-19 13:00:22 -07:00
|
|
|
top_p=self.api_params['top_p'],
|
|
|
|
|
top_k=self.api_params['top_k'],
|
|
|
|
|
)
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-08-19 13:00:22 -07:00
|
|
|
resp = LlmResult(
|
|
|
|
|
text=response.content[0].text,
|
|
|
|
|
in_token=response.usage.input_tokens,
|
|
|
|
|
out_token=response.usage.output_tokens,
|
2025-09-24 16:36:25 +01:00
|
|
|
model=model_name
|
2025-08-19 13:00:22 -07:00
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
# Gemini API combines system and user prompts
|
2025-09-24 16:36:25 +01:00
|
|
|
logger.debug(f"Sending request to Gemini model '{model_name}'...")
|
2025-08-19 13:00:22 -07:00
|
|
|
full_prompt = system + "\n\n" + prompt
|
|
|
|
|
|
2025-09-25 21:26:11 +01:00
|
|
|
llm, generation_config = self._get_gemini_model(model_name, effective_temperature)
|
2025-09-24 16:36:25 +01:00
|
|
|
|
|
|
|
|
response = llm.generate_content(
|
|
|
|
|
full_prompt, generation_config = generation_config,
|
2025-08-19 13:00:22 -07:00
|
|
|
safety_settings = self.safety_settings,
|
|
|
|
|
)
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-08-19 13:00:22 -07:00
|
|
|
resp = LlmResult(
|
|
|
|
|
text = response.text,
|
|
|
|
|
in_token = response.usage_metadata.prompt_token_count,
|
|
|
|
|
out_token = response.usage_metadata.candidates_token_count,
|
2025-09-24 16:36:25 +01:00
|
|
|
model = model_name
|
2025-08-19 13:00:22 -07:00
|
|
|
)
|
2024-08-26 11:46:36 +01:00
|
|
|
|
2025-07-30 23:18:38 +01:00
|
|
|
logger.info(f"Input Tokens: {resp.in_token}")
|
|
|
|
|
logger.info(f"Output Tokens: {resp.out_token}")
|
|
|
|
|
logger.debug("Send response...")
|
2024-08-22 17:02:18 +01:00
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
return resp
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-08-19 13:00:22 -07:00
|
|
|
except (google.api_core.exceptions.ResourceExhausted, RateLimitError) as e:
|
2025-07-30 23:18:38 +01:00
|
|
|
logger.warning(f"Hit rate limit: {e}")
|
2025-01-27 17:04:49 +00:00
|
|
|
# Leave rate limit retries to the base handler
|
|
|
|
|
raise TooManyRequests()
|
2024-07-15 17:17:04 +01:00
|
|
|
|
2024-08-22 17:02:18 +01:00
|
|
|
except Exception as e:
|
2025-01-27 17:04:49 +00:00
|
|
|
# Apart from rate limits, treat all exceptions as unrecoverable
|
2025-07-30 23:18:38 +01:00
|
|
|
logger.error(f"VertexAI LLM exception: {e}", exc_info=True)
|
2025-04-22 20:21:38 +01:00
|
|
|
raise e
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-07-17 17:18:24 +01:00
|
|
|
@staticmethod
|
|
|
|
|
def add_args(parser):
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
LlmService.add_args(parser)
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-07-17 17:18:24 +01:00
|
|
|
parser.add_argument(
|
|
|
|
|
'-m', '--model',
|
2024-08-21 16:03:56 -07:00
|
|
|
default=default_model,
|
2025-08-19 13:00:22 -07:00
|
|
|
help=f'LLM model (e.g., gemini-1.5-flash-001, claude-3-sonnet@20240229) (default: {default_model})'
|
2024-07-17 17:18:24 +01:00
|
|
|
)
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-07-17 17:18:24 +01:00
|
|
|
parser.add_argument(
|
|
|
|
|
'-k', '--private-key',
|
2025-08-19 13:00:22 -07:00
|
|
|
help=f'Google Cloud private JSON file (optional, uses ADC if not provided)'
|
2024-07-17 17:18:24 +01:00
|
|
|
)
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-07-17 17:18:24 +01:00
|
|
|
parser.add_argument(
|
|
|
|
|
'-r', '--region',
|
2024-08-21 16:03:56 -07:00
|
|
|
default=default_region,
|
|
|
|
|
help=f'Google Cloud region (default: {default_region})',
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
'-t', '--temperature',
|
|
|
|
|
type=float,
|
|
|
|
|
default=default_temperature,
|
|
|
|
|
help=f'LLM temperature parameter (default: {default_temperature})'
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
'-x', '--max-output',
|
|
|
|
|
type=int,
|
|
|
|
|
default=default_max_output,
|
|
|
|
|
help=f'LLM max output tokens (default: {default_max_output})'
|
2024-07-17 17:18:24 +01:00
|
|
|
)
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-07-17 17:18:24 +01:00
|
|
|
def run():
|
2025-10-11 11:46:03 +01:00
|
|
|
Processor.launch(default_ident, __doc__)
|