Repository navigation
Expand file tree
/
Copy pathexample_client.py
More file actions
131 lines (107 loc) · 3.75 KB
/
Copy pathexample_client.py
File metadata and controls
131 lines (107 loc) · 3.75 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
#!/usr/bin/env python3
"""
Example client for the OpenAI Batch Proxy.
This demonstrates how to use the batch proxy with automatic retries
and long timeouts to transparently handle batch processing.
"""
import uuid
import time
from openai import OpenAI, APIError, APITimeoutError
import sys
def batched_completion(
messages,
model="gpt-4",
base_url="http://localhost:8080/v1",
max_wait_hours=24,
timeout_per_attempt=3600, # 1 hour per attempt
):
"""
Make a completion request through the batch proxy.
Args:
messages: List of message dicts with 'role' and 'content'
model: Model name to use
base_url: Base URL of the batch proxy
max_wait_hours: Maximum time to wait for completion (hours)
timeout_per_attempt: Timeout for each HTTP attempt (seconds)
Returns:
OpenAI completion response
"""
client = OpenAI(
base_url=base_url,
api_key="dummy", # Not needed for the proxy, but required by the SDK
timeout=timeout_per_attempt,
max_retries=0, # We handle retries manually
)
# Generate a unique request ID
request_id = str(uuid.uuid4())
print(f"Request ID: {request_id}")
start_time = time.time()
retry_delay = 30 # Start with 30 seconds
attempt = 0
while time.time() - start_time < max_wait_hours * 3600:
attempt += 1
elapsed = time.time() - start_time
print(f"\nAttempt {attempt} (elapsed: {elapsed:.1f}s)")
try:
response = client.chat.completions.create(
model=model,
messages=messages,
extra_headers={
"Idempotency-Key": request_id
}
)
print("✓ Request completed successfully!")
return response
except APITimeoutError as e:
print(f"⏱ Connection timeout, retrying in {retry_delay}s...")
time.sleep(retry_delay)
retry_delay = min(retry_delay * 1.5, 300) # Max 5 minutes
except APIError as e:
if e.status_code >= 500:
# Server error, retry
print(f"⚠ Server error ({e.status_code}), retrying in {retry_delay}s...")
time.sleep(retry_delay)
retry_delay = min(retry_delay * 1.5, 300)
else:
# Client error, don't retry
print(f"✗ Client error: {e}")
raise
except Exception as e:
print(f"⚠ Unexpected error: {e}, retrying in {retry_delay}s...")
time.sleep(retry_delay)
retry_delay = min(retry_delay * 1.5, 300)
raise TimeoutError(f"Batch did not complete within {max_wait_hours} hours")
def main():
"""Example usage"""
print("OpenAI Batch Proxy - Example Client")
print("=" * 50)
messages = [
{
"role": "user",
"content": "Write a short poem about batch processing."
}
]
print("\nSending request to batch proxy...")
print("This may take a while (potentially hours) depending on batch processing.")
print("The connection will automatically retry if it drops.\n")
try:
response = batched_completion(
messages=messages,
model="gpt-4",
max_wait_hours=24,
)
print("\n" + "=" * 50)
print("Response:")
print("=" * 50)
print(response.choices[0].message.content)
print("\n" + "=" * 50)
print(f"Model: {response.model}")
print(f"Tokens: {response.usage.total_tokens}")
except KeyboardInterrupt:
print("\n\n⚠ Interrupted by user")
sys.exit(1)
except Exception as e:
print(f"\n\n✗ Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()