-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
196 lines (167 loc) · 6.93 KB
/
Copy pathexample.py
File metadata and controls
196 lines (167 loc) · 6.93 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
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
"""
KeyMesh Demonstration — Basic implementation showcasing three concurrency-safe approaches
for managing API keys in both Sync and Async KeyPools.
"""
import os
import asyncio
import time
import contextlib
from typing import Generator, AsyncGenerator
from dotenv import load_dotenv
from openai import OpenAI, AsyncOpenAI, RateLimitError
from keymesh import KeyPool, SyncKeyPool
# Load environment variables
load_dotenv()
API_KEYS = os.getenv("OPENAI_API_KEYS", "").split(",")
BASE_URL = os.getenv("OPENAI_BASE_URL", "")
MODEL_NAME = os.getenv("OPENAI_MODEL_NAME", "")
# Initialize client instances once (reusing connection pools)
sync_client = OpenAI(base_url=BASE_URL)
async_client = AsyncOpenAI(base_url=BASE_URL)
# ── APPROACH 1: Request-Scoped Client Overrides (with_options) ──────────────
def run_sync_with_options(pool: SyncKeyPool) -> None:
print("── Sync Approach 1: with_options ──")
try:
key = pool.acquire()
start = time.monotonic()
try:
# with_options returns a copy sharing the connection pool
scoped_client = sync_client.with_options(api_key=key)
response = scoped_client.chat.completions.create(
model=MODEL_NAME,
messages=[{"role": "user", "content": "Say 'Options Sync' in 3 words."}],
)
pool.release(key, latency=time.monotonic() - start)
print(f"Success: {response.choices[0].message.content}")
except BaseException:
pool.mark_failed(key)
raise
except Exception as e:
print(f"Failed: {e}")
async def run_async_with_options(pool: KeyPool) -> None:
print("\n── Async Approach 1: with_options ──")
try:
key = await pool.acquire()
start = time.monotonic()
try:
scoped_client = async_client.with_options(api_key=key)
response = await scoped_client.chat.completions.create(
model=MODEL_NAME,
messages=[{"role": "user", "content": "Say 'Options Async' in 3 words."}],
)
await pool.release(key, latency=time.monotonic() - start)
print(f"Success: {response.choices[0].message.content}")
except BaseException:
await pool.mark_failed(key)
raise
except Exception as e:
print(f"Failed: {e}")
# ── APPROACH 2: Per-Request Custom Headers (extra_headers) ──────────────────
def run_sync_headers(pool: SyncKeyPool) -> None:
print("\n── Sync Approach 2: extra_headers ──")
try:
key = pool.acquire()
start = time.monotonic()
try:
# Pass the Authorization header dynamically per-request
response = sync_client.chat.completions.create(
model=MODEL_NAME,
messages=[{"role": "user", "content": "Say 'Headers Sync' in 3 words."}],
extra_headers={"Authorization": f"Bearer {key}"}
)
pool.release(key, latency=time.monotonic() - start)
print(f"Success: {response.choices[0].message.content}")
except BaseException:
pool.mark_failed(key)
raise
except Exception as e:
print(f"Failed: {e}")
async def run_async_headers(pool: KeyPool) -> None:
print("\n── Async Approach 2: extra_headers ──")
try:
key = await pool.acquire()
start = time.monotonic()
try:
response = await async_client.chat.completions.create(
model=MODEL_NAME,
messages=[{"role": "user", "content": "Say 'Headers Async' in 3 words."}],
extra_headers={"Authorization": f"Bearer {key}"}
)
await pool.release(key, latency=time.monotonic() - start)
print(f"Success: {response.choices[0].message.content}")
except BaseException:
await pool.mark_failed(key)
raise
except Exception as e:
print(f"Failed: {e}")
# ── APPROACH 3: Lifecycle Hooks (Context Managers) ──────────────────────────
@contextlib.contextmanager
def sync_key_lifecycle(pool: SyncKeyPool) -> Generator[str, None, None]:
key = pool.acquire()
start = time.monotonic()
try:
yield key
pool.release(key, latency=time.monotonic() - start)
except RateLimitError:
pool.mark_rate_limited(key, cooldown=60.0)
raise
except BaseException:
pool.mark_failed(key)
raise
@contextlib.asynccontextmanager
async def async_key_lifecycle(pool: KeyPool) -> AsyncGenerator[str, None]:
key = await pool.acquire()
start = time.monotonic()
try:
yield key
await pool.release(key, latency=time.monotonic() - start)
except RateLimitError:
await pool.mark_rate_limited(key, cooldown=60.0)
raise
except BaseException:
await pool.mark_failed(key)
raise
def run_sync_lifecycle(pool: SyncKeyPool) -> None:
print("\n── Sync Approach 3: Lifecycle Hook ──")
try:
with sync_key_lifecycle(pool) as key:
scoped_client = sync_client.with_options(api_key=key)
response = scoped_client.chat.completions.create(
model=MODEL_NAME,
messages=[{"role": "user", "content": "Say 'Lifecycle Sync' in 3 words."}],
)
print(f"Success: {response.choices[0].message.content}")
except Exception as e:
print(f"Failed: {e}")
async def run_async_lifecycle(pool: KeyPool) -> None:
print("\n── Async Approach 3: Lifecycle Hook ──")
try:
async with async_key_lifecycle(pool) as key:
scoped_client = async_client.with_options(api_key=key)
response = await scoped_client.chat.completions.create(
model=MODEL_NAME,
messages=[{"role": "user", "content": "Say 'Lifecycle Async' in 3 words."}],
)
print(f"Success: {response.choices[0].message.content}")
except Exception as e:
print(f"Failed: {e}")
# ── MAIN EXECUTION ──────────────────────────────────────────────────────────
async def run_all_async(async_pool: KeyPool) -> None:
await run_async_with_options(async_pool)
await run_async_headers(async_pool)
await run_async_lifecycle(async_pool)
if __name__ == "__main__":
# Create the pools
sync_pool = SyncKeyPool(keys=API_KEYS)
async_pool = KeyPool(keys=API_KEYS)
try:
# Run Synchronous Demos
run_sync_with_options(sync_pool)
run_sync_headers(sync_pool)
run_sync_lifecycle(sync_pool)
# Run Asynchronous Demos
asyncio.run(run_all_async(async_pool))
finally:
# Safely close pools to release storage backends
sync_pool.close()
asyncio.run(async_pool.close())