-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgemini-universal.py
256 lines (218 loc) · 8.45 KB
/
gemini-universal.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
import json
import os
from dotenv import load_dotenv
# The official OpenAI Python library with Gemini support (via Javelin)
from openai import OpenAI
from pydantic import BaseModel
from javelin_sdk import JavelinClient, JavelinConfig
load_dotenv()
# -----------------------------------------------------------------------------
# 1) Initialize Gemini + Javelin
# -----------------------------------------------------------------------------
def init_gemini_client():
"""
Sets environment variables for Gemini and Javelin, creates an OpenAI client,
registers it with Javelin, and returns the configured client.
"""
print("Initializing Gemini client...")
# Hard-coded environment variable assignment (for demonstration)
# You may prefer to do: gemini_api_key = os.environ.get("GEMINI_API_KEY") in real usage.
gemini_api_key = os.getenv("GEMINI_API_KEY") # define your gemini api key here
if not gemini_api_key:
raise ValueError("GEMINI_API_KEY is not set!")
print("Gemini API Key loaded successfully.")
# Create an OpenAI client configured for Gemini
openai_client = OpenAI(
api_key=gemini_api_key,
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
)
# Javelin configuration
javelin_api_key = os.getenv("JAVELIN_API_KEY") # define your javelin api key here
config = JavelinConfig(javelin_api_key=javelin_api_key)
client = JavelinClient(config)
rout_name = "google_univ" # define your universal route name here
# Register the Gemini client with Javelin
client.register_gemini(openai_client, route_name=rout_name)
return openai_client
# -----------------------------------------------------------------------------
# 2) Chat Completions
# -----------------------------------------------------------------------------
def gemini_chat_completions(client):
"""
Demonstrates a basic chat completion with Gemini.
Returns the JSON string of the response.
"""
response = client.chat.completions.create(
model="gemini-1.5-flash",
n=1,
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain to me how AI works"},
],
)
return response.model_dump_json(indent=2)
# -----------------------------------------------------------------------------
# 3) Streaming
# -----------------------------------------------------------------------------
def gemini_streaming(client):
"""
Demonstrates streaming a response from Gemini.
Returns a concatenated string of all streamed tokens for demonstration.
"""
response = client.chat.completions.create(
model="gemini-1.5-flash",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"},
],
stream=True,
)
# Accumulate partial content in a list
streamed_content = []
for chunk in response:
if chunk.choices and chunk.choices[0].delta:
delta_content = chunk.choices[0].delta
# If delta_content has a .dict() method (e.g. it's a Pydantic model), use it.
if hasattr(delta_content, "dict"):
dumped = json.dumps(delta_content.dict())
else:
dumped = json.dumps(delta_content)
streamed_content.append(dumped)
# Join all chunk data with newlines
return "\n".join(streamed_content)
# -----------------------------------------------------------------------------
# 4) Function calling
# -----------------------------------------------------------------------------
def gemini_function_calling(client):
"""
Demonstrates a function-calling scenario with Gemini (like OpenAI Tools).
Returns JSON string of the response.
"""
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. Chicago, IL",
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["location"],
},
},
}
]
messages = [
{"role": "user", "content": "What's the weather like in Chicago today?"}
]
response = client.chat.completions.create(
model="gemini-1.5-flash", messages=messages, tools=tools, tool_choice="auto"
)
return response.model_dump_json(indent=2)
# -----------------------------------------------------------------------------
# 5) Structured output
# -----------------------------------------------------------------------------
class CalendarEvent(BaseModel):
name: str
date: str
participants: list[str]
def gemini_structured_output(client):
"""
Demonstrates how to request structured JSON output from Gemini
using the 'parse' endpoint (beta).
Returns the JSON string of the structured result.
"""
completion = client.beta.chat.completions.parse(
model="gemini-1.5-flash",
messages=[
{"role": "system", "content": "Extract the event information."},
{
"role": "user",
"content": "John and Susan are going to an AI conference on Friday.",
},
],
response_format=CalendarEvent,
)
return completion.model_dump_json(indent=2)
# -----------------------------------------------------------------------------
# 6) Embeddings
# -----------------------------------------------------------------------------
def gemini_embeddings(client):
"""
Demonstrates generating embeddings using Gemini.
Returns the JSON string of the embeddings response.
"""
response = client.embeddings.create(
input="Your text string goes here", model="text-embedding-004"
)
return response.model_dump_json(indent=2)
# -----------------------------------------------------------------------------
# 7) Main
# -----------------------------------------------------------------------------
def main():
print("=== Gemini Example ===")
try:
gemini_client = init_gemini_client()
except Exception as e:
print(f"Error initializing Gemini client: {e}")
return
# 1) Chat Completions
# print("\n--- Gemini: Chat Completions ---")
# try:
# chat_response = gemini_chat_completions(gemini_client)
# if not chat_response.strip():
# print("Error: Empty response failed")
# else:
# print(chat_response)
# except Exception as e:
# print(f"Error in chat completions: {e}")
# 2) Streaming
print("\n--- Gemini: Streaming ---")
try:
stream_response = gemini_streaming(gemini_client)
if not stream_response.strip():
print("Error: Empty response failed")
else:
print("Streaming output:")
print(stream_response)
except Exception as e:
print(f"Error in streaming: {e}")
# # 3) Function Calling
# print("\n--- Gemini: Function Calling ---")
# try:
# func_response = gemini_function_calling(gemini_client)
# if not func_response.strip():
# print("Error: Empty response failed")
# else:
# print(func_response)
# except Exception as e:
# print(f"Error in function calling: {e}")
# # 4) Structured Output
# print("\n--- Gemini: Structured Output ---")
# try:
# structured_response = gemini_structured_output(gemini_client)
# if not structured_response.strip():
# print("Error: Empty response failed")
# else:
# print(structured_response)
# except Exception as e:
# print(f"Error in structured output: {e}")
# # 5) Embeddings
# print("\n--- Gemini: Embeddings ---")
# try:
# embeddings_response = gemini_embeddings(gemini_client)
# if not embeddings_response.strip():
# print("Error: Empty response failed")
# else:
# print(embeddings_response)
# except Exception as e:
# print(f"Error in embeddings: {e}")
print("\nScript Complete")
if __name__ == "__main__":
main()