Queries and Prompting Policies
Queries
Query
Bases: AbstractQuery[T]
Base class for queries.
This class adds standard convenience features on top of
AbstractQuery
, using reflection to allow queries to be defined
concisely. Here is a simple example of a query type definition:
@dataclass class MakeSum(Query[list[int]]):
'''Given a list of allowed numbers and a target number, you
must find a sub-list whose elements sum up to the target.
Just answer with a list of numbers as a JSON object and
nothing else.'''
allowed: list[int] target: int
In general, a query type is a dataclass that inherits Query[T]
,
where T
is the query's answer type. In the example above, no
parser is specified and so oracles are requested to provide
structured answers as JSON objects, which are automatically parsed
into the answer type (list[int]
) using pydantic. Assuming that no
Jinja prompt file is provided, the docstring is used as a system
prompt and instance prompts are generated by simply serializing
MakeSum
instances into YAML.
All attributes of a query must be serializable by pydantic. They can be builtin types (int, list, dict...), custom dataclasses...
Customizing Prompts
System and instance prompts can be specified via Jinja templates.
The templates manager (TemplatesManager
) looks for templates named
"__system_prompt__
and/or
__instance_prompt__
class attributes. If none of these are
provided, the query's docstring is used as a system prompt and
DEFAULT_INSTANCE_PROMPT
is used as an instance prompt template.
All attributes from QueryTemplateArgs
are made available to
templates, with possibly extra ones.
Answer Modes and Configurations
A query can define several answer modes (AnswerMode
), each of
which can be associated with a different parser and set of settings.
By default, the only answer mode is None
. More answer modes can be
defined by setting class variable __modes__
.
The parser_for
method maps modes to parser specifications. Its
default implementation first checks whether the parser
method is
overriden, in which case it is used. Otherwise, the __parser__
attribute is checked. If none of these conditions hold, structured
is used as a default parser.
Allowing Multi-Message Exchanges and Tool Calls
A common pattern for interacting with LLMs is to have multi-message
exchanges where the full conversation history is resent repeatedly.
LLMs are also often allowed to request tool call. This interaction
pattern is implemented in the interact
standard strategy. It is
enabled by several features on the Query
side.
Answer Prefixes
If a query type has a prefix attribute with type AnswerPrefix
,
this attribute can be used to provide a chat history, to be added to
the query's prompt.
The Response
Type
If the query answer type is Response
, the query does not only
return a parsed answer, but also the LLM raw answer (which can be
appended to a chat history), and possibly a sequence of tool calls.
Source code in src/delphyne/stdlib/queries.py
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 |
|
parser
parser() -> Parser[T] | GenericParser
Method to override to provide a parser specification common to
all modes. Alternatively, the __parser__
class attribute can
be set. The first method allows more flexibility since parser
specifications can then depend on query attributes.
Source code in src/delphyne/stdlib/queries.py
810 811 812 813 814 815 816 817 818 819 820 |
|
parser_for
parser_for(mode: AnswerMode) -> Parser[T] | GenericParser
Obtain a parser speficiation for a given answer mode.
This method can be overriden. By default, it does the following:
- If the
parser
method is overriden, it uses it. - If
__parser__
is set as a parser, it is used. - If
__parser__
is set as a dictionary, the mode is used as a key to obtain a parser. - Otherwise,
structured
is used as a default parser.
Source code in src/delphyne/stdlib/queries.py
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 |
|
query_prefix
query_prefix() -> AnswerPrefix | None
Return the value of the prefix
attribute if it has type
annotation AnswerPrefix
or return None
.
Source code in src/delphyne/stdlib/queries.py
888 889 890 891 892 893 894 895 896 |
|
globals
globals() -> dict[str, object] | None
Return global objects accessible in prompts via the globals
attribute.
Source code in src/delphyne/stdlib/queries.py
950 951 952 953 954 955 |
|
using
using(
get_policy: Callable[[P], PromptingPolicy] | EllipsisType,
/,
inner_policy_type: type[P] | None = None,
) -> Opaque[P, T]
using(
get_policy: Callable[[P], PromptingPolicy] | EllipsisType,
/,
inner_policy_type: type[P] | None = None,
) -> Opaque[P, T]
Turn a query into an opaque space by providing a mapping from the ambient inner policy to a prompting policy.
Attributes:
Name | Type | Description |
---|---|---|
get_policy |
||
inner_policy_type |
Ambient inner policy type. This information is not used at runtime but it can be provided to help type inference when necessary. |
The optional inner_policy_type
argument is ignored at runtime
and can be used to help type checkers infer the type of the
ambient inner policy.
Source code in src/delphyne/stdlib/queries.py
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 |
|
run_toplevel
run_toplevel(env: PolicyEnv, policy: PromptingPolicy) -> Stream[T]
Obtain a search stream of query answers, given a prompting policy.
Source code in src/delphyne/stdlib/queries.py
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 |
|
Parser
dataclass
A parser specification.
In addition to a mapping from answers to answer type A
, a parser
also specifies query settings to be passed to oracles, along with
special formatting instructions to be rendered into the prompt.
Indeed, these components are typically tied and so specifying them
together in a single place is clearer.
Attributes:
Name | Type | Description |
---|---|---|
settings |
QuerySettings
|
The query settings associated with the parser. |
formatting |
FormattingMetadata
|
Formatting metadata. |
parse |
Callable[[Answer], A]
|
The parsing function, which is allowed to raise
the |
Source code in src/delphyne/stdlib/queries.py
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 |
|
wrap_errors
property
wrap_errors: Parser[A | WrappedParseError]
Wrap parse errors into WrappedParseError
.
response
property
response: GenericParser
Wrap answers into full Response
objects.
Return a GenericParser
so that the list of supported tools can
be extracted from the query's answer type.
json
property
json: GenericParser
Parse a string as a JSON object.
Return a GenericParser
so that the target type can be
extracted from the query's answer type.
yaml
property
yaml: GenericParser
Parse a string as a YAML object.
Return a GenericParser
so that the target type can be
extracted from the query's answer type.
map
map(f: Callable[[A], B | ParseError], /, *, catch_exn: bool = False) -> Parser[B]
Apply a function to the parser's output.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
f
|
Callable[[A], B | ParseError]
|
The function to apply, which is allowed to raise or
return |
required |
catch_exn
|
bool
|
If |
False
|
Source code in src/delphyne/stdlib/queries.py
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 |
|
validate
validate(
f: Callable[[A], ParseError | None], /, *, catch_exn: bool = False
) -> Parser[A]
Check that the parser's output satisfies a given property.
If the property is satisfied, function f
must return None
.
Otherwise, it may return or raise a ParseError
.
Source code in src/delphyne/stdlib/queries.py
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 |
|
response_with
Wrap answers into full Response
objects.
Source code in src/delphyne/stdlib/queries.py
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 |
|
json_as
json_as(type: TypeAnnot[U]) -> Parser[U]
Parse a string as a JSON object.
Info
This method currently does not work very well with type
inference since its arguments do not allow inferring the
type of U
. This should work better once TypeAnnot
can be
replaced with TypeExpr
(incoming in Python 3.14).
Source code in src/delphyne/stdlib/queries.py
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 |
|
yaml_as
yaml_as(type: TypeAnnot[U]) -> Parser[U]
Parse a string as a YAML object.
Info
This method currently does not work very well with type
inference since its arguments do not allow inferring the
type of U
. This should work better once TypeAnnot
can be
replaced with TypeExpr
(incoming in Python 3.14).
Source code in src/delphyne/stdlib/queries.py
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
|
GenericParser
dataclass
A mapping from a query's answer type to a parser specification.
This is useful to avoid redundancy when specifying parsers. In particular, it allows writing:
@dataclass
class MyQuery(Query[Response[Out, Tool1 | Tool2]]):
...
__parser__ = last_block.yaml.response
instead of:
__parser__ = last_block.yaml_as(Out).response_with(Tool1 | Tool2)
Attributes:
Name | Type | Description |
---|---|---|
for_type |
_GenericParserFn
|
A function that takes a type annotation and returns a
|
Source code in src/delphyne/stdlib/queries.py
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 |
|
wrap_errors
property
wrap_errors: GenericParser
Wrap parse errors into WrappedParseError
.
A runtime check is performed to ensure that the answer type
features WrappedParseError
.
response
property
response: GenericParser
Wrap answers into full Response
objects.
Possible tool calls are extracted from the query's answer type
and an exception is raised if this type does not have the form
Response[..., ...]
.
_GenericParserFn
Bases: Protocol
Type of functions wrapped by GenericParser
.
Source code in src/delphyne/stdlib/queries.py
483 484 485 486 487 488 |
|
ParserDict
ParserDict: dict[AnswerMode, Parser[Any] | GenericParser]
A mapping from answer modes to parser specifications.
Can be used as a value for the __parser__
class attribute of queries.
Response
dataclass
Answer type for queries that allow follow-ups.
Response
values give access to both the raw LLM response (to be
passed pass in AnswerPrefix
) and to eventual tool calls. See the
Parser.response
, Parser.response_with
, and
GenericParser.response
methods for creating parsers that produce
Response
values.
Attributes:
Name | Type | Description |
---|---|---|
answer |
Answer
|
The raw, unparsed LLM answer. |
parsed |
FinalAnswer[F] | ToolRequests[T]
|
Either the parsed answer wrapped in |
Source code in src/delphyne/stdlib/queries.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
|
FinalAnswer
dataclass
See Response
.
Source code in src/delphyne/stdlib/queries.py
86 87 88 89 90 91 92 |
|
ToolRequests
dataclass
See Response
.
Source code in src/delphyne/stdlib/queries.py
95 96 97 98 99 100 101 |
|
WrappedParseError
dataclass
A wrapped parse error that is returned to a strategy instead of causing a failure.
For queries that declare a return type of the form Response[... |
WrappedParseError, ...]
, parse errors do not result in failures but
are instead wrapped and returned, to be handled explicitly by the
surrounding strategy. For example, when building conversational
agents with interact
, having the query include WrappedParseError
in its return type allows explicitly asking the agent to fix parse
errors instead of failing (or having the policy retry an identical
prompt).
See the Parser.wrap_errors
and GenericParser.wrap_errors
methods
for creating parsers that produce WrappedParseError
values.
Attributes:
Name | Type | Description |
---|---|---|
error |
ParseError
|
The wrapped parse error. |
Source code in src/delphyne/stdlib/queries.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
|
QueryTemplateArgs
Bases: TypedDict
Template arguments passed to all query templates.
For particular kinds of templates, additional arguments may be
provided (e.g., feedback
for feedback prompts).
Attributes:
Name | Type | Description |
---|---|---|
query |
Query[Any]
|
The query instance. |
mode |
AnswerMode
|
The requested answer mode. |
available_modes |
Sequence[AnswerMode]
|
The sequence of all available answer modes for the query type. |
params |
dict[str, Any]
|
The query hyperparameters (e.g., as passed to |
format |
FormattingMetadata
|
Formatting metadata. |
Source code in src/delphyne/stdlib/queries.py
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 |
|
Standard Parsers
structured_as
structured_as(type: TypeAnnot[T]) -> Parser[T]
Parse an LLM structured answer into a given target type.
Warning
Only dataclass types are supported, since most LLM providers only support structured output and tool calls for JSON objects.
Source code in src/delphyne/stdlib/queries.py
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 |
|
final_tool_call_as
final_tool_call_as(annot: TypeAnnot[T]) -> Parser[T]
Variant of structured_as
, where the query answer type is presented
to oracles as a tool, which must be called to produce the final
answer. This provides an alternative to "structured", which
additionally allows a chain of thoughts to precede the final answer.
Warning
Only dataclass types are supported, since most LLM providers only support structured output and tool calls for JSON objects.
Source code in src/delphyne/stdlib/queries.py
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 |
|
structured
module-attribute
structured = GenericParser(structured_as)
Generic parser associated with structured_as
.
final_tool_call
module-attribute
final_tool_call = GenericParser(final_tool_call_as)
Generic parser associated with final_tool_call_as
.
last_code_block
module-attribute
last_code_block: Parser[str] = update_formatting(
lambda f: replace(f, where="last_code_block")
)
Parser that extracts the last code block from a text answer.
get_text
module-attribute
get_text = Parser[str](
QuerySettings(),
FormattingMetadata(where="full_answer", what="text"),
_get_text_answer,
)
Parser that extracts the text content of an answer.
A runtime error is raised if the answer contains structured content.
Prompting Policies
few_shot
few_shot(
query: AttachedQuery[T],
env: PolicyEnv,
model: LLM,
*,
params: dict[str, object] | None = None,
select_examples: Sequence[ExampleSelector] = (),
mode: AnswerMode = None,
enable_logging: bool = True,
temperature: float | None = None,
num_completions: int = 1,
max_requests: int | None = None,
no_wrap_parse_errors: bool = False,
iterative_mode: bool = False,
) -> StreamGen[T]
The standard few-shot prompting policy.
A prompt is formed by concatenating a system prompt, a series of examples (each of which consists in an instance prompt followed by an answer), and a final answer prompt. Then, answers are repeatedly sampled and parsed, until a spending request is declined.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
query
|
AttachedQuery[T]
|
The query to answer. env: The policy environment. |
required |
model
|
LLM
|
The LLM to use for answering the query |
required |
params
|
dict[str, object] | None
|
Prompt hyperparameters, which are passed to prompt
templates as a |
None
|
select_examples
|
Sequence[ExampleSelector]
|
A series of filters for selecting examples, to be applied in sequence. By default, no filter is used and so all available examples are fetched. |
()
|
mode
|
AnswerMode
|
The answer mode to use for parsing the query answer. |
None
|
enable_logging
|
bool
|
Whether to log raw oracle responses. |
True
|
temperature
|
float | None
|
The temperature parameter to use with the LLM, as a number from 0 to 2. |
None
|
num_completions
|
int
|
The number of completions to request for each LLM call. Note that most LLM providers only bill input tokens once, regardless of the number of completions. |
1
|
max_requests
|
int | None
|
The maximum number of LLM requests to perform before the resulting seach stream terminates, if any. |
None
|
no_wrap_parse_errors
|
bool
|
If set to |
False
|
iterative_mode
|
bool
|
If set to This special mode allows creating simple conversational
agents with very little effort, by only defining a single
query. However, it does not support tool calls, and the
demonstration language cannot be used to illustrate how
|
False
|
Source code in src/delphyne/stdlib/queries.py
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 |
|
classify
classify(
query: AttachedQuery[T],
env: PolicyEnv,
model: LLM,
params: dict[str, object] | None = None,
select_examples: Sequence[ExampleSelector] = (),
mode: AnswerMode = None,
enable_logging: bool = True,
top_logprobs: int = 20,
temperature: float = 1.0,
bias: tuple[str, float] | None = None,
) -> StreamGen[T]
Execute a classification query, attaching a probability distribution to the attached answer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
query
|
AttachedQuery[T]
|
The query to answer. |
required |
env
|
PolicyEnv
|
The global policy environment. |
required |
model
|
LLM
|
The LLM to use for answering the query. |
required |
params
|
dict[str, object] | None
|
Prompt hyperparameters. |
None
|
select_examples
|
Sequence[ExampleSelector]
|
Example selector. |
()
|
mode
|
AnswerMode
|
The answer mode to use for parsing the query answer. |
None
|
enable_logging
|
bool
|
Whether to log raw oracle responses. |
True
|
top_logprobs
|
int
|
The number of top logprobs to request from the LLM, putting an upper bound on the support size of the classifier's output distributions. |
20
|
temperature
|
float
|
A temperature to apply to the classifier's output distribution (a temperature of 0 means that only top elements are assigned a nonzero probability). |
1.0
|
bias
|
tuple[str, float] | None
|
When |
None
|
See few_shot
for details on some of the arguments above.
Source code in src/delphyne/stdlib/queries.py
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 |
|
ProbInfo
dataclass
Bases: SearchMeta
Distribution probability, guaranteed to be nonempty and to sum to 1.
Source code in src/delphyne/stdlib/queries.py
1252 1253 1254 1255 1256 1257 1258 |
|
Models
LLM
Bases: ABC
Base class for an LLM.
Source code in src/delphyne/stdlib/models.py
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 |
|
estimate_budget
estimate_budget(req: LLMRequest) -> Budget
Estimate the budget that is required to process a request.
Source code in src/delphyne/stdlib/models.py
410 411 412 413 414 |
|
add_model_defaults
abstractmethod
add_model_defaults(req: LLMRequest) -> LLMRequest
Rewrite a request to take model-specific defaults into account.
A model can carry default values for some of the request fields (e.g. the model name). Thus, requests must be processed through this function right before they are executed or cached.
Source code in src/delphyne/stdlib/models.py
416 417 418 419 420 421 422 423 424 425 |
|
stream_request
stream_request(chat: Chat, options: RequestOptions) -> AsyncIterable[str]
Stream the text answer to a request.
This is currently not used but could be leveraged by the VSCode extension in the future.
Source code in src/delphyne/stdlib/models.py
442 443 444 445 446 447 448 449 450 451 |
|
send_request
send_request(req: LLMRequest, cache: LLMCache | None) -> LLMResponse
Send a request to a model and return the response.
This function is allowed to raise exceptions (some
provider-specific), including LLMBusyException
for cases where
retrials may be warranted.
Attributes:
Name | Type | Description |
---|---|---|
req |
The request to send. |
|
cache |
An optional cache to use for the request. |
Source code in src/delphyne/stdlib/models.py
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 |
|
LLMRequest
dataclass
An LLM chat completion request.
Attributes:
Name | Type | Description |
---|---|---|
chat |
Chat
|
The chat history. |
num_completions |
int
|
The number of completions to generate. Note that most LLM providers only bill input tokens once, regardless of the number of requested completions. |
options |
RequestOptions
|
Request options. |
tools |
Sequence[Schema]
|
Available tools. |
structured_output |
Schema | None
|
Provide a schema to enable structured output,
or |
Source code in src/delphyne/stdlib/models.py
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 |
|
LLMResponse
dataclass
Response to an LLM request.
Attributes:
Name | Type | Description |
---|---|---|
outputs |
Sequence[LLMOutput]
|
Generated completions. |
budget |
Budget
|
Budget consumed by the request. |
log_items |
list[LLMResponseLogItem]
|
Log items generated while evaluating the request. |
model_name |
str | None
|
The name of the model used for the request, which is
sometimes more detailed than the model name passed in
|
usage_info |
dict[str, Any] | None
|
Additional usage info metadata, in a provider-specific format. |
Source code in src/delphyne/stdlib/models.py
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 |
|
AbstractTool
Base class for an LLM tool interface.
A new tool interface can be added by defining a dataclass S
that
inherits AbstractTool[T]
, with T
the tool output type. Instances
of S
correspond to tool calls, and an actual tool implementation
maps values of type S
to values of type T
.
A JSON tool specification can be extracted through the
tool_name
, tool_description
and tool_answer_type
class
methods. The render_result
method describes how to render the
output of a tool implementation, in a way that can be added back as
a message in a chat history.
Source code in src/delphyne/stdlib/models.py
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 |
|
SystemMessage
dataclass
Source code in src/delphyne/stdlib/models.py
77 78 79 80 81 82 83 84 85 |
|
UserMessage
dataclass
Source code in src/delphyne/stdlib/models.py
88 89 90 91 92 93 94 95 |
|
AssistantMessage
dataclass
Source code in src/delphyne/stdlib/models.py
98 99 100 101 102 103 104 105 106 |
|
ToolMessage
dataclass
Source code in src/delphyne/stdlib/models.py
109 110 111 112 113 114 115 116 117 118 |
|
RequestOptions
Bases: TypedDict
LLM request options, inspired from the OpenAI chat API.
All values are optional.
Attributes:
Name | Type | Description |
---|---|---|
model |
str
|
The name of the model to use for the request. |
reasoning_effort |
Literal['minimal', 'low', 'medium', 'high']
|
The reasoning effort to use for the request, when applicable (e.g., for GPT-5 or o3). |
tool_choice |
Literal['auto', 'none', 'required']
|
How the model should select which tool (or tools)
to use when generating a response. |
temperature |
float
|
The temperature to use for sampling, as a value between 0 and 2. |
max_completion_tokens |
int
|
The maximum number of tokens to generate. |
logprobs |
bool
|
Whether to return log probabilities for the generated tokens. |
top_logprobs |
int
|
The number of top log probabilities to return for each generated token, as an integer between 0 and 20. |
Source code in src/delphyne/stdlib/models.py
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 |
|
Schema
dataclass
The description of a schema for structured output or tool use.
Attributes:
Name | Type | Description |
---|---|---|
name |
str
|
Name of the tool or structured output type. |
description |
str | None
|
Optional description. |
schema |
Any
|
The JSON schema of the tool or structured output type,
typically generated using pydantic's |
Source code in src/delphyne/stdlib/models.py
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 |
|
make
staticmethod
make(annot: TypeAnnot[Any]) -> Schema
Build a schema from a Python type annotation
Source code in src/delphyne/stdlib/models.py
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 |
|
LLMOutput
dataclass
A single LLM chat completion.
Attributes:
Name | Type | Description |
---|---|---|
content |
str | Structured
|
The completion content, as a string or as a structured object (if structured output was requested). |
tool_calls |
Sequence[ToolCall]
|
A sequence of tool calls made by the model, if any. |
finish_reason |
FinishReason
|
The reason why the model stopped generating content. |
logprobs |
Sequence[TokenInfo] | None
|
Optional sequence of token log probabilities, if requested. |
reasoning_content |
str | None
|
Reasoning chain of thoughts, if provided (the DeepSeek API returns reasoning tokens, while the OpenAI API generally does not). |
Source code in src/delphyne/stdlib/models.py
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
|
FinishReason
FinishReason: Literal['stop', 'length', 'content_filter', 'tool_calls']
Reason why the LLM stopped generating content.
DummyModel
dataclass
Bases: LLM
A model that always fails to generate completions.
Used by the answer_query
command in particular.
Source code in src/delphyne/stdlib/models.py
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
|
WithRetry
dataclass
Bases: LLM
Retrying with exponential backoff.
Source code in src/delphyne/stdlib/models.py
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 |
|
CachedModel
dataclass
Bases: LLM
Wrap a model to use a given cache.
Note
The LLM.send_request
method has a cache
argument that can be
used as a replacement for the CachedModel
wrapper. In
addition, all standard prompting policies use a global request
cache (see PolicyEnv
) when available. Thus, external users
should rarely need to manually wrap models with CachedModel
.
Source code in src/delphyne/stdlib/models.py
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 |
|
LLMCache
dataclass
A cache for LLM requests.
More precisely, what are cached are (r, i)
pairs where r
is a
request and i
is the number of times the request has been answered
since the model was instantiated. This way, caching works even when
a policy samples multiple answers for the same request.
Multiple models can share the same cache.
Source code in src/delphyne/stdlib/models.py
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 |
|
Token
dataclass
A token produced by an LLM.
Attributes:
Name | Type | Description |
---|---|---|
token |
str
|
String representation of the token. |
bytes |
Sequence[int] | None
|
Optional sequence of integers representing the token's byte encoding. |
Source code in src/delphyne/stdlib/models.py
217 218 219 220 221 222 223 224 225 226 227 228 229 |
|
TokenInfo
dataclass
Logprob information for a single token.
Source code in src/delphyne/stdlib/models.py
232 233 234 235 236 237 238 239 240 |
|
ModelPricing
dataclass
Source code in src/delphyne/stdlib/models.py
308 309 310 311 312 |
|
LLMResponseLogItem
dataclass
Source code in src/delphyne/stdlib/models.py
347 348 349 350 351 |
|
LLMBusyException
dataclass
Bases: Exception
This exception should be raised when an LLM call failed due to a
timeout or a rate limit error that warrants a retry. In particular,
it should not be raised for ill-formed requests (those assumptions
should not be caught) or when the LLM gave a bad answer (in which
case budget was consumed and should be counted, while errors are
added into LLMResponse
).
See WithRetry
for adding retrial logic to LLMs.
Source code in src/delphyne/stdlib/models.py
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 |
|
BudgetCategory
BudgetCategory: Literal[
"num_requests",
"num_completions",
"input_tokens",
"cached_input_tokens",
"output_tokens",
"price",
]
Standard metrics to measure LLM inference usage.
budget_entry
budget_entry(category: BudgetCategory, model_class: str | None = None) -> str
Return a string that can be used as a key in a budget dictionary.
Source code in src/delphyne/stdlib/models.py
296 297 298 299 300 301 302 303 304 305 |
|
NUM_REQUESTS
module-attribute
NUM_REQUESTS = 'num_requests'
NUM_COMPLETIONS
module-attribute
NUM_COMPLETIONS = 'num_completions'
NUM_INPUT_TOKENS
module-attribute
NUM_INPUT_TOKENS = 'input_tokens'
NUM_CACHED_INPUT_TOKENS
module-attribute
NUM_CACHED_INPUT_TOKENS = 'cached_input_tokens'
NUM_OUTPUT_TOKENS
module-attribute
NUM_OUTPUT_TOKENS = 'output_tokens'
DOLLAR_PRICE
module-attribute
DOLLAR_PRICE = 'price'