-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
469 lines (384 loc) · 15.1 KB
/
Copy pathclient.py
File metadata and controls
469 lines (384 loc) · 15.1 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
"""Hawk SDK client implementations (sync and async)."""
from __future__ import annotations
from typing import Any
from urllib.parse import urlparse
import httpx
from ._version import __version__
from .errors import parse_error
from .retry import DEFAULT_RETRY_CONFIG, RetryConfig, with_retry, with_retry_sync
from .streaming import AsyncStreamReader, StreamReader
from .types import (
ChatRequest,
ChatResponse,
HealthResponse,
Message,
PaginatedResponse,
SessionDetail,
SessionSummary,
StatsResponse,
)
DEFAULT_BASE_URL = "http://127.0.0.1:4590"
DEFAULT_TIMEOUT = 30.0
DEFAULT_POOL_CONNECTIONS = 10
DEFAULT_POOL_MAXSIZE = 100
def _build_headers(api_key: str | None) -> dict[str, str]:
"""Build standard HTTP headers for Hawk API requests."""
headers: dict[str, str] = {
"Accept": "application/json",
"User-Agent": f"hawk-sdk-python/{__version__}",
}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
return headers
def _validate_base_url(url: str) -> str:
"""Validate that base_url uses http/https and has a hostname."""
parsed = urlparse(url)
if parsed.scheme not in ("http", "https"):
raise ValueError(f"base_url must use http or https scheme, got: {parsed.scheme}")
if not parsed.hostname:
raise ValueError("base_url must have a hostname")
return url
class HawkClient:
"""Synchronous client for the Hawk daemon API.
Usage:
with HawkClient() as client:
health = client.health()
response = client.chat("Hello!")
"""
def __init__(
self,
base_url: str = DEFAULT_BASE_URL,
api_key: str | None = None,
retry_config: RetryConfig | None = None,
timeout: float = DEFAULT_TIMEOUT,
pool_connections: int = DEFAULT_POOL_CONNECTIONS,
pool_maxsize: int = DEFAULT_POOL_MAXSIZE,
) -> None:
_validate_base_url(base_url)
self._base_url = base_url.rstrip("/")
self._api_key = api_key
self._retry_config = retry_config or DEFAULT_RETRY_CONFIG
self._timeout = timeout
self._pool_connections = pool_connections
self._pool_maxsize = pool_maxsize
self._client = httpx.Client(
base_url=self._base_url,
timeout=self._timeout,
headers=_build_headers(api_key),
limits=httpx.Limits(
max_keepalive_connections=pool_connections,
max_connections=pool_maxsize,
),
)
def __repr__(self) -> str:
masked = "***" + self._api_key[-4:] if self._api_key else "None"
return f"HawkClient(base_url='{self._base_url}', api_key='{masked}')"
def __enter__(self) -> HawkClient:
return self
def __exit__(self, *args: object) -> None:
self.close()
def close(self) -> None:
"""Close the underlying HTTP client."""
self._client.close()
def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
"""Make an HTTP request, raising typed errors on failure."""
response = self._client.request(method, path, **kwargs)
if response.status_code >= 400:
raise parse_error(response)
return response
def health(self) -> HealthResponse:
"""Check daemon connectivity and health."""
def _do() -> HealthResponse:
resp = self._request("GET", "/v1/health")
return HealthResponse.model_validate(resp.json())
return with_retry_sync(_do, self._retry_config)
def chat(
self,
prompt: str,
*,
session_id: str | None = None,
model: str | None = None,
max_turns: int | None = None,
autonomy: str | None = None,
cwd: str | None = None,
agent: str | None = None,
) -> ChatResponse:
"""Send a prompt and return the complete response."""
request = ChatRequest(
prompt=prompt,
session_id=session_id,
model=model,
max_turns=max_turns,
autonomy=autonomy,
cwd=cwd,
agent=agent,
)
def _do() -> ChatResponse:
resp = self._request(
"POST",
"/v1/chat",
json=request.model_dump(exclude_none=True, by_alias=True),
)
return ChatResponse.model_validate(resp.json())
return with_retry_sync(_do, self._retry_config)
def chat_stream(
self,
prompt: str,
*,
session_id: str | None = None,
model: str | None = None,
max_turns: int | None = None,
autonomy: str | None = None,
cwd: str | None = None,
agent: str | None = None,
) -> StreamReader:
"""Send a prompt and stream the response via SSE."""
request = ChatRequest(
prompt=prompt,
session_id=session_id,
model=model,
max_turns=max_turns,
autonomy=autonomy,
cwd=cwd,
agent=agent,
)
def _do() -> StreamReader:
response = self._client.send(
self._client.build_request(
"POST",
"/v1/chat",
json=request.model_dump(exclude_none=True, by_alias=True),
headers={"Accept": "text/event-stream"},
),
stream=True,
)
if response.status_code >= 400:
response.read()
raise parse_error(response)
return StreamReader(response)
return with_retry_sync(_do, self._retry_config)
def create_session(
self,
name: str | None = None,
metadata: dict[str, Any] | None = None,
) -> SessionDetail:
"""Create a new session."""
body: dict[str, Any] = {}
if name is not None:
body["name"] = name
if metadata is not None:
body["metadata"] = metadata
def _do() -> SessionDetail:
resp = self._request("POST", "/v1/sessions", json=body)
return SessionDetail.model_validate(resp.json())
return with_retry_sync(_do, self._retry_config)
def get_session(self, session_id: str) -> SessionDetail:
"""Get a session by ID."""
def _do() -> SessionDetail:
resp = self._request("GET", f"/v1/sessions/{session_id}")
return SessionDetail.model_validate(resp.json())
return with_retry_sync(_do, self._retry_config)
def list_sessions(self, limit: int = 20, offset: int = 0) -> PaginatedResponse[SessionSummary]:
"""List sessions with pagination."""
def _do() -> PaginatedResponse[SessionSummary]:
params: dict[str, Any] = {"limit": limit}
if offset > 0:
params["offset"] = offset
resp = self._request("GET", "/v1/sessions", params=params)
return PaginatedResponse[SessionSummary].model_validate(resp.json())
return with_retry_sync(_do, self._retry_config)
def delete_session(self, session_id: str) -> None:
"""Delete a session by ID."""
def _do() -> None:
self._request("DELETE", f"/v1/sessions/{session_id}")
return with_retry_sync(_do, self._retry_config)
def list_messages(
self, session_id: str, limit: int = 50, offset: int = 0
) -> PaginatedResponse[Message]:
"""List messages for a session with pagination."""
def _do() -> PaginatedResponse[Message]:
params: dict[str, Any] = {"limit": limit}
if offset > 0:
params["offset"] = offset
resp = self._request("GET", f"/v1/sessions/{session_id}/messages", params=params)
return PaginatedResponse[Message].model_validate(resp.json())
return with_retry_sync(_do, self._retry_config)
def stats(self) -> StatsResponse:
"""Get aggregated usage statistics."""
def _do() -> StatsResponse:
resp = self._request("GET", "/v1/stats")
return StatsResponse.model_validate(resp.json())
return with_retry_sync(_do, self._retry_config)
class AsyncHawkClient:
"""Asynchronous client for the Hawk daemon API.
Usage:
async with AsyncHawkClient() as client:
health = await client.health()
response = await client.chat("Hello!")
"""
def __init__(
self,
base_url: str = DEFAULT_BASE_URL,
api_key: str | None = None,
retry_config: RetryConfig | None = None,
timeout: float = DEFAULT_TIMEOUT,
pool_connections: int = DEFAULT_POOL_CONNECTIONS,
pool_maxsize: int = DEFAULT_POOL_MAXSIZE,
) -> None:
_validate_base_url(base_url)
self._base_url = base_url.rstrip("/")
self._api_key = api_key
self._retry_config = retry_config or DEFAULT_RETRY_CONFIG
self._timeout = timeout
self._pool_connections = pool_connections
self._pool_maxsize = pool_maxsize
self._client = httpx.AsyncClient(
base_url=self._base_url,
timeout=self._timeout,
headers=_build_headers(api_key),
limits=httpx.Limits(
max_keepalive_connections=pool_connections,
max_connections=pool_maxsize,
),
)
def __repr__(self) -> str:
masked = "***" + self._api_key[-4:] if self._api_key else "None"
return f"AsyncHawkClient(base_url='{self._base_url}', api_key='{masked}')"
async def __aenter__(self) -> AsyncHawkClient:
return self
async def __aexit__(self, *args: object) -> None:
await self.close()
async def close(self) -> None:
"""Close the underlying HTTP client."""
await self._client.aclose()
async def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
"""Make an async HTTP request, raising typed errors on failure."""
response = await self._client.request(method, path, **kwargs)
if response.status_code >= 400:
raise parse_error(response)
return response
async def health(self) -> HealthResponse:
"""Check daemon connectivity and health."""
async def _do() -> HealthResponse:
resp = await self._request("GET", "/v1/health")
return HealthResponse.model_validate(resp.json())
return await with_retry(_do, self._retry_config)
async def chat(
self,
prompt: str,
*,
session_id: str | None = None,
model: str | None = None,
max_turns: int | None = None,
autonomy: str | None = None,
cwd: str | None = None,
agent: str | None = None,
) -> ChatResponse:
"""Send a prompt and return the complete response."""
request = ChatRequest(
prompt=prompt,
session_id=session_id,
model=model,
max_turns=max_turns,
autonomy=autonomy,
cwd=cwd,
agent=agent,
)
async def _do() -> ChatResponse:
resp = await self._request(
"POST",
"/v1/chat",
json=request.model_dump(exclude_none=True, by_alias=True),
)
return ChatResponse.model_validate(resp.json())
return await with_retry(_do, self._retry_config)
async def chat_stream(
self,
prompt: str,
*,
session_id: str | None = None,
model: str | None = None,
max_turns: int | None = None,
autonomy: str | None = None,
cwd: str | None = None,
agent: str | None = None,
) -> AsyncStreamReader:
"""Send a prompt and stream the response via SSE."""
request = ChatRequest(
prompt=prompt,
session_id=session_id,
model=model,
max_turns=max_turns,
autonomy=autonomy,
cwd=cwd,
agent=agent,
)
async def _do() -> AsyncStreamReader:
response = await self._client.send(
self._client.build_request(
"POST",
"/v1/chat",
json=request.model_dump(exclude_none=True, by_alias=True),
headers={"Accept": "text/event-stream"},
),
stream=True,
)
if response.status_code >= 400:
await response.aread()
raise parse_error(response)
return AsyncStreamReader(response)
return await with_retry(_do, self._retry_config)
async def create_session(
self,
name: str | None = None,
metadata: dict[str, Any] | None = None,
) -> SessionDetail:
"""Create a new session."""
body: dict[str, Any] = {}
if name is not None:
body["name"] = name
if metadata is not None:
body["metadata"] = metadata
async def _do() -> SessionDetail:
resp = await self._request("POST", "/v1/sessions", json=body)
return SessionDetail.model_validate(resp.json())
return await with_retry(_do, self._retry_config)
async def get_session(self, session_id: str) -> SessionDetail:
"""Get a session by ID."""
async def _do() -> SessionDetail:
resp = await self._request("GET", f"/v1/sessions/{session_id}")
return SessionDetail.model_validate(resp.json())
return await with_retry(_do, self._retry_config)
async def list_sessions(
self, limit: int = 20, offset: int = 0
) -> PaginatedResponse[SessionSummary]:
"""List sessions with pagination."""
async def _do() -> PaginatedResponse[SessionSummary]:
params: dict[str, Any] = {"limit": limit}
if offset > 0:
params["offset"] = offset
resp = await self._request("GET", "/v1/sessions", params=params)
return PaginatedResponse[SessionSummary].model_validate(resp.json())
return await with_retry(_do, self._retry_config)
async def delete_session(self, session_id: str) -> None:
"""Delete a session by ID."""
async def _do() -> None:
await self._request("DELETE", f"/v1/sessions/{session_id}")
return await with_retry(_do, self._retry_config)
async def list_messages(
self, session_id: str, limit: int = 50, offset: int = 0
) -> PaginatedResponse[Message]:
"""List messages for a session with pagination."""
async def _do() -> PaginatedResponse[Message]:
params: dict[str, Any] = {"limit": limit}
if offset > 0:
params["offset"] = offset
resp = await self._request("GET", f"/v1/sessions/{session_id}/messages", params=params)
return PaginatedResponse[Message].model_validate(resp.json())
return await with_retry(_do, self._retry_config)
async def stats(self) -> StatsResponse:
"""Get aggregated usage statistics."""
async def _do() -> StatsResponse:
resp = await self._request("GET", "/v1/stats")
return StatsResponse.model_validate(resp.json())
return await with_retry(_do, self._retry_config)