ontocast.agent.common¶
LLMJsonParseError
¶
Bases: ValueError
A JSON syntax error in an LLM response, carrying the decoder's position.
Distinguished from the schema ValidationError that follows a successful
parse: only syntax errors get the position-window retry feedback, and only
they are abandoned on a repeated error class -- a model that emits the same
structural malformation twice emits it a third time, whereas a schema
mismatch does converge.
Source code in ontocast/agent/common.py
call_llm_with_retry(llm_tool, prompt, parser, prompt_kwargs, max_retries=3, retry_error_feedback=True, llm_graph_format=None)
async
¶
Call LLM and parse response with automatic retry on parsing failures.
This utility function implements a common pattern across agent functions: 1. Call LLM with a prompt 2. Parse the response 3. Retry if parsing fails (up to max_retries times)
On retry, if retry_error_feedback is True, the error message from the previous attempt is included in the prompt to help the LLM correct its output format.
Only parsing failures are retried with feedback. A transport-level failure (rate limit, connection error) propagates on the first occurrence: the retry exists to show the model its own malformed output, which is meaningless when no output arrived, and retrying would triple the request rate exactly when the provider is asking for less of it. The one exception is a request timeout: unlike a 429 it is not a provider "send less" signal, and losing the call silently costs a unit one of its few loop visits — so a single identical re-issue (per outer call) is allowed before the timeout propagates.
Retries back off exponentially with jitter, so N units failing to parse simultaneously do not re-issue in lockstep.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm_tool
|
LLMTool
|
The LLM tool instance to use for generation. |
required |
prompt
|
BasePromptTemplate
|
The prompt template to format and send to the LLM. |
required |
parser
|
BaseOutputParser[T]
|
The output parser to parse the LLM response. |
required |
prompt_kwargs
|
dict[str, Any]
|
Keyword arguments to pass to prompt.format_prompt(). |
required |
max_retries
|
int
|
Maximum number of retry attempts (default: 3). |
3
|
retry_error_feedback
|
bool
|
Whether to include error feedback in retry prompts (default: True). |
True
|
llm_graph_format
|
LLMGraphFormat | None
|
When set, passed explicitly to |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The parsed output of type T. |
Raises:
| Type | Description |
|---|---|
Exception
|
The provider's error on a transport failure, or the last parsing error once retries are exhausted. |
Source code in ontocast/agent/common.py
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 | |
parse_json_object(text)
¶
Parse LLM JSON output strictly, failing loudly with position context.
Langchain's parse_json_markdown degrades to a partial parser that
silently returns None — or a truncated prefix of the object — for
malformed input; validating that produced the informationless
input_value=None retry feedback, and retries repeated the same
malformation. Here strict parsing runs first, a fenced `` block is
extracted and strict-parsed as the next fallback, mismatched bracket
*kinds* are repaired as the last one (see :func:repair_bracket_kinds),
and any remaining failure raises :class:LLMJsonParseError` with the
strict error's line/column and a ±150-char context window, so retry
feedback names the exact broken spot.
strict=False mirrors the old path's one legitimate leniency — raw
control characters inside string literals, which the models do emit —
while every structural error still raises.
Source code in ontocast/agent/common.py
render_suggestions_prompt(suggestions, stage)
¶
Generate prompt templates from the suggestions.
Returns:
| Type | Description |
|---|---|
str
|
Combined string with general and concrete templates. |
str
|
Returns empty string if both fields are empty. |
Source code in ontocast/agent/common.py
repair_bracket_kinds(text)
¶
Rewrite each closing bracket to the kind its opener demands.
Models lose track of which frame they are closing while emitting a long
payload, and produce the right number of closers in the wrong kinds -- the
measured failure was ] } where } ] was due, at the tail of a
JSON-LD document nested inside a singleton list. The bracket counts balance,
so nothing upstream notices; only the decoder does.
The transform never inserts, deletes, or reorders: it only substitutes one character for another, and only where the document is already invalid. Repair is abandoned entirely (0 fixes, text unchanged) when a closer appears with no open frame, or when frames remain open at EOF -- that is genuine truncation, and closing it here would fabricate a payload the model never emitted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Candidate JSON that failed strict parsing. |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, int]
|
The repaired text and the number of characters substituted. |
Source code in ontocast/agent/common.py
strip_json_comments(text)
¶
Remove single-line // comments from JSON-like text while preserving string literals.
The LLM occasionally emits JavaScript-style // comments inside JSON output, which are not valid JSON. This function strips them by scanning the text token by token: JSON string literals (which may contain '//') are kept intact, while bare // … sequences are dropped.
Source code in ontocast/agent/common.py
strip_trailing_commas(text)
¶
Remove trailing commas before } or ] (invalid in strict JSON).
unescape_json_delimiters(text)
¶
Repair strings whose delimiting quotes the LLM escaped.
Observed malformation: "text_fragment": \"quoted text\", — the model
escapes the quotes that should open and close the JSON string, which is
invalid JSON and defeats the lenient parser too. This scans the text with
string-awareness: a \" where a key/value must start (after :,
,, { or [) is rewritten to ", and inside such a repaired
string a \" followed by a delimiter (,, }, ], :) is
rewritten as its closer. Legitimate \" escapes inside normally
delimited strings are left untouched. The same responses escape token
whitespace too (\",\n "action") — outside a string a backslash
is never valid JSON, so \n/\t/\r there are rewritten to the
whitespace they denote.