forked from GoogleCloudPlatform/generative-ai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
99 lines (78 loc) · 3.15 KB
/
main.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
import asyncio
import json
import websockets
from websockets.legacy.protocol import WebSocketCommonProtocol
from websockets.legacy.server import WebSocketServerProtocol
HOST = "us-central1-aiplatform.googleapis.com"
SERVICE_URL = f"wss://{HOST}/ws/google.cloud.aiplatform.v1beta1.LlmBidiService/BidiGenerateContent"
DEBUG = False
async def proxy_task(
client_websocket: WebSocketCommonProtocol, server_websocket: WebSocketCommonProtocol
) -> None:
"""
Forwards messages from one WebSocket connection to another.
Args:
client_websocket: The WebSocket connection from which to receive messages.
server_websocket: The WebSocket connection to which to send messages.
"""
async for message in client_websocket:
try:
data = json.loads(message)
if DEBUG:
print("proxying: ", data)
await server_websocket.send(json.dumps(data))
except Exception as e:
print(f"Error processing message: {e}")
await server_websocket.close()
async def create_proxy(
client_websocket: WebSocketCommonProtocol, bearer_token: str
) -> None:
"""
Establishes a WebSocket connection to the server and creates two tasks for
bidirectional message forwarding between the client and the server.
Args:
client_websocket: The WebSocket connection of the client.
bearer_token: The bearer token for authentication with the server.
"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {bearer_token}",
}
async with websockets.connect(
SERVICE_URL, additional_headers=headers
) as server_websocket:
client_to_server_task = asyncio.create_task(
proxy_task(client_websocket, server_websocket)
)
server_to_client_task = asyncio.create_task(
proxy_task(server_websocket, client_websocket)
)
await asyncio.gather(client_to_server_task, server_to_client_task)
async def handle_client(client_websocket: WebSocketServerProtocol) -> None:
"""
Handles a new client connection, expecting the first message to contain a bearer token.
Establishes a proxy connection to the server upon successful authentication.
Args:
client_websocket: The WebSocket connection of the client.
"""
print("New connection...")
# Wait for the first message from the client
auth_message = await asyncio.wait_for(client_websocket.recv(), timeout=5.0)
auth_data = json.loads(auth_message)
if "bearer_token" in auth_data:
bearer_token = auth_data["bearer_token"]
else:
print("Error: Bearer token not found in the first message.")
await client_websocket.close(code=1008, reason="Bearer token missing")
return
await create_proxy(client_websocket, bearer_token)
async def main() -> None:
"""
Starts the WebSocket server and listens for incoming client connections.
"""
async with websockets.serve(handle_client, "localhost", 8080):
print("Running websocket server localhost:8080...")
# Run forever
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())