-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient_example.py
More file actions
executable file
·296 lines (254 loc) · 9.03 KB
/
client_example.py
File metadata and controls
executable file
·296 lines (254 loc) · 9.03 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
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#!/usr/bin/env python3
"""
AIM Client Example - Connect to Remote MI300X Endpoint
This script demonstrates how to connect to an AIM inference service
running on a remote MI300X node from your laptop.
Usage:
python client_example.py --endpoint http://remote-host:8000
python client_example.py --endpoint http://localhost:8000 # if using SSH port forwarding
"""
import argparse
import json
import requests
import sys
from typing import Optional, Dict, Any, Iterator
class AIMClient:
"""Client for interacting with AIM inference service"""
def __init__(self, base_url: str):
"""
Initialize AIM client
Args:
base_url: Base URL of the AIM endpoint (e.g., http://remote-host:8000)
"""
self.base_url = base_url.rstrip('/')
self.session = requests.Session()
self.session.headers.update({
'Content-Type': 'application/json'
})
def health_check(self) -> bool:
"""Check if the endpoint is healthy"""
try:
response = self.session.get(f"{self.base_url}/health", timeout=5)
return response.status_code == 200
except requests.exceptions.RequestException:
return False
def list_models(self) -> Dict[str, Any]:
"""List available models"""
try:
response = self.session.get(f"{self.base_url}/v1/models", timeout=10)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error listing models: {e}", file=sys.stderr)
return {}
def chat_completion(
self,
messages: list,
model: Optional[str] = None,
max_tokens: int = 2048,
temperature: float = 0.7,
stream: bool = False
) -> Dict[str, Any]:
"""
Send a chat completion request
Args:
messages: List of message dicts with 'role' and 'content'
model: Model name (optional, will use default if not specified)
max_tokens: Maximum tokens to generate
temperature: Sampling temperature
stream: Whether to stream the response
Returns:
Response dict (or generator if streaming)
"""
payload = {
"messages": messages,
"max_tokens": max_tokens,
"temperature": temperature,
"stream": stream
}
if model:
payload["model"] = model
try:
if stream:
return self._stream_chat_completion(payload)
else:
response = self.session.post(
f"{self.base_url}/v1/chat/completions",
json=payload,
timeout=300 # 5 minute timeout for long responses
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error in chat completion: {e}", file=sys.stderr)
raise
def _stream_chat_completion(self, payload: Dict[str, Any]) -> Iterator[Dict[str, Any]]:
"""Stream chat completion responses"""
response = self.session.post(
f"{self.base_url}/v1/chat/completions",
json=payload,
stream=True,
timeout=300
)
response.raise_for_status()
for line in response.iter_lines():
if not line:
continue
line = line.decode('utf-8')
if line.startswith('data: '):
data = line[6:].strip()
if data == '[DONE]':
break
try:
chunk = json.loads(data)
yield chunk
except json.JSONDecodeError:
continue
def completion(
self,
prompt: str,
max_tokens: int = 50,
temperature: float = 0.7
) -> Dict[str, Any]:
"""
Send a text completion request
Args:
prompt: Text prompt
max_tokens: Maximum tokens to generate
temperature: Sampling temperature
Returns:
Response dict
"""
payload = {
"prompt": prompt,
"max_tokens": max_tokens,
"temperature": temperature
}
try:
response = self.session.post(
f"{self.base_url}/v1/completions",
json=payload,
timeout=300
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error in completion: {e}", file=sys.stderr)
raise
def main():
parser = argparse.ArgumentParser(
description="AIM Client Example - Connect to Remote MI300X Endpoint"
)
parser.add_argument(
'--endpoint',
type=str,
required=True,
help='AIM endpoint URL (e.g., http://remote-host:8000 or http://localhost:8000)'
)
parser.add_argument(
'--model',
type=str,
help='Model name (optional, will use default if not specified)'
)
parser.add_argument(
'--prompt',
type=str,
default="Hello! Can you explain what AIM is?",
help='Prompt/question to send'
)
parser.add_argument(
'--max-tokens',
type=int,
default=2048,
help='Maximum tokens to generate (default: 2048)'
)
parser.add_argument(
'--stream',
action='store_true',
help='Stream the response'
)
parser.add_argument(
'--list-models',
action='store_true',
help='List available models and exit'
)
args = parser.parse_args()
# Initialize client
client = AIMClient(args.endpoint)
# Health check
print(f"Connecting to {args.endpoint}...")
if not client.health_check():
print(f"⚠ Warning: Health check failed. Endpoint may not be ready.")
print(f" Continuing anyway...")
else:
print("✓ Endpoint is healthy")
print()
# List models if requested
if args.list_models:
print("Available models:")
models = client.list_models()
if models and 'data' in models:
for model in models['data']:
print(f" - {model.get('id', 'unknown')}")
if 'max_model_len' in model:
print(f" Max context length: {model['max_model_len']}")
else:
print(" No models found or error retrieving models")
return
# Test chat completion
print(f"Sending prompt: {args.prompt}")
print()
messages = [{"role": "user", "content": args.prompt}]
if args.stream:
print("Response (streaming):")
print("-" * 80)
try:
for chunk in client.chat_completion(
messages=messages,
model=args.model,
max_tokens=args.max_tokens,
stream=True
):
if 'choices' in chunk and len(chunk['choices']) > 0:
delta = chunk['choices'][0].get('delta', {})
# Qwen3 uses reasoning_content for thinking, content for response
reasoning = delta.get('reasoning_content', '')
content = delta.get('content', '')
if reasoning:
print(reasoning, end='', flush=True)
if content:
print(content, end='', flush=True)
print() # Newline at end
print("-" * 80)
except Exception as e:
print(f"\nError: {e}", file=sys.stderr)
sys.exit(1)
else:
print("Response:")
print("-" * 80)
try:
response = client.chat_completion(
messages=messages,
model=args.model,
max_tokens=args.max_tokens,
stream=False
)
if 'choices' in response and len(response['choices']) > 0:
content = response['choices'][0]['message']['content']
print(content)
# Show usage if available
if 'usage' in response:
usage = response['usage']
print()
print(f"Tokens used: {usage.get('total_tokens', 'N/A')} "
f"(prompt: {usage.get('prompt_tokens', 'N/A')}, "
f"completion: {usage.get('completion_tokens', 'N/A')})")
else:
print("No response received")
print(json.dumps(response, indent=2))
print("-" * 80)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()