-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
648 lines (561 loc) · 25.7 KB
/
client.py
File metadata and controls
648 lines (561 loc) · 25.7 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
"""API client for communicating with AI model servers."""
from contextlib import asynccontextmanager
from dataclasses import dataclass
from typing import AsyncGenerator, Dict, Optional, Tuple
import httpx
import json
import time
@asynccontextmanager
async def _http_session(http_client: Optional[httpx.AsyncClient]):
"""Yield an httpx.AsyncClient: the caller-provided one, or a one-shot.
When the caller supplies a client, we must NOT close it (connection pool
must survive across requests). When we create our own, close it on exit.
"""
if http_client is not None:
yield http_client
else:
async with httpx.AsyncClient(timeout=300.0) as client:
yield client
@dataclass
class ChatMetrics:
"""Metrics extracted from an API response."""
prompt_tokens: int = 0
completion_tokens: int = 0
prompt_eval_duration_ns: int = 0 # Ollama-specific prefill timing
eval_duration_ns: int = 0 # Ollama-specific decode timing
ttft: float = 0.0 # Time to first content token (seconds)
class ModelClient:
"""Client for interacting with AI model servers."""
def __init__(self, server: Dict, model: str):
self.server = server
self.model = model
self.url = server["url"]
self.server_type = server["type"]
self.last_metrics: ChatMetrics = ChatMetrics() # populated by chat_stream
async def chat_stream(
self, message: str, history: Optional[list] = None,
enable_thinking: Optional[bool] = None
) -> AsyncGenerator[str, None]:
"""Send a chat message and stream the response."""
if self.server_type == "openai":
async for chunk in self._chat_stream_openai(message, history, enable_thinking):
yield chunk
else: # ollama
async for chunk in self._chat_stream_ollama(message, history, enable_thinking):
yield chunk
async def _chat_stream_openai(
self, message: str, history: Optional[list] = None,
enable_thinking: Optional[bool] = None
) -> AsyncGenerator[str, None]:
"""Stream chat using OpenAI-compatible API."""
# Create a copy of history to avoid mutating the original
messages = (history or []).copy()
if message:
messages.append({"role": "user", "content": message})
payload = {
"model": self.model,
"messages": messages,
"stream": True,
}
# Pass thinking toggle for models that support it (e.g. Qwen 3/3.5 on vLLM)
if enable_thinking is not None:
payload["chat_template_kwargs"] = {"enable_thinking": enable_thinking}
async with httpx.AsyncClient(timeout=60.0) as client:
async with client.stream(
"POST",
f"{self.url}/v1/chat/completions",
json=payload,
) as response:
# Use aiter_bytes to avoid line buffering for real-time streaming
buffer = b""
thinking_active = False
async for chunk_bytes in response.aiter_bytes(chunk_size=64):
buffer += chunk_bytes
# Process all complete lines in buffer
while b"\n" in buffer:
line_bytes, buffer = buffer.split(b"\n", 1)
line = line_bytes.decode('utf-8', errors='ignore').strip()
if line.startswith("data: "):
data = line[6:]
if data == "[DONE]":
if thinking_active:
yield "</think>"
return
try:
chunk = json.loads(data)
delta = chunk.get("choices", [{}])[0].get("delta", {})
# Handle reasoning_content (vLLM/Qwen thinking field)
reasoning = delta.get("reasoning_content", "")
if reasoning:
if not thinking_active:
yield "<think>"
thinking_active = True
yield reasoning
content = delta.get("content", "")
if content:
if thinking_active:
yield "</think>"
thinking_active = False
yield content
except json.JSONDecodeError:
continue
async def _chat_stream_ollama(
self, message: str, history: Optional[list] = None,
enable_thinking: Optional[bool] = None
) -> AsyncGenerator[str, None]:
"""Stream chat using Ollama API. Populates self.last_metrics on completion."""
# Create a copy of history to avoid mutating the original
messages = (history or []).copy()
if message:
messages.append({"role": "user", "content": message})
payload = {
"model": self.model,
"messages": messages,
"stream": True,
}
# Pass thinking toggle for Ollama models that support it
if enable_thinking is not None:
payload["options"] = payload.get("options", {})
payload["options"]["enable_thinking"] = enable_thinking
self.last_metrics = ChatMetrics()
async with httpx.AsyncClient(timeout=60.0) as client:
async with client.stream(
"POST",
f"{self.url}/api/chat",
json=payload,
) as response:
# Use aiter_bytes to avoid line buffering for real-time streaming
buffer = b""
async for chunk_bytes in response.aiter_bytes(chunk_size=64):
buffer += chunk_bytes
# Process all complete lines in buffer (Ollama sends NDJSON)
while b"\n" in buffer:
line_bytes, buffer = buffer.split(b"\n", 1)
line = line_bytes.decode('utf-8', errors='ignore').strip()
if line:
try:
chunk = json.loads(line)
# Capture metrics from the final done chunk
if chunk.get("done"):
self.last_metrics.completion_tokens = chunk.get("eval_count", 0)
self.last_metrics.prompt_tokens = chunk.get("prompt_eval_count", 0)
self.last_metrics.eval_duration_ns = chunk.get("eval_duration", 0)
self.last_metrics.prompt_eval_duration_ns = chunk.get("prompt_eval_duration", 0)
break
content = chunk.get("message", {}).get("content", "")
if content:
yield content
except json.JSONDecodeError:
continue
async def chat(
self, message: str, history: Optional[list] = None,
enable_thinking: Optional[bool] = None
) -> str:
"""Send a chat message and return the full response."""
full_response = ""
async for chunk in self.chat_stream(message, history, enable_thinking):
full_response += chunk
return full_response
async def chat_with_metrics(
self, message: str, history: Optional[list] = None,
max_tokens: Optional[int] = None,
enable_thinking: Optional[bool] = None,
http_client: Optional[httpx.AsyncClient] = None
) -> Tuple[str, ChatMetrics]:
"""Send a chat message and return the full response with API metrics.
Streams internally to capture TTFT, then extracts real token counts
from the API response metadata (Ollama eval_count / OpenAI usage).
Falls back gracefully when the server doesn't report metrics.
If `http_client` is provided, it is reused (keepalive / connection
pool preserved across calls). Otherwise a one-shot client is created.
"""
if self.server_type == "openai":
return await self._chat_metrics_openai(message, history, max_tokens, enable_thinking, http_client)
else:
return await self._chat_metrics_ollama(message, history, max_tokens, enable_thinking, http_client)
async def _chat_metrics_openai(
self, message: str, history: Optional[list] = None,
max_tokens: Optional[int] = None,
enable_thinking: Optional[bool] = None,
http_client: Optional[httpx.AsyncClient] = None
) -> Tuple[str, ChatMetrics]:
"""Stream via OpenAI-compatible API, extracting usage metrics."""
messages = (history or []).copy()
if message:
messages.append({"role": "user", "content": message})
payload = {
"model": self.model,
"messages": messages,
"stream": True,
"stream_options": {"include_usage": True},
}
if max_tokens is not None:
payload["max_tokens"] = max_tokens
if enable_thinking is not None:
payload["chat_template_kwargs"] = {"enable_thinking": enable_thinking}
metrics = ChatMetrics()
full_response = ""
request_start = time.monotonic()
first_content = True
thinking_active = False
try:
async with _http_session(http_client) as client:
async with client.stream(
"POST",
f"{self.url}/v1/chat/completions",
json=payload,
timeout=300.0,
) as response:
# Check for server error (stream_options not supported)
if response.status_code >= 400:
raise httpx.HTTPStatusError(
f"HTTP {response.status_code}",
request=response.request, response=response
)
buffer = b""
async for chunk_bytes in response.aiter_bytes(chunk_size=64):
buffer += chunk_bytes
while b"\n" in buffer:
line_bytes, buffer = buffer.split(b"\n", 1)
line = line_bytes.decode('utf-8', errors='ignore').strip()
if not line.startswith("data: "):
continue
data = line[6:]
if data == "[DONE]":
break
try:
chunk = json.loads(data)
# Extract usage from final chunk if present
usage = chunk.get("usage")
if usage:
metrics.prompt_tokens = usage.get("prompt_tokens", 0)
metrics.completion_tokens = usage.get("completion_tokens", 0)
# Usage-only chunks have "choices": [] — skip delta parsing
choices = chunk.get("choices", [])
if not choices:
continue
delta = choices[0].get("delta", {})
reasoning = delta.get("reasoning_content", "")
if reasoning:
if not thinking_active:
thinking_active = True
full_response += "<think>"
full_response += reasoning
content = delta.get("content", "")
if content:
if thinking_active:
thinking_active = False
full_response += "</think>"
if first_content:
metrics.ttft = time.monotonic() - request_start
first_content = False
full_response += content
except json.JSONDecodeError:
continue
except (httpx.HTTPStatusError, httpx.RequestError):
# stream_options not supported — retry without it
return await self._chat_metrics_openai_fallback(
message, history, max_tokens, enable_thinking, http_client
)
if thinking_active:
full_response += "</think>"
return full_response, metrics
async def _chat_metrics_openai_fallback(
self, message: str, history: Optional[list] = None,
max_tokens: Optional[int] = None,
enable_thinking: Optional[bool] = None,
http_client: Optional[httpx.AsyncClient] = None
) -> Tuple[str, ChatMetrics]:
"""Fallback for servers that reject stream_options."""
messages = (history or []).copy()
if message:
messages.append({"role": "user", "content": message})
payload = {
"model": self.model,
"messages": messages,
"stream": True,
}
if max_tokens is not None:
payload["max_tokens"] = max_tokens
if enable_thinking is not None:
payload["chat_template_kwargs"] = {"enable_thinking": enable_thinking}
metrics = ChatMetrics()
full_response = ""
request_start = time.monotonic()
first_content = True
thinking_active = False
async with _http_session(http_client) as client:
async with client.stream(
"POST",
f"{self.url}/v1/chat/completions",
json=payload,
timeout=300.0,
) as response:
buffer = b""
async for chunk_bytes in response.aiter_bytes(chunk_size=64):
buffer += chunk_bytes
while b"\n" in buffer:
line_bytes, buffer = buffer.split(b"\n", 1)
line = line_bytes.decode('utf-8', errors='ignore').strip()
if not line.startswith("data: "):
continue
data = line[6:]
if data == "[DONE]":
break
try:
chunk = json.loads(data)
choices = chunk.get("choices", [])
if not choices:
continue
delta = choices[0].get("delta", {})
reasoning = delta.get("reasoning_content", "")
if reasoning:
if not thinking_active:
thinking_active = True
full_response += "<think>"
full_response += reasoning
content = delta.get("content", "")
if content:
if thinking_active:
thinking_active = False
full_response += "</think>"
if first_content:
metrics.ttft = time.monotonic() - request_start
first_content = False
full_response += content
except json.JSONDecodeError:
continue
if thinking_active:
full_response += "</think>"
# No usage data available — metrics.completion_tokens stays 0, caller falls back
return full_response, metrics
# ----------------------------------------------------------------- #
# Tool calling (non-streaming) — supports agentic loops
# ----------------------------------------------------------------- #
def make_assistant_tool_msg(self, content: str, tool_calls: list) -> dict:
"""Build an assistant message containing tool_calls in server-native format.
``tool_calls`` is the normalized list returned by ``chat_with_tools``:
``[{"id": str, "name": str, "arguments": dict}, ...]``.
"""
if self.server_type == "openai":
return {
"role": "assistant",
"content": content or "",
"tool_calls": [
{
"id": tc.get("id") or f"call_{i}",
"type": "function",
"function": {
"name": tc["name"],
"arguments": json.dumps(tc.get("arguments") or {}),
},
}
for i, tc in enumerate(tool_calls)
],
}
# Ollama
return {
"role": "assistant",
"content": content or "",
"tool_calls": [
{"function": {"name": tc["name"], "arguments": tc.get("arguments") or {}}}
for tc in tool_calls
],
}
def make_tool_result_msg(self, tool_call_id: str, result: str) -> dict:
"""Build a tool-result message in server-native format."""
if self.server_type == "openai":
return {
"role": "tool",
"tool_call_id": tool_call_id or "call_0",
"content": str(result),
}
return {"role": "tool", "content": str(result)}
async def chat_with_tools(
self,
messages: list,
tools: list,
max_tokens: Optional[int] = None,
http_client: Optional[httpx.AsyncClient] = None,
) -> Tuple[str, list, ChatMetrics]:
"""Non-streaming chat with tool support.
Returns ``(content, tool_calls, metrics)``. ``tool_calls`` is normalized to
``[{"id": str, "name": str, "arguments": dict}, ...]`` regardless of server.
``content`` may be empty when the assistant only emits tool calls.
"""
if self.server_type == "openai":
return await self._chat_tools_openai(messages, tools, max_tokens, http_client)
return await self._chat_tools_ollama(messages, tools, max_tokens, http_client)
async def _chat_tools_openai(
self, messages: list, tools: list,
max_tokens: Optional[int], http_client: Optional[httpx.AsyncClient],
) -> Tuple[str, list, ChatMetrics]:
payload = {
"model": self.model,
"messages": messages,
"tools": tools,
"tool_choice": "auto",
"stream": False,
}
if max_tokens is not None:
payload["max_tokens"] = max_tokens
request_start = time.monotonic()
async with _http_session(http_client) as client:
r = await client.post(
f"{self.url}/v1/chat/completions",
json=payload, timeout=300.0,
)
r.raise_for_status()
body = r.json()
metrics = ChatMetrics()
metrics.ttft = time.monotonic() - request_start # non-streaming → TTFT == full
usage = body.get("usage") or {}
metrics.prompt_tokens = usage.get("prompt_tokens", 0)
metrics.completion_tokens = usage.get("completion_tokens", 0)
msg = (body.get("choices") or [{}])[0].get("message") or {}
content = msg.get("content") or ""
raw_calls = msg.get("tool_calls") or []
normalized = []
for i, tc in enumerate(raw_calls):
fn = tc.get("function") or {}
args_raw = fn.get("arguments")
malformed = False
if isinstance(args_raw, str):
try:
args = json.loads(args_raw)
if not isinstance(args, dict):
malformed = True
args = {}
except Exception:
malformed = True
args = {}
elif isinstance(args_raw, dict):
args = args_raw
elif args_raw is None:
args = {}
else:
malformed = True
args = {}
normalized.append({
"id": tc.get("id") or f"call_{i}",
"name": fn.get("name") or "",
"arguments": args,
"malformed_args": malformed,
})
return content, normalized, metrics
async def _chat_tools_ollama(
self, messages: list, tools: list,
max_tokens: Optional[int], http_client: Optional[httpx.AsyncClient],
) -> Tuple[str, list, ChatMetrics]:
payload = {
"model": self.model,
"messages": messages,
"tools": tools,
"stream": False,
}
if max_tokens is not None:
payload["options"] = {"num_predict": max_tokens}
request_start = time.monotonic()
async with _http_session(http_client) as client:
r = await client.post(
f"{self.url}/api/chat",
json=payload, timeout=300.0,
)
r.raise_for_status()
body = r.json()
metrics = ChatMetrics()
metrics.ttft = time.monotonic() - request_start
metrics.completion_tokens = body.get("eval_count", 0)
metrics.prompt_tokens = body.get("prompt_eval_count", 0)
metrics.eval_duration_ns = body.get("eval_duration", 0)
metrics.prompt_eval_duration_ns = body.get("prompt_eval_duration", 0)
msg = body.get("message") or {}
content = msg.get("content") or ""
raw_calls = msg.get("tool_calls") or []
normalized = []
for i, tc in enumerate(raw_calls):
fn = tc.get("function") or {}
args = fn.get("arguments")
malformed = False
if isinstance(args, str):
try:
args = json.loads(args)
if not isinstance(args, dict):
malformed = True
args = {}
except Exception:
malformed = True
args = {}
elif isinstance(args, dict):
pass
elif args is None:
args = {}
else:
malformed = True
args = {}
normalized.append({
"id": tc.get("id") or f"call_{i}",
"name": fn.get("name") or "",
"arguments": args,
"malformed_args": malformed,
})
return content, normalized, metrics
async def _chat_metrics_ollama(
self, message: str, history: Optional[list] = None,
max_tokens: Optional[int] = None,
enable_thinking: Optional[bool] = None,
http_client: Optional[httpx.AsyncClient] = None
) -> Tuple[str, ChatMetrics]:
"""Stream via Ollama API, extracting eval_count / eval_duration."""
messages = (history or []).copy()
if message:
messages.append({"role": "user", "content": message})
payload = {
"model": self.model,
"messages": messages,
"stream": True,
}
options = {}
if max_tokens is not None:
options["num_predict"] = max_tokens
if enable_thinking is not None:
options["enable_thinking"] = enable_thinking
if options:
payload["options"] = options
metrics = ChatMetrics()
full_response = ""
request_start = time.monotonic()
first_content = True
async with _http_session(http_client) as client:
async with client.stream(
"POST",
f"{self.url}/api/chat",
json=payload,
timeout=300.0,
) as response:
buffer = b""
async for chunk_bytes in response.aiter_bytes(chunk_size=64):
buffer += chunk_bytes
while b"\n" in buffer:
line_bytes, buffer = buffer.split(b"\n", 1)
line = line_bytes.decode('utf-8', errors='ignore').strip()
if not line:
continue
try:
chunk = json.loads(line)
# Final chunk with done=true has timing/count data
if chunk.get("done"):
metrics.completion_tokens = chunk.get("eval_count", 0)
metrics.prompt_tokens = chunk.get("prompt_eval_count", 0)
metrics.eval_duration_ns = chunk.get("eval_duration", 0)
metrics.prompt_eval_duration_ns = chunk.get("prompt_eval_duration", 0)
break
content = chunk.get("message", {}).get("content", "")
if content:
if first_content:
metrics.ttft = time.monotonic() - request_start
first_content = False
full_response += content
except json.JSONDecodeError:
continue
return full_response, metrics