Search Algorithms and Utilities
Strategies
interact
interact(
step: Callable[
[AnswerPrefix, InteractStats], Opaque[P, Response[A | WrappedParseError, T]]
],
process: Callable[[A, InteractStats], Opaque[P, B | Error]],
tools: Mapping[type[T], Callable[[Any], Opaque[P, Any]]] | None = None,
inner_policy_type: type[P] | None = None,
) -> Strategy[Branch, P, B]
A standard strategy for creating conversational agents.
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 strategy
implements this pattern. It is meant to be inlined into a wrapping
strategy (since it is not decorated with strategy
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
step
|
Callable[[AnswerPrefix, InteractStats], Opaque[P, Response[A | WrappedParseError, T]]]
|
A parametric opaque space, induced by a strategy or query
that takes as an argument the current chat history (possibly
empty) along with some statistics, and returns an answer to
be processed. Oftentimes, this parametric opaque space is
induced by a query with a special |
required |
process
|
Callable[[A, InteractStats], Opaque[P, B | Error]]
|
An opaque space induced by a query or strategy that is
called on all model responses that are not tool calls, and
which returns either a final response to be returned, or an
error to be transmitted to the model as feedback (as an
|
required |
tools
|
Mapping[type[T], Callable[[Any], Opaque[P, Any]]] | None
|
A mapping from supported tool interfaces to implementations. Tools themselves can be implemented using arbitrary strategies or queries, allowing the integration of horizontal and vertical LLM pipelines. |
None
|
inner_policy_type
|
type[P] | None
|
Ambient inner policy type. This information is not used at runtime but it can be provided to help type inference when necessary. |
None
|
Source code in src/delphyne/stdlib/search/interactive.py
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 |
|
InteractStats
dataclass
Statistics maintained by interact
.
Attributes:
Name | Type | Description |
---|---|---|
num_rejected |
int
|
Number of answers that have been rejected so far, due to either parsing or processing errors. |
num_tool_call_rounds |
int
|
Number of tool call rounds that have been reuqetsed by the LLM so far (a round consists in a single message that can contain several tool call requests). |
Source code in src/delphyne/stdlib/search/interactive.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
Policies
dfs
dfs(
tree: Tree[Branch | Fail, P, T],
env: PolicyEnv,
policy: P,
max_depth: int | None = None,
max_branching: int | None = None,
) -> StreamGen[T]
The Standard Depth-First Search Algorithm.
Whenever a branching node is encountered, branching candidates are lazily enumerated and the corresponding child recursively searched.
Attributes:
Name | Type | Description |
---|---|---|
max_depth |
optional
|
maximum number of branching nodes that can be traversed in a path to success. |
max_branching |
optional
|
maximum number of children explored at each branching node. |
Source code in src/delphyne/stdlib/search/dfs.py
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 |
|
par_dfs
Parallel Depth-First Search.
Whenever a branching node is encountered, all branching candidates are computed at once and the associated children are explored in parallel.
Source code in src/delphyne/stdlib/search/dfs.py
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 |
|
Combinators
sequence
sequence(
policies: Iterable[PromptingPolicy], *, stop_on_reject: bool = True
) -> PromptingPolicy
sequence(
policies: Iterable[SearchPolicy[N]], *, stop_on_reject: bool = True
) -> SearchPolicy[N]
sequence(policies: Iterable[_AnyPolicy], *, stop_on_reject: bool = True) -> _AnyPolicy
Try a list of policies, search policies, or prompting policies in sequence.
- policies: An iterable of policies, search policies, or prompting policies to try in sequence.
- stop_on_reject: If True, stop the sequence as soon as one policy
sees all its resource requests denied. Note that this is
necessary for termination when
policies
is an infinite iterator.
Source code in src/delphyne/stdlib/misc.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 |
|
or_else
or_else(main: PromptingPolicy, other: PromptingPolicy) -> PromptingPolicy
or_else(main: SearchPolicy[N], other: SearchPolicy[N]) -> SearchPolicy[N]
or_else(main: _AnyPolicy, other: _AnyPolicy) -> _AnyPolicy
Take two policies, search policies, or prompting policies as arguments. Try the first one, and then the second one only if it fails (i.e., it does not produce any solution).
Source code in src/delphyne/stdlib/misc.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
|
nofail
Modify an opaque space to that branching over it can never fail.
If the stream associated with the opaque space gets exhausted and no solution is produced, the provided default value is used.
In demonstrations, the default value can be selected by using the
#no_fail_default
hint.
Source code in src/delphyne/stdlib/misc.py
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
|
iterate
iterate(
next: Callable[[S | None], Opaque[P, tuple[T | None, S]]],
transform_stream: Callable[[P], StreamTransformer | None] | None = None,
) -> Opaque[P, T]
Iteratively call a strategy or query, repeatedly feeding back the last call's output state into a new call and yielding values along the way.
A standard use case is to repeatedly call a query or strategy with a blacklist of previously generated values, so as to produce diverse success values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
next
|
Callable[[S | None], Opaque[P, tuple[T | None, S]]]
|
A parametric opaque space, induced by a query or stratey
that takes a state as an input (or |
required |
transform_stream
|
Callable[[P], StreamTransformer | None] | None
|
An optional mapping from the inner policy to a stream transformer to be applied to the resulting stream of generated values. |
None
|
Returns:
Type | Description |
---|---|
Opaque[P, T]
|
An opaque space enumerating all generated values. |
Source code in src/delphyne/stdlib/search/iteration.py
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 |
|
Opaque Spaces Sugar
just_dfs
Convenience shortcut to avoid passing lambdas to the get_policy
argument of using
, when using DFS in combination with the ambient
inner policy.
Source code in src/delphyne/stdlib/misc.py
60 61 62 63 64 65 66 |
|
just_compute
Convenience shortcut to avoid passing lambdas to the get_policy
argument of using
, in the case of sub-strategies that only feature
the Compute
effect.
Source code in src/delphyne/stdlib/misc.py
69 70 71 72 73 74 75 |
|
ambient_pp
ambient_pp(policy: PromptingPolicy) -> PromptingPolicy
Convenience shortcut to avoid passing lambdas to the get_policy
argument of Query.using
, when using the ambient inner policy as a
prompting policy.
Source code in src/delphyne/stdlib/misc.py
78 79 80 81 82 83 84 |
|
ambient
ambient(policy: F) -> F
Convenience shortcut to avoid passing lambdas to the get_policy
argument of Query.using
, when using the ambient inner policy as a
sub-policy (or as a sub- prompting policy).
Source code in src/delphyne/stdlib/misc.py
87 88 89 90 91 92 93 |
|
Universal Queries
UniversalQuery
dataclass
Bases: Query[object]
A universal query, implicitly defined by the surrounding context of
its call. See guess
for more information.
Attributes:
Name | Type | Description |
---|---|---|
strategy |
str
|
Fully qualified name of the surrounding strategy
(e.g., |
expected_type |
str
|
A string rendition of the expected answer type. |
tags |
Sequence[str]
|
Tags associated with the space induced by the query, which can be used to locate the exact location where the query is issued (the default tag takes the name of the variable that the query result is assigned to). |
locals |
dict[str, object]
|
A dictionary that provides the values of a subset of local variables or expressions (as JSON values). |
Experimental
This feature is experimental and subject to change.
Source code in src/delphyne/stdlib/universal_queries.py
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 |
|
strategy_source
property
strategy_source: str
Return the source code of the strategy that contains this query.
guess
guess(
annot: TypeAnnot[Any], /, *, using: Sequence[object]
) -> Strategy[Branch | Fail, IPDict, Any]
Attempt to guess a value of a given type, using the surrounding context of the call site along with the value of some local variables or expressions.
This function inspects the call stack to determine the context in
which it is called and issues a UniversalQuery
, with a tag
corresponding to the name of the assigned variable. A failure node is
issued if the oracle result cannot be parsed into the expected type.
For example:
res = yield from guess(int, using=[x, y.summary()])
issues a UniversalQuery
query tagged res
, with attribute
locals
a dictionary with string keys "x"
and "y.summary()"
.
Attributes:
Name | Type | Description |
---|---|---|
annot |
The expected type of the value to be guessed. |
|
using |
A sequence of local variables or expressions whose value should be communicated to the oracle (a label for each expression is automatically generated using source information). |
Note
Our use of an overloaded type should not be necessary anymore
when TypeExpr
is released with Python 3.14.
Experimental
This feature is experimental and subject to change.
Source code in src/delphyne/stdlib/universal_queries.py
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 |
|
Best-First Search
best_first_search
best_first_search(
tree: Tree[Branch | Factor | Value | Fail, P, T],
env: PolicyEnv,
policy: P,
child_confidence_prior: Callable[[int, int], float],
max_depth: int | None = None,
) -> StreamGen[T]
Best First Search Algorithm.
Nodes can be branching nodes or factor nodes. Factor nodes feature a confidence score in the [0, 1] interval. The total confidence of any node in the tree is the product of all confidence factors found on the path from the root to this node. The algorithm stores all visited branching nodes in a priority queue. At every step, it picks the node with highest confidence and spends an atomic amount of effort trying to generate a new child. If it succeeds, the first descendant branching node is added to the tree and the algorithm continues.
Also, the total confidence of each branching node is multiplied by
an additional penalty factor that depends on how many children have
been generated already, using the child_confidence_prior
argument.
This argument is a function that takes as its first argument the
depth of the current branching node (0 for the root, only
incrementing when meeting other branching nodes) and as its second
argument how many children have been generated so far. It returns
the additional penalty to be added.
The max_depth
parameter indicates the maximum depth a branch node
can have. The root has depth 0 and and only branch nodes count
towards increasing the depth.
Source code in src/delphyne/stdlib/search/bestfs.py
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 |
|
Abduction
Abduction
dataclass
Bases: Node
Node for the singleton tree produced by abduction
.
See abduction
for details.
An action is a successful proof of the main goal.
Source code in src/delphyne/stdlib/search/abduction.py
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 |
|
abduction
abduction(
prove: Callable[
[Sequence[tuple[Fact, Proof]], Fact | None],
Opaque[P, AbductionStatus[Feedback, Proof]],
],
suggest: Callable[[Feedback], Opaque[P, Sequence[Fact]]],
search_equivalent: Callable[[Sequence[Fact], Fact], Opaque[P, Fact | None]],
redundant: Callable[[Sequence[Fact], Fact], Opaque[P, bool]],
inner_policy_type: type[P] | None = None,
) -> Strategy[Abduction, P, Proof]
Higher-order strategy for proving a fact via recursive abduction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prove
|
Callable[[Sequence[tuple[Fact, Proof]], Fact | None], Opaque[P, AbductionStatus[Feedback, Proof]]]
|
take a sequence of already established facts as an
argument along with a new fact, and attempt to prove this new
fact. Three outcomes are possible: the fact is proved,
disproved, or a list of suggestions are made that might be
helpful to prove first. |
required |
suggest
|
Callable[[Feedback], Opaque[P, Sequence[Fact]]]
|
take some feedback from the |
required |
search_equivalent
|
Callable[[Sequence[Fact], Fact], Opaque[P, Fact | None]]
|
take a collection of facts along with a new
one, and return either the first fact of the list equivalent to
the new fact or |
required |
redundant
|
Callable[[Sequence[Fact], Fact], Opaque[P, bool]]
|
take a collection of established facts and decide whether they imply a new fact candidate. This is useful to avoid trying to prove and accumulating redundant facts. |
required |
Returns:
Type | Description |
---|---|
Strategy[Abduction, P, Proof]
|
a proof of the top-level goal. |
Source code in src/delphyne/stdlib/search/abduction.py
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 |
|
abduct_and_saturate
abduct_and_saturate(
tree: Tree[Abduction, P, Proof],
env: PolicyEnv,
policy: P,
max_rollout_depth: int = 3,
scoring_function: ScoringFunction = _default_scoring_function,
log_steps: LogLevel | None = None,
max_raw_suggestions_per_step: int | None = None,
max_reattempted_candidates_per_propagation_step: int | None = None,
max_consecutive_propagation_steps: int | None = None,
) -> StreamGen[Proof]
A saturation-based, sequential policy for abduction trees.
This policy proceeds by saturation: it repeatedly grows a set of proved facts until the main goal is proved or some limit is reached.
It does so by repeatedly performing rollouts. Each rollout starts
with the toplevel goal as a target, and attempts to prove this target
assuming all facts in proved
. If the target cannot be proved,
suggestions for auxilliary facts to prove first are requested before
another attempt is made. If still unsuccessful, one of the unproved
suggestions is set as the new target and the rollout proceeds (up to
some depth specified by max_rollout_depth
).
The algorithm maintains four, disjoint global sets of facts:
proved
: facts that have been successfully proveddisproved
: facts that have been disprovedredundant
: facts that are implied by the conjunction of all facts fromproved
.candidates
: facts that have been suggested but do not belong to any of the three sets above.
Each step of a rollout proceeds as follows:
- The current target is assumed to be a fact from the
candidates
set. Suggestions for new rollout targets are determined as follows (get_suggestions
):- The
suggest
node function returns a list of candidates. - All suggestions are normalized using the
search_equivalent
node function (one call per suggestion). - Each normalized suggestion is added (
add_candidate
) to one of theproved
,disproved
,redundant
, orcandidates
sets. At most one call to theprove
andis_redundant
node functions is made per suggestion. - Assuming the previous step results in at least one new fact
being proved, all candidates from the
candidates
set are re-examined until saturation (saturate
). - Remaining suggestions that are in
candidates
are potential taregts for the next rollout step.
- The
- Assuming the current target is still not proved, the next rollout
target is picked using the
scoring_function
parameter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_rollout_depth
|
int
|
The maximum depth of a rollout, as the maximal number of consecutive target goals that can be set (the first goal being the toplevel goal). |
3
|
scoring_function
|
ScoringFunction
|
Scoring function for choosing the next target goal at the end of each rollout step. |
_default_scoring_function
|
log_steps
|
LogLevel | None
|
If not |
None
|
max_raw_suggestions_per_step
|
int | None
|
Maximum number of suggestions from
the |
None
|
max_reattempted_candidates_per_propagation_step
|
int | None
|
Maximum number of candidates that are reattempted at each propagation step. Candidates that have been proposed more frequently are selected in priority. |
None
|
max_consecutive_propagation_steps
|
int | None
|
Maximum number of propagation
steps that are performed during a rollout step, or |
None
|
Warning
Facts must be hashable.
Warning
By design, this policy tries and makes as few calls to suggest
as possible, since those typically involve LLM calls. However,
by default, it can make a very large number of calls to prove
,
is_redundant
and search_equivalent
. This number can explode
as the number of candidates increases (in particular, it can be
quadratic in the number of candidates at each rollout step, due
to saturation). Thus, we recommend setting proper limits using
the hyperparameters whose name start with max_
.
Note
No fact is attempted to be proved if it is redundant with
already-proved facts. However, in the current implementation,
the set of proved facts can still contain redundancy. For
example, if x > 0
is established before the stronger x >= 0
is, the former won't be deleted.
Source code in src/delphyne/stdlib/search/abduction.py
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 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 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 |
|
ScoringFunction
Bases: Protocol
A function for assigning a score to candidate facts to prove, so that the fact with the highest score is chosen next.
Source code in src/delphyne/stdlib/search/abduction.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
|
__call__
__call__(num_proposed: float, num_visited: float) -> float
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_proposed
|
float
|
Normalized number of times the fact was
proposed by the |
required |
num_visited
|
float
|
Number of times the fact was chosen as target in one step of a rollout. |
required |
Source code in src/delphyne/stdlib/search/abduction.py
192 193 194 195 196 197 198 199 200 201 202 |
|
_default_scoring_function
_default_scoring_function(num_proposed: float, num_visited: float) -> float
The default scoring function for fact candidates.
See ScoringFunction
for details.
Source code in src/delphyne/stdlib/search/abduction.py
205 206 207 208 209 210 211 212 213 |
|