-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeminiwrapper.py
301 lines (219 loc) · 11 KB
/
geminiwrapper.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
from google.oauth2 import service_account
import google.ai.generativelanguage as glm
from google_labs_html_chunker.html_chunker import HtmlChunker
from urllib.request import urlopen
# stop the stupid logs
import os
# Suppress logging warnings
os.environ["GRPC_VERBOSITY"] = "ERROR"
os.environ["GLOG_minloglevel"] = "2"
class GeminiAQA:
def __init__(self) -> None:
service_account_file_name = 'programs/gemini/service_account_key.json'
credentials = service_account.Credentials.from_service_account_file(service_account_file_name)
scoped_credentials = credentials.with_scopes(
['https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/generative-language.retriever'])
self.generative_service_client = glm.GenerativeServiceClient(credentials=scoped_credentials)
self.retriever_service_client = glm.RetrieverServiceClient(credentials=scoped_credentials)
self.permission_service_client = glm.PermissionServiceClient(credentials=scoped_credentials)
def create_corpus(self, display_name, resource_name=None):
"""
Creates a new corpus with the given display name.
Parameters:
display_name (str): The display name for the new corpus.
Returns:
str: The name of the created corpus resource.
"""
example_corpus = glm.Corpus(display_name=display_name, name=resource_name if resource_name else None)
create_corpus_request = glm.CreateCorpusRequest(corpus=example_corpus)
# Make the request
create_corpus_response = self.retriever_service_client.create_corpus(create_corpus_request)
# Set the `corpus_resource_name` for subsequent sections.
corpus_resource_name = create_corpus_response.name
corpus = Corpus(corpus_resource_name, self)
return corpus
def list_corpora(self):
"""
Fetches a list of corpora from the retriever service client.
Returns:
The response containing the list of corpora. -- Keep in mind it has more than just resource names!
"""
list_corpus_request = glm.ListCorporaRequest()
list_corpus_response = self.retriever_service_client.list_corpora(list_corpus_request)
return list_corpus_response
def delete_corpus(self, corpus_resource_name):
"""
Deletes a corpus resource from the retriever service client.
Args:
corpus_resource_name (str): The name of the corpus resource to delete.
Returns:
google.longrunning.operations_pb2.Operation: The response from the deletion operation.
"""
delete_corpus_request = glm.DeleteCorpusRequest(name=corpus_resource_name)
delete_corpus_response = self.retriever_service_client.delete_corpus(delete_corpus_request)
return delete_corpus_response
def get_corpus(self, corpus_resource_name):
"""
Retrieves a corpus resource from the retriever service client.
Args:
corpus_resource_name (str): The name of the corpus resource to retrieve.
Returns:
Corpus: The retrieved corpus resource.
"""
return Corpus(corpus_resource_name, self)
class Corpus:
def __init__(self, corpus_resource_name, GeminiAQA) -> None:
self.corpus_resource_name = corpus_resource_name
self.GeminiAQA = GeminiAQA
# Print the response
def get_display_name(self):
"""
Retrieves the display name of a corpus.
Returns:
str: The display name of the corpus.
"""
get_corpus_request = glm.GetCorpusRequest(name=self.corpus_resource_name)
response = self.GeminiAQA.retriever_service_client.get_corpus(get_corpus_request)
return response.display_name
def list_documents(self):
"""
Retrieves a list of documents in a corpus.
Returns:
list: A list of document names.
"""
list_documents_request = glm.ListDocumentsRequest(parent=self.corpus_resource_name)
response = self.GeminiAQA.retriever_service_client.list_documents(list_documents_request)
return response
def create_document(self, document_display_name, document_resource_name=None, metadata=None):
"""
Creates a new document in a corpus.
Args:
document_display_name (str): The display name of the new document.
document_resource_name (str, optional): The name of the document resource. Defaults to None.
metadata (dict, optional): The metadata of the document. Defaults to None.
Returns:
Document: The created document.
"""
if metadata is not None:
document_metadata = []
for key, value in metadata.items():
document_metadata.append(glm.CustomMetadata(key=key, string_value=value))
document = glm.Document(display_name=document_display_name, name=document_resource_name if document_resource_name else None)
if metadata is not None:
document.custom_metadata.extend(document_metadata)
create_document_request = glm.CreateDocumentRequest(document=document, parent=self.corpus_resource_name)
create_document_response = self.GeminiAQA.retriever_service_client.create_document(create_document_request)
return Document(create_document_response.name, self)
def generate_answer(self, user_query, mode="ABSTRACTIVE"): # or EXTRACTIVE or VERBOSE
"""
Generates an answer to a given text.
Args:
user_query (str): The text to generate an answer for.
mode (str, optional): The mode of the answer. Defaults to "ABSTRACTIVE".
Returns:
str: The generated answer.
"""
model = "models/aqa"
content = glm.Content(parts=[glm.Part(text=user_query)])
retriever_config = glm.SemanticRetrieverConfig(source=self.corpus_resource_name, query=content)
req = glm.GenerateAnswerRequest(model=model,
contents=[content],
semantic_retriever=retriever_config,
answer_style=mode)
aqa_response = self.GeminiAQA.generative_service_client.generate_answer(req)
return aqa_response
def delete_document(self, document_resource_name):
"""
Deletes a document resource from the retriever service client.
Args:
document_resource_name (str): The name of the document resource to delete.
Returns:
google.longrunning.operations_pb2.Operation: The response from the deletion operation.
"""
delete_document_request = glm.DeleteDocumentRequest(name=document_resource_name)
delete_document_response = self.GeminiAQA.retriever_service_client.delete_document(delete_document_request)
return delete_document_response
class Document:
def __init__(self, document_resource_name, corpus) -> None:
self.document_resource_name = document_resource_name
self.corpus = corpus
def list_chunks(self):
list_chunks_request = glm.ListChunksRequest(parent=self.document_resource_name)
response = self.corpus.GeminiAQA.retriever_service_client.list_chunks(list_chunks_request)
return response
def delete_chunk(self, chunk_resource_name):
"""
Deletes a chunk resource from the retriever service client.
Args:
chunk_resource_name (str): The name of the chunk resource to delete.
Returns:
google.longrunning.operations_pb2.Operation: The response from the deletion operation.
"""
delete_chunk_request = glm.DeleteChunkRequest(name=chunk_resource_name)
delete_chunk_response = self.corpus.GeminiAQA.retriever_service_client.delete_chunk(delete_chunk_request)
return delete_chunk_response
def ingest_chunk(self, text):
"""
Ingests a chunk of text into a document.
Args:
text (str): The text to ingest.
Returns:
google.longrunning.operations_pb2.Operation: The response from the ingestion operation.
"""
if len(text) < 200:
chunk = glm.Chunk(data={"string_value": text})
create_chunk_request = glm.CreateChunkRequest(chunk=chunk, parent=self.document_resource_name)
response = self.corpus.GeminiAQA.retriever_service_client.create_chunk(create_chunk_request)
else:
passages = [text[i:i+400] for i in range(0, len(text), 400)]
chunks= []
for passsage in passages:
chunk = glm.Chunk(data={"string_value": passsage})
chunks.append(chunk)
create_chunk_requests = []
for chunk in chunks:
create_chunk_requests.append(glm.CreateChunkRequest(parent=self.document_resource_name, chunk=chunk))
# Make the request
# Split create_chunk_requests into batches of 100
batched_requests = [create_chunk_requests[i:i + 100] for i in range(0, len(create_chunk_requests), 100)]
for batch in batched_requests:
request = glm.BatchCreateChunksRequest(parent=self.document_resource_name, requests=batch)
response = self.corpus.GeminiAQA.retriever_service_client.batch_create_chunks(request)
return response
def ingest_url(self, url):
with(urlopen(url)) as f:
html = f.read().decode("utf-8")
chunker = HtmlChunker(
max_words_per_aggregate_passage=200,
greedily_aggregate_sibling_nodes=True,
html_tags_to_exclude={"noscript", "script", "style"},
)
passages = chunker.chunk(html)
print(passages)
chunks = []
for passage in passages:
chunk = glm.Chunk(data={'string_value': passage})
chunks.append(chunk)
create_chunk_requests = []
for chunk in chunks:
create_chunk_requests.append(glm.CreateChunkRequest(parent=self.document_resource_name, chunk=chunk))
# Make the request
# Split create_chunk_requests into batches of 100
batched_requests = [create_chunk_requests[i:i + 100] for i in range(0, len(create_chunk_requests), 100)]
for batch in batched_requests:
request = glm.BatchCreateChunksRequest(parent=self.document_resource_name, requests=batch)
response = self.corpus.GeminiAQA.retriever_service_client.batch_create_chunks(request)
return response
def ingest_wikipedia(self, wikipedia_url):
"""
Ingests a Wikipedia article into a document.
Args:
wikipedia_url (str): The URL of the Wikipedia article.
Returns:
google.longrunning.operations_pb2.Operation: The response from the ingestion operation.
"""
import wikipedia
article = wikipedia.page(wikipedia_url)
text = article.content
# return text
return self.ingest_chunk(text)