-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_gemini_stream.py
More file actions
149 lines (122 loc) · 4.29 KB
/
Copy pathtest_gemini_stream.py
File metadata and controls
149 lines (122 loc) · 4.29 KB
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
#!/usr/bin/env python3
import json
import os
import requests
from dotenv import load_dotenv
def print_openai_stream(response: requests.Response) -> str:
full_text = ""
for line in response.iter_lines():
if not line:
continue
line_text = line.decode("utf-8")
if not line_text.startswith("data: "):
continue
content = line_text[6:]
if content == "[DONE]":
print("\n[DONE]")
break
try:
response_json = json.loads(content)
except json.JSONDecodeError as error:
print(f"\nError parsing JSON: {error}")
print(f"Raw content: {content}")
continue
if "choices" in response_json and response_json["choices"]:
delta = response_json["choices"][0].get("delta", {})
if "content" in delta:
content_part = delta["content"]
full_text += content_part
print(content_part, end="", flush=True)
return full_text
def print_gemini_stream(response: requests.Response) -> str:
full_text = ""
for line in response.iter_lines():
if not line:
continue
line_text = line.decode("utf-8")
if not line_text.startswith("data: "):
continue
content = line_text[6:]
if content == "[DONE]":
print("\n[DONE]")
break
try:
response_json = json.loads(content)
except json.JSONDecodeError as error:
print(f"\nError parsing JSON: {error}")
print(f"Raw content: {content}")
continue
if "candidates" in response_json and response_json["candidates"]:
candidate = response_json["candidates"][0]
for part in candidate.get("content", {}).get("parts", []):
if "text" in part:
full_text += part["text"]
print(part["text"], end="", flush=True)
return full_text
def main() -> int:
load_dotenv()
admin_api_key = os.environ.get("ADMIN_API_KEY")
if not admin_api_key:
print("ERROR: ADMIN_API_KEY not found in environment variables")
return 1
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {admin_api_key}",
}
print("\nTesting Gemini proxy chat completions streaming...")
response = requests.post(
"http://localhost:1400/gemini/chat/completions",
headers=headers,
json={
"model": "gemini-2.0-flash",
"messages": [
{"role": "user", "content": "Write a short poem about AI assistants"},
],
"stream": True,
"temperature": 0.7,
},
stream=True,
)
if response.status_code == 200:
print("Streaming response:")
full_text = print_openai_stream(response)
print("\n\nFull generated text:")
print(full_text)
else:
print(f"Error: {response.status_code}")
print(response.text)
return 1
print("\nTesting Gemini direct model proxy streaming...")
response = requests.post(
"http://localhost:1400/gemini/v1beta/models/gemini-2.0-flash:generateContent",
headers=headers,
json={
"contents": [
{"parts": [{"text": "Write a short poem about programming"}]},
],
"stream": True,
"generationConfig": {
"temperature": 0.7,
},
"safetySettings": [
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
],
},
stream=True,
)
if response.status_code == 200:
print("Streaming response:")
full_text = print_gemini_stream(response)
print("\n\nFull generated text:")
print(full_text)
else:
print(f"Error: {response.status_code}")
print(response.text)
return 1
print("\nTests completed.")
return 0
if __name__ == "__main__":
raise SystemExit(main())