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 calls. 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
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 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 |
|
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
826 827 828 829 830 831 832 833 834 835 836 |
|
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
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 |
|
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
904 905 906 907 908 909 910 911 912 |
|
globals
globals() -> dict[str, object] | None
Return global objects accessible in prompts via the globals
attribute.
Source code in src/delphyne/stdlib/queries.py
971 972 973 974 975 976 |
|
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
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 |
|
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
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 |
|
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. In a multi-message chat with few-shot examples, this variable can have different values across examples. Also, it has the same value for the system prompt and the final instance prompt. |
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, as derived from |
example_id |
int | None
|
If the message is part of an example, indicate the
example number (examples are numbered starting from 1).
Otherwise, indicate |
example |
bool
|
Whether or not the message is part of an example
(redundant with |
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 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 |
|
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,
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
|
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
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 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 |
|
classify
classify(
query: AttachedQuery[T],
env: PolicyEnv,
model: LLM,
params: dict[str, object] | None = None,
select_examples: Sequence[ExampleSelector] = (),
mode: AnswerMode = None,
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
|
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
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 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 |
|
ProbInfo
dataclass
Bases: SearchMeta
Distribution probability, guaranteed to be nonempty and to sum to 1.
Source code in src/delphyne/stdlib/queries.py
1256 1257 1258 1259 1260 1261 1262 |
|
Models
LLM
Bases: ABC
Base class for an LLM.
Source code in src/delphyne/stdlib/models.py
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 |
|
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
451 452 453 454 455 |
|
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
457 458 459 460 461 462 463 464 465 466 |
|
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
483 484 485 486 487 488 489 490 491 492 |
|
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
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 |
|
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 |
tuple[Schema, ...]
|
Available tools. |
structured_output |
Schema | None
|
Provide a schema to enable structured output,
or |
Note
This class is hashable, as needed by LLMCache
. For soundness,
it is assumed that RequestOptions
dictionaries are immutable.
Source code in src/delphyne/stdlib/models.py
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 |
|
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
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 |
|
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
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 |
|
SystemMessage
dataclass
Source code in src/delphyne/stdlib/models.py
80 81 82 83 84 85 86 87 88 |
|
UserMessage
dataclass
Source code in src/delphyne/stdlib/models.py
91 92 93 94 95 96 97 98 |
|
AssistantMessage
dataclass
Source code in src/delphyne/stdlib/models.py
101 102 103 104 105 106 107 108 109 |
|
ToolMessage
dataclass
Source code in src/delphyne/stdlib/models.py
112 113 114 115 116 117 118 119 120 121 |
|
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. |
Warning
Dictionaries of this type should be treated as immutable, since
they are used as part of the hash of LLMRequest
objects.
Source code in src/delphyne/stdlib/models.py
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 |
|
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
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 |
|
make
staticmethod
make(annot: TypeAnnot[Any]) -> Schema
Build a schema from a Python type annotation
Source code in src/delphyne/stdlib/models.py
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 |
|
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
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
|
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
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 |
|
WithRetry
dataclass
Bases: LLM
Retrying with exponential backoff.
Source code in src/delphyne/stdlib/models.py
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 |
|
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
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 |
|
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.
LLMCache
objects can be created using the load_request_cache
context manager.
Source code in src/delphyne/stdlib/models.py
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 |
|
load_request_cache
load_request_cache(file: Path, *, mode: CacheMode)
Context manager that loads an LLM request cache from a YAML file.
Source code in src/delphyne/stdlib/models.py
626 627 628 629 630 631 632 633 634 |
|
CacheMode
CacheMode = Literal['read_write', 'off', 'create', 'replay']
Caching mode:
off
: the cache is disabled.read_write
: values can be read and written to the cache (no extra check is made).create
: the cache is used in write-only mode, and an exception is raided if a cached value already exists.replay
: all requests must hit the cache or an exception is raised.
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
239 240 241 242 243 244 245 246 247 248 249 250 251 |
|
TokenInfo
dataclass
Logprob information for a single token.
Source code in src/delphyne/stdlib/models.py
254 255 256 257 258 259 260 261 262 |
|
ModelPricing
dataclass
Source code in src/delphyne/stdlib/models.py
330 331 332 333 334 |
|
LLMResponseLogItem
dataclass
Source code in src/delphyne/stdlib/models.py
369 370 371 372 373 |
|
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
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
|
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
318 319 320 321 322 323 324 325 326 327 |
|
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'
Standard Models
standard_model
standard_model(
model: StandardModelName | str,
*,
options: RequestOptions | None = None,
pricing: ModelPricing | None | Literal["auto"] = "auto",
model_class: str | None = None,
) -> OpenAICompatibleModel
Obtain a standard model from OpenAI, Mistral, DeepSeek or Gemini.
Make sure that the following environment variables are set:
OPENAI_API_KEY
for OpenAI modelsMISTRAL_API_KEY
for Mistral modelsDEEPSEEK_API_KEY
for DeepSeek modelsGEMINI_API_KEY
for Gemini models
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
StandardModelName | str
|
The name of the model to use. The model provider is automatically inferred from this name. |
required |
options
|
RequestOptions | None
|
Additional options for the model, such as reasoning
effort or default temperature. The |
None
|
pricing
|
ModelPricing | None | Literal['auto']
|
Pricing model to use. If |
'auto'
|
model_class
|
str | None
|
An optional identifier for the model class (e.g., "reasoning_large"). When provided, class-specific budget metrics are reported, so that resource consumption can be tracked separately for different classes of models (e.g., tracking "num_requests__reasoning_large" separately from "num_requests__chat_small"). |
None
|
Raises:
Type | Description |
---|---|
ValueError
|
The provider or pricing model could not be inferred. |
Source code in src/delphyne/stdlib/standard_models.py
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 |
|
openai_model
openai_model(
model: OpenAIModelName | str,
*,
options: RequestOptions | None = None,
pricing: ModelPricing | None | Literal["auto"] = "auto",
model_class: str | None = None,
)
Obtain a standard model from OpenAI.
See standard_model
for details.
Source code in src/delphyne/stdlib/standard_models.py
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 |
|
mistral_model
mistral_model(
model: MistralModelName | str,
*,
options: RequestOptions | None = None,
pricing: ModelPricing | None | Literal["auto"] = "auto",
model_class: str | None = None,
)
Obtain a standard model from Mistral.
See standard_model
for details.
Source code in src/delphyne/stdlib/standard_models.py
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 |
|
deepseek_model
deepseek_model(
model: DeepSeekModelName | str,
*,
options: RequestOptions | None = None,
pricing: ModelPricing | None | Literal["auto"] = "auto",
model_class: str | None = None,
)
Obtain a standard model from DeepSeek.
See standard_model
for details.
Source code in src/delphyne/stdlib/standard_models.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
|
gemini_model
gemini_model(
model: GeminiModelName | str,
*,
options: RequestOptions | None = None,
pricing: ModelPricing | None | Literal["auto"] = "auto",
model_class: str | None = None,
)
Obtain a standard model from Gemini.
See standard_model
for details.
Source code in src/delphyne/stdlib/standard_models.py
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
|