Module: GeminiExt::Cache

Defined in:
lib/geminiext/cache.rb

Class Method Summary collapse

Class Method Details

.create(contents:, display_name:, model: 'gemini-1.5-flash-001', ttl: 600) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/geminiext/cache.rb', line 6

def self.create(contents:, display_name:, model: 'gemini-1.5-flash-001', ttl: 600)
  content = {
    model: "models/#{model}",
    display_name:,
    contents:,
    ttl: "#{ttl}s"
  }.to_json

  conn = Faraday.new(
    url: 'https://generativelanguage.googleapis.com',
    headers: { 'Content-Type' => 'application/json' }
  )

  response = conn.post('/v1beta/cachedContents') do |req|
    req.params['key'] = ENV.fetch('GEMINI_API_KEY')
    req.body = content
  end

  return JSON.parse(response.body) if response.status == 200

  raise "Erro ao criar cache: #{response.status} - #{response.body}"
rescue Faraday::Error => e
  raise "Erro na requisição: #{e.message}"
end

.delete(name:) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/geminiext/cache.rb', line 105

def self.delete(name:)
  conn = Faraday.new(
    url: 'https://generativelanguage.googleapis.com',
    headers: { 'Content-Type' => 'application/json' }
  )

  response = conn.delete("/v1beta/#{name}") do |req|
    req.params['key'] = ENV.fetch('GEMINI_API_KEY')
  end

  return true if response.status == 200
  
  raise "Erro ao deletar cache: #{response.body}"
rescue Faraday::Error => e
  raise "Erro na requisição: #{e.message}"
end

.get(name: nil, display_name: nil) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/geminiext/cache.rb', line 31

def self.get(name: nil, display_name: nil)
  raise 'Nome do cache ou display name é obrigatório' if name.nil? && display_name.nil?
  raise 'Nome do cache e display name não podem ser informados juntos' if !name.nil? && !display_name.nil?
  
  return GeminiExt::Cache.list.find { |item| item['name'].eql? name } if !name.nil?
  return GeminiExt::Cache.list.find { |item| item['displayName'].eql? display_name } if !display_name.nil?
end

.listObject



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
# File 'lib/geminiext/cache.rb', line 39

def self.list
  conn = Faraday.new(
    url: 'https://generativelanguage.googleapis.com',
    headers: { 'Content-Type' => 'application/json' }
  )

  response = conn.get("/v1beta/cachedContents") do |req|
    req.params['key'] = ENV.fetch('GEMINI_API_KEY')
  end
  
  JSON.parse(response.body)['cachedContents'].map do |item|
    def item.delete = GeminiExt::Cache.delete(name: self['name'])
    def item.set_ttl(ttl = 120) = GeminiExt::Cache.update(name: self['name'], content: { ttl: "#{ttl}s" })

    def item.generate_content(contents:)
      conn = Faraday.new(
        url: 'https://generativelanguage.googleapis.com',
        headers: { 'Content-Type' => 'application/json' }
      )

      response = conn.post("/v1beta/models/#{self['model'].split('/').last}:generateContent") do |req|
        req.params['key'] = ENV.fetch('GEMINI_API_KEY')
        req.body = {
          contents:,
          cached_content: self['name']
        }.to_json
      end
      
      if response.status == 200
        resp = JSON.parse(response.body)
        def resp.content = dig('candidates', 0, 'content', 'parts', 0, 'text')
        return resp
      end

      raise "Erro ao gerar conteúdo: #{response.body}"
    rescue Faraday::Error => e
      raise "Erro na requisição: #{e.message}"
    end
    
    def item.single_prompt(prompt) = generate_content(contents: [{ parts: [{ text: prompt }], role: 'user' }])

    item
  end

rescue Faraday::Error => e
  raise "Erro na requisição: #{e.message}"
end

.update(name:, content:) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/geminiext/cache.rb', line 87

def self.update(name:, content:)
  conn = Faraday.new(
    url: 'https://generativelanguage.googleapis.com',
    headers: { 'Content-Type' => 'application/json' }
  )

  response = conn.patch("/v1beta/#{name}") do |req|
    req.params['key'] = ENV.fetch('GEMINI_API_KEY')
    req.body = content.to_json
  end

  return JSON.parse(response.body) if response.status == 200
  
  raise "Erro ao atualizar cache: #{response.body}"
rescue Faraday::Error => e
  raise "Erro na requisição: #{e.message}"
end