Class: Prescient::Provider::Gemini

Inherits:
Base
  • Object
show all
Includes:
HTTParty
Defined in:
lib/prescient/provider/gemini.rb

Overview

Google Gemini API provider adapter.

Instance Attribute Summary

Attributes inherited from Base

#options, #provider_name

Instance Method Summary collapse

Methods inherited from Base

#available?, #build_prompt, #clean_text, #default_context_configs, #default_prompt_templates, #extract_embedding_text, #extract_text_values, #format_context_item, #handle_errors, #validate_embedding_dimensions

Constructor Details

#initialize(**options) ⇒ Gemini

Returns a new instance of Gemini.



13
14
15
16
17
# File 'lib/prescient/provider/gemini.rb', line 13

def initialize(**options)
  super
  @provider_name = "Google Gemini"
  self.class.default_timeout(@options[:timeout] || 60)
end

Instance Method Details

#generate_embedding(text, **options) ⇒ Array<Float>

Generate an embedding through Gemini's embedContent endpoint.

Parameters:

  • text (String)

    Text to embed

Returns:

  • (Array<Float>)

    Embedding vector



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/prescient/provider/gemini.rb', line 22

def generate_embedding(text, **options)
  handle_errors do
    embedding_model = options[:model] || @options[:embedding_model]
    response = self.class.post(
      model_endpoint(embedding_model, "embedContent"),
      headers: api_headers,
      body: {
        content: { parts: [{ text: clean_text(text) }] }
      }.to_json
    )

    validate_response!(response, "embedding generation")

    embedding = response.parsed_response.dig("embedding", "values")
    raise Prescient::InvalidResponseError, "No embedding returned" unless embedding.is_a?(Array)

    expected_dimensions = @options[:embedding_dimensions]
    expected_dimensions ? validate_embedding_dimensions(embedding, expected_dimensions) : embedding
  end
end

#generate_response(prompt, context_items = [], **options) ⇒ Hash

Generate a response through Gemini's generateContent endpoint.

Parameters:

  • prompt (String)

    Prompt to send

  • context_items (Array<Hash, String>) (defaults to: [])

    Optional context items

Returns:

  • (Hash)

    Normalized response data



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
# File 'lib/prescient/provider/gemini.rb', line 47

def generate_response(prompt, context_items = [], **options)
  handle_errors do
    model = options[:model] || @options[:chat_model]
    response = self.class.post(
      model_endpoint(model, "generateContent"),
      headers: api_headers,
      body: {
        contents: [{ role: "user", parts: [{ text: build_prompt(prompt, context_items) }] }],
        generationConfig: {
          maxOutputTokens: options[:max_tokens] || 2000,
          temperature: options[:temperature] || 0.7,
          topP: options[:top_p] || 0.9
        }
      }.to_json
    )

    validate_response!(response, "text generation")

    parsed_response = response.parsed_response
    parts = parsed_response.dig("candidates", 0, "content", "parts")
    content = Array(parts).filter_map { |part| part["text"] }.join
    raise Prescient::InvalidResponseError, "No response generated" if content.nil? || content.empty?

    {
      response: content.strip,
      model: model,
      provider: "gemini",
      processing_time: nil,
      metadata: {
        usage: parsed_response["usageMetadata"],
        finish_reason: parsed_response.dig("candidates", 0, "finishReason")
      }
    }
  end
end

#health_checkHash

Check whether the configured Gemini models are available.

Returns:

  • (Hash)

    Provider health information



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
# File 'lib/prescient/provider/gemini.rb', line 85

def health_check
  handle_errors do
    response = self.class.get("/v1beta/models", headers: api_headers)

    if response.success?
      models = response.parsed_response["models"] || []
      embedding_model = find_model(models, @options[:embedding_model], "embedContent")
      chat_model = find_model(models, @options[:chat_model], "generateContent")

      {
        status: "healthy",
        provider: "gemini",
        reachable: true,
        models_available: models.map { |model| model["name"].to_s.delete_prefix("models/") },
        embedding_model: { name: @options[:embedding_model], available: embedding_model },
        chat_model: { name: @options[:chat_model], available: chat_model },
        ready: embedding_model && chat_model
      }
    else
      {
        status: "unhealthy",
        provider: "gemini",
        reachable: true,
        error: "HTTP #{response.code}",
        message: response.message,
        ready: false
      }
    end
  end
rescue Prescient::Error => e
  {
    status: "unavailable",
    provider: "gemini",
    reachable: false,
    error: e.class.name,
    message: e.message,
    ready: false
  }
end

#list_modelsArray<Hash>

List models available to the configured Gemini API key.

Returns:

  • (Array<Hash>)

    Model descriptors



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/prescient/provider/gemini.rb', line 127

def list_models
  handle_errors do
    response = self.class.get("/v1beta/models", headers: api_headers)
    validate_response!(response, "model listing")

    (response.parsed_response["models"] || []).map do |model|
      {
        name: model["name"].to_s.delete_prefix("models/"),
        display_name: model["displayName"],
        supported_generation_modes: model["supportedGenerationMethods"],
        input_token_limit: model["inputTokenLimit"],
        output_token_limit: model["outputTokenLimit"]
      }.compact
    end
  end
end

#validate_configuration!Object (protected)

Raises:



146
147
148
149
150
151
152
153
# File 'lib/prescient/provider/gemini.rb', line 146

def validate_configuration!
  required_options = %i[api_key embedding_model chat_model]
  missing_options = required_options.select { |option| @options[option].nil? }

  return unless missing_options.any?

  raise Prescient::Error, "Missing required options: #{missing_options.join(", ")}"
end