lpgcast.llm¶
The model client, its response cache, the tolerant JSON parser and usage accounting.
Modules:
| Name | Description |
|---|---|
cache |
On-disk cache of model responses, keyed by the logical request. |
client |
The model client: one JSON object per request, from any OpenAI-compatible endpoint. |
jsonparse |
Tolerant parsing of a model's JSON reply. |
usage |
Token and call accounting. |
Attributes¶
__all__ = ['CacheMissError', 'CachedResponse', 'ChatMessage', 'JsonCompletion', 'LLMCache', 'LLMClient', 'LLMConfigurationError', 'LLMJsonParseError', 'LLMRefusalError', 'LLMReplyError', 'LLMRequestTimeoutError', 'LLMTruncatedError', 'TokenUsage', 'UsageTracker', 'cache_key', 'parse_json_object', 'track_usage']
module-attribute
¶
Classes¶
CacheMissError
¶
CachedResponse
¶
Bases: BaseModel
One stored response.
Source code in lpgcast/llm/cache.py
Attributes¶
content = Field(description='Response text as received.')
class-attribute
instance-attribute
¶
finish_reason = Field(default=None, description='Provider stop reason.')
class-attribute
instance-attribute
¶
mode = Field(description='Response format the request was sent with.')
class-attribute
instance-attribute
¶
model = Field(default=None, description='Model the endpoint reported.')
class-attribute
instance-attribute
¶
refusal = Field(default=None, description="The model's refusal message, when it refused.")
class-attribute
instance-attribute
¶
usage = Field(default=None, description='Token counts, replayed on a hit.')
class-attribute
instance-attribute
¶
ChatMessage
¶
JsonCompletion
¶
Bases: BaseModel
The parsed reply to one :meth:LLMClient.acomplete_json request.
Source code in lpgcast/llm/client.py
Attributes¶
attempts = Field(description='Requests made, counting re-asks.')
class-attribute
instance-attribute
¶
cached = Field(description='Whether that reply came from the cache.')
class-attribute
instance-attribute
¶
content = Field(description='Raw text of the reply that parsed.')
class-attribute
instance-attribute
¶
data = Field(description='The parsed JSON object.')
class-attribute
instance-attribute
¶
mode = Field(description='Response format that reply was requested in.')
class-attribute
instance-attribute
¶
usage = Field(default_factory=TokenUsage, description='Tokens over all attempts.')
class-attribute
instance-attribute
¶
LLMCache
¶
Response cache under <dir>/llm/<key>.json.
Source code in lpgcast/llm/cache.py
Attributes¶
dir = Path(base).expanduser() / LLM_CACHE_SUBDIR
instance-attribute
¶
enabled
property
¶
require_hit
property
¶
settings = settings or CacheSettings()
instance-attribute
¶
writable
property
¶
Methods:¶
__init__(settings=None)
¶
Source code in lpgcast/llm/cache.py
aget(key)
async
¶
aset(key, entry)
async
¶
clear()
¶
Delete every entry; returns how many were removed.
get(key)
¶
The cached response for key, or None on a miss or unreadable entry.
Source code in lpgcast/llm/cache.py
path(key)
¶
set(key, entry)
¶
Store entry atomically; a no-op when the cache is not writable.
Source code in lpgcast/llm/cache.py
LLMClient
¶
A JSON-object client over openai.AsyncOpenAI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
LLMSettings | None
|
The endpoint and model. Defaults to the environment. |
None
|
cache
|
LLMCache | None
|
The response cache. Defaults to the environment's cache settings. |
None
|
http_client
|
AsyncClient | None
|
An |
None
|
Source code in lpgcast/llm/client.py
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 | |
Attributes¶
cache = cache if cache is not None else LLMCache()
instance-attribute
¶
settings = settings or LLMSettings()
instance-attribute
¶
usage = UsageTracker()
instance-attribute
¶
Methods:¶
__init__(settings=None, cache=None, *, http_client=None)
¶
Source code in lpgcast/llm/client.py
acomplete_json(messages, json_schema, *, schema_name='instance')
async
¶
Ask for one JSON object conforming to json_schema.
The reply is parsed, not validated: conformance to the schema is the
caller's check. A reply that is not a JSON object is re-asked up to
parse_retries times with the error shown, and given up on early
when the same syntax error repeats. A timeout is re-issued once. A truncated
or refused reply is not re-asked.
Raises:
| Type | Description |
|---|---|
LLMJsonParseError
|
no attempt produced a JSON object. |
LLMConfigurationError
|
no key or model, or the endpoint refuses the configuration. |
LLMRequestTimeoutError
|
a request timed out twice. |
LLMTruncatedError
|
the reply stopped at the output token limit. |
LLMRefusalError
|
the model refused or the provider filtered the reply. |
CacheMissError
|
a miss while the cache requires hits. |
APIError
|
any other provider failure, after SDK retries. |
Source code in lpgcast/llm/client.py
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 | |
from_settings(settings, *, http_client=None)
classmethod
¶
Build a client and its cache from top-level settings.
Source code in lpgcast/llm/client.py
LLMConfigurationError
¶
Bases: RuntimeError
The deployment, not the request, is at fault: no key, no model, a bad key, an unknown model, or a parameter the model refuses. Every other request would fail the same way, so callers should stop rather than skip.
Source code in lpgcast/llm/client.py
LLMJsonParseError
¶
LLMRefusalError
¶
Bases: LLMReplyError
The model refused, or the provider filtered the reply.
Source code in lpgcast/llm/client.py
LLMReplyError
¶
Bases: RuntimeError
A reply that arrived but cannot be used, and would not improve if re-asked.
Source code in lpgcast/llm/client.py
LLMRequestTimeoutError
¶
LLMTruncatedError
¶
Bases: LLMReplyError
The reply stopped at the output token limit (finish_reason == "length").
Source code in lpgcast/llm/client.py
TokenUsage
¶
Bases: BaseModel
Token counts for one call, as far as the provider reports them.
None means not reported, which is not zero.
Source code in lpgcast/llm/usage.py
Attributes¶
cache_read_input_tokens = Field(default=None, description="Prompt tokens served from the provider's prompt cache, counted inside input_tokens. Unrelated to LPGCast's response cache.")
class-attribute
instance-attribute
¶
input_tokens = Field(default=None, description='Prompt tokens.')
class-attribute
instance-attribute
¶
output_tokens = Field(default=None, description='Completion tokens.')
class-attribute
instance-attribute
¶
reasoning_tokens = Field(default=None, description='Thinking tokens, counted inside output_tokens.')
class-attribute
instance-attribute
¶
Methods:¶
__add__(other)
¶
Source code in lpgcast/llm/usage.py
UsageTracker
¶
Bases: BaseModel
Calls, events and tokens for a run or a scope within it.
Source code in lpgcast/llm/usage.py
Attributes¶
billed = Field(default_factory=TokenUsage, description='Tokens from live provider calls.')
class-attribute
instance-attribute
¶
cache_hits = Field(default=0, description='Responses served from cache.')
class-attribute
instance-attribute
¶
calls = Field(default=0, description='Provider calls that returned.')
class-attribute
instance-attribute
¶
calls_failed = Field(default=0, description='Provider calls that raised.')
class-attribute
instance-attribute
¶
chars_received = Field(default=0, description='Response characters.')
class-attribute
instance-attribute
¶
chars_sent = Field(default=0, description='Prompt characters sent.')
class-attribute
instance-attribute
¶
json_repairs = Field(default=0, description='Bracket-kind repairs.')
class-attribute
instance-attribute
¶
json_schema_fallbacks = Field(default=0, description='Switches from json_schema to json_object.')
class-attribute
instance-attribute
¶
parse_abandoned = Field(default=0, description='Requests given up on.')
class-attribute
instance-attribute
¶
parse_retries = Field(default=0, description='Re-asks after bad JSON.')
class-attribute
instance-attribute
¶
rate_limited = Field(default=0, description='Subset of calls_failed.')
class-attribute
instance-attribute
¶
refused = Field(default=0, description='Replies the model refused.')
class-attribute
instance-attribute
¶
rejected = Field(default=0, description='Subset of calls_failed: configuration faults.')
class-attribute
instance-attribute
¶
replayed = Field(default_factory=TokenUsage, description='Tokens of responses served from cache.')
class-attribute
instance-attribute
¶
timeouts = Field(default=0, description='Subset of calls_failed.')
class-attribute
instance-attribute
¶
truncated = Field(default=0, description='Replies cut off at the output token limit.')
class-attribute
instance-attribute
¶
Methods:¶
add_call(chars_sent, chars_received, usage)
¶
Charge one live provider call.
add_hit(usage)
¶
Functions:¶
cache_key(messages, json_schema, settings)
¶
SHA-256 of the logical request.
Keyed on the messages the caller passed, not on the wire request: a
json_object fallback adds a schema message, and a replay must hit
whichever format served the original run.
Source code in lpgcast/llm/cache.py
parse_json_object(text)
¶
Parse a reply as one JSON object.
Strict parse first; then the first fenced block; then the bracket-kind repair. Raw control characters inside strings are tolerated.
Returns:
| Type | Description |
|---|---|
tuple[dict[str, Any], int]
|
The object, and the number of brackets repaired (0 if none). |
Raises:
| Type | Description |
|---|---|
LLMJsonParseError
|
with the strict error's position and context. |
Source code in lpgcast/llm/jsonparse.py
track_usage(tracker=None)
¶
Charge calls made in this block (and tasks it spawns) to tracker too.
Task-local: concurrent episodes each charge their own tracker.