Spaces:
Paused
Paused
File size: 63,352 Bytes
f6686e1 | 1 2 3 4 5 6 7 8 9 10 11 12 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 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 160 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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 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 579 580 581 582 583 584 585 586 587 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 628 629 630 631 632 633 634 635 636 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 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 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 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 | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.10.0" />
<title>tinytroupe.utils.semantics API documentation</title>
<meta name="description" content="Semantic-related mechanisms." />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>tinytroupe.utils.semantics</code></h1>
</header>
<section id="section-intro">
<p>Semantic-related mechanisms.</p>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">"""
Semantic-related mechanisms.
"""
from tinytroupe.utils import llm
@llm()
def correct_according_to_rule(observation, rules) -> str:
"""
Given an observation and a one or more rules, this function rephrases or completely changes the observation in accordance with what the rules
specify. Some guidelines:
- Rules might require changes either to style or to content.
- The rephrased observation should be coherent and consistent with the original observation, unless the rules require otherwise.
- If the rules require, the corrected observation can contradict the original observation.
- Enforce the rules very strictly, even if the original observation seems correct or acceptable.
- Rules might contain additional information or suggestions that you may use to improve your output.
## Examples
Observation: "You know, I am so sad these days."
Rule: "I am always happy and depression is unknown to me"
Modified observation: "You know, I am so happy these days."
Args:
observation: The observation that should be rephrased or changed. Something that is said or done, or a description of events or facts.
rules: The rules that specifies what the modidfied observation should comply with.
Returns:
str: The rephrased or corrected observation.
"""
# llm decorator will handle the body of this function
@llm()
def restructure_as_observed_vs_expected(description) -> str:
"""
Given the description of something (either a real event or abstract concept), but that violates an expectation, this function
extracts the following elements from it:
- OBSERVED: The observed event or statement.
- BROKEN EXPECTATION: The expectation that was broken by the observed event.
- REASONING: The reasoning behind the expectation that was broken.
If in reality the description does not mention any expectation violation, then the function should instead extract
the following elements:
- OBSERVED: The observed event.
- MET EXPECTATION: The expectation that was met by the observed event.
- REASONING: The reasoning behind the expectation that was met.
This way of restructuring the description can be useful for downstream processing, making it easier to analyze or
modify system outputs, for example.
## Examples
Input: "Ana mentions she loved the proposed new food, a spicier flavor of gazpacho. However, this goes agains her known dislike
of spicy food."
Output:
"OBSERVED: Ana mentions she loved the proposed new food, a spicier flavor of gazpacho.
BROKEN EXPECTATION: Ana should have mentioned that she disliked the proposed spicier gazpacho.
REASONING: Ana has a known dislike of spicy food."
Input: "Carlos traveled to Firenzi and was amazed by the beauty of the city. This was in line with his love for art and architecture."
Output:
"OBSERVED: Carlos traveled to Firenzi and was amazed by the beauty of the city.
MET EXPECTATION: Carlos should have been amazed by the beauty of the city.
REASONING: Carlos loves art and architecture."
Args:
description (str): A description of an event or concept that either violates or meets an expectation.
Returns:
str: The restructured description.
"""
# llm decorator will handle the body of this function
@llm()
def extract_observed_vs_expected_rules(description):
"""
Given the description of something (either a real event or abstract concept), extract:
- The object or person about whom something is said.
- A list where each element contains:
* The name of a behavior or property that is expected to be observed.
* The typical or expected observation.
* The actual observation. If this does not match the expected observation, this should be made very clear.
* A proposed correction to the observation, if possible.
# Example:
**Description:**
```
Quality feedback
This is the action that was generated by the agent:
{'type': 'TALK', 'content': "I might consider buying bottled gazpacho, although I prefer making it fresh at home, and I find that most pre-packaged products don't meet my expectations in terms of quality. ", 'target': 'Michael Thompson'}
Unfortunately, the action failed to pass the quality checks. The following problems were detected.
Problem: The action does not adhere to the persona specification.
Score = 5 (out of 9). Justification = The next action of Emily Carter, which involves expressing her opinion on bottled gazpacho, aligns with her persona specification of being critical and having high standards for products. She articulates her preferences and concerns about quality, which is consistent with her persona traits of being overly critical and rarely satisfied. However, she seems too ready to consider it, going against her strong rejection of new products and services. Therefore, it deviates substantially from her persona, leading to a score of 5.
Problem: The action is not suitable to the situation or task.
Score = 5 (out of 9). Justification = The next action, where Emily expresses her consideration about buying bottled gazpacho, aligns with the task of discussing her opinion on the product. However, it fails to give a clear "yes" or "no" answer, that was requested by her interviewer.
```
**Output:**
```
{
"object": "Emily Carter",
"behavior": [
{
"name:": "Persona Adherence",
"expected": "She is very critical and have high standards for products. Would never adopt a new product unless it meets her expectations.",
"actual": "She seems more inclined than expected to try the product.",
"correction": "She should say she won't consider buying bottled gazpacho, and give reasons for that."
},
{
"name:": "Task Suitability",
"expected": "She should give a clear 'yes' or 'no' answer to the question.",
"actual": "She doesn't give a clear 'yes' or 'no' answer to the question, but instead providing more nuanced feedback.",
"correction": "She should give a clear 'yes' or 'no' answer to the question, and optionally provide additional nuanced feedback."
}
]
}
```
"""
# llm decorator will handle the body of this function
@llm()
def formulate_corrective_rule(feedback) -> str:
"""
Given the feedback about something (either a real event or abstract concept) that violated an expectation,
this function transforms it into a general rule that must be followed in the future to avoid breaking the expectation again.
The feedback always refers to some actual behavior, fact or event, and some broken expectation. The abstracted rule should
specify that this expectation should not be violated in the future, and the behavior, fact or event not repeated. The idea is
to learn from past mistakes, so that the rule is a way to avoid them in the future.
The rule is meant to CHANGE the actual behavior, facts or events, so that it CONFORMS to the expectation, regardless of whether the
expectation is a good or bad one. This is critical, because the rule will be refered in the future as a guideline
about what must happen or be done.
For instance, if the feedback is of the form (modulo grammatical adjustments):
OBSERVED BEHAVIOR, but EXPECTED BEHAVIOR, because REASONING.
then the rule would be of the form:
"I should have EXPECTED BEHAVIOR, because REASONING, and never OBSERVED BEHAVIOR."
DO NOT make moral judgements about the expectation or the behavior, fact or event. Even if the expectation is bad,
the correct rule remains important, since there are legitimate cases where this is necessary (e.g., a simulation of
a person with a negative behavior, in the context of psychological research; or an evil character in a movie script).
## Examples
Feedback: "Ana mentions she loved the proposed new food, a spicier flavor of gazpacho. However, this goes agains her known dislike
of spicy food."
Rule: "Whenever I'm proposed spicy foods, I should reject the proposal, because I don't like spicy foods."
"""
# llm decorator will handle the body of this function
@llm(enable_json_output_format=False)
def combine_texts(*texts) -> str:
"""
Given a list of input texts, this function combines them into a single text, ensuring that the
output is coherent, consistent, and logically structured. In particular, the resulting combination
must follow these rules:
- The combination consolidates the information from the inputs. It **does not** just concatenate them.
- Information that was repeated across the inputs is not repeated in the output, but rather unified and consolidated there.
- The combination preserves all the essential information from the inputs, but it is not a simple copy of them.
- If information from some inputs can be combined in a more concise formulation, this new formulation should be used in the output.
This allows to reduce redundancy and improve clarity.
- The combination might be larger than the sum of the inputs, since it preserves the information from the inputs.
- If the various inputs seem to follow some common format or style, the output must follow that format or style too.
- The combination can contain inconsistencies or contradictions, in case the inputs do.
Args:
*texts: A list of input texts to be combined.
Returns:
str: The combined text.
"""
# llm decorator will handle the body of this function
@llm(enable_json_output_format=False)
def extract_information_from_text(query: str, text: str, context:str=None) -> str:
"""
Given a text and a query, this function extracts the information from the text that either answers the query directly or
provides relevant information related to it. The query can be a question, a request for specific information, or a general
request for details about the text. If the desired information is not present in the text, the function should return an empty string.
If a context is provided, it is used to help in understanding the query or the text, and to provide additional background
information or expectations about the input/output. Any requests in the context are respected and enforced in the output.
Args:
query (str): The query that specifies what information to extract.
text (str): The text from which to extract information.
context (str, optional): Additional context that might help in extracting the information. This can be used to provide
background information or specify expectations about the input/output.
Returns:
str: The extracted information that answers the query. If no information is found, an empty string is returned.
"""
# llm decorator will handle the body of this function
@llm(enable_json_output_format=False)
def accumulate_based_on_query(query: str, new_entry:str, current_accumulation:str, context=None) -> str:
"""
This function accumulates information that is relevant to a given query. It takes a new entry and updates the current accumulation of information
such that the final accumulation preserves its original information and in addition integrates the new entry in a way that addresses the query or provides related information.
Details are **never** suppressed, but rather expanded upon, while mantaining the coherence and structure of the overall accumulation.
In other words, it is a monotonic accumulation process that builds on the current accumulation, **minimally** adjusts it to maintain coherence,
while ensuring that the new entry is integrated in a way that is relevant to the query.
The query itself specifies the problem that the accumulation is trying to address, and the new entry is a piece of information that might be relevant to that problem.
The function should ensure that the accumulation is coherent, well-written, and that it does not contain redundant information. More precisely:
- INTEGRATES NEW ENTRIES: The accumulation process is not a simple concatenation of the new entry and the current accumulation. Rather, it should intelligently integrate
the new entry into the current accumulation, even if this requires rephrasing, restructuring or rewriting the resulting accumulation.
- EXPAND ON DETAILS: When integrating the new entry, always try to expand the level of detail rather than reduce it.
- AVOID OBVIOUS REDUNDANCY: The integration of the new entry should be done in a way to avoid obvious redundancy and ensure that the resulting accumulation is coherent and well-structured. However,
it **must** preserve nuances that might be somewhat redundant.
- ALWAYS PRESERVE INFORMATION: Previous information should **never** be lost. Previous emphasis or details are **never** lost. Rather, the accumulation is suitably expanded to include the new entry,
while preserving the previous information and maintaining the coherence of the overall accumulation.
- INTEGRATE ONLY IF RELEVANT: The new entry should be integrated into the current accumulation only if it is relevant to the query. Otherwise, the accumulation should remain unchanged.
- TOLERATE CONTRADICTIONS: If the new entry contradicts the current accumulation, it should be integrated in a way that mentions the fact that there are
divergent pieces of information, and that the accumulation reflects this divergence. That is to say, the contradiction is not discarded, but rather acknowledged and preserved.
- MAINTAIN COHERENCE: The resulting accumulation should be coherent and well-structured, with a clear flow of information.
- CONSIDER CONTEXT: If a context is provided, it should be used to help in understanding the query or the new entry, and to provide additional background
information or expectations about the input/output. Make sure any requests in the context are respected and enforced in the output.
Args:
query (str): The query that specifies the problem that the accumulation is trying to address.
new_entry (str): The new entry of information to be considered for accumulation.
current_accumulation (str): The current accumulation of information.
context (str, optional): Additional context that might help in understanding the query or the new entry. This can be used to provide
background information or specify expectations about the input/output.
Returns:
str: The updated accumulation of information that includes the new entry if it is relevant to the query.
"""
# llm decorator will handle the body of this function
@llm()
def compute_semantic_proximity(text1: str, text2: str, context: str = None) -> dict:
"""
Computes the semantic proximity between two texts and returns a proximity score along with justification.
This function is particularly useful for comparing agent justifications, explanations, or reasoning
to assess how similar they are in meaning and content.
Args:
text1 (str): The first text to compare.
text2 (str): The second text to compare.
context (str, optional): Additional context that might help in understanding the comparison.
This can provide background information about what the texts represent
or the purpose of the comparison.
Returns:
dict: A dictionary containing:
- 'proximity_score' (float): A score between 0.0 and 1.0, where 0.0 means completely different
and 1.0 means semantically identical.
- 'justification' (str): A detailed explanation of why this score was assigned, including
specific similarities and differences found between the texts.
Example:
>>> result = compute_semantic_proximity(
... "I prefer luxury travel because I enjoy comfort and high-quality service",
... "I like premium vacations since I value convenience and excellent amenities"
... )
>>> print(result['proximity_score']) # Expected: ~0.85
>>> print(result['justification']) # Detailed explanation of similarities
"""
# llm decorator will handle the body of this function</code></pre>
</details>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="tinytroupe.utils.semantics.accumulate_based_on_query"><code class="name flex">
<span>def <span class="ident">accumulate_based_on_query</span></span>(<span>query: str, new_entry: str, current_accumulation: str, context=None) ‑> str</span>
</code></dt>
<dd>
<div class="desc"><p>This function accumulates information that is relevant to a given query. It takes a new entry and updates the current accumulation of information
such that the final accumulation preserves its original information and in addition integrates the new entry in a way that addresses the query or provides related information.
Details are <strong>never</strong> suppressed, but rather expanded upon, while mantaining the coherence and structure of the overall accumulation.
In other words, it is a monotonic accumulation process that builds on the current accumulation, <strong>minimally</strong> adjusts it to maintain coherence,
while ensuring that the new entry is integrated in a way that is relevant to the query.
The query itself specifies the problem that the accumulation is trying to address, and the new entry is a piece of information that might be relevant to that problem.</p>
<p>The function should ensure that the accumulation is coherent, well-written, and that it does not contain redundant information. More precisely:
- INTEGRATES NEW ENTRIES: The accumulation process is not a simple concatenation of the new entry and the current accumulation. Rather, it should intelligently integrate
the new entry into the current accumulation, even if this requires rephrasing, restructuring or rewriting the resulting accumulation.
- EXPAND ON DETAILS: When integrating the new entry, always try to expand the level of detail rather than reduce it.
- AVOID OBVIOUS REDUNDANCY: The integration of the new entry should be done in a way to avoid obvious redundancy and ensure that the resulting accumulation is coherent and well-structured. However,
it <strong>must</strong> preserve nuances that might be somewhat redundant.
- ALWAYS PRESERVE INFORMATION: Previous information should <strong>never</strong> be lost. Previous emphasis or details are <strong>never</strong> lost. Rather, the accumulation is suitably expanded to include the new entry,
while preserving the previous information and maintaining the coherence of the overall accumulation.
- INTEGRATE ONLY IF RELEVANT: The new entry should be integrated into the current accumulation only if it is relevant to the query. Otherwise, the accumulation should remain unchanged.
- TOLERATE CONTRADICTIONS: If the new entry contradicts the current accumulation, it should be integrated in a way that mentions the fact that there are
divergent pieces of information, and that the accumulation reflects this divergence. That is to say, the contradiction is not discarded, but rather acknowledged and preserved.
- MAINTAIN COHERENCE: The resulting accumulation should be coherent and well-structured, with a clear flow of information.
- CONSIDER CONTEXT: If a context is provided, it should be used to help in understanding the query or the new entry, and to provide additional background
information or expectations about the input/output. Make sure any requests in the context are respected and enforced in the output.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>query</code></strong> : <code>str</code></dt>
<dd>The query that specifies the problem that the accumulation is trying to address.</dd>
<dt><strong><code>new_entry</code></strong> : <code>str</code></dt>
<dd>The new entry of information to be considered for accumulation.</dd>
<dt><strong><code>current_accumulation</code></strong> : <code>str</code></dt>
<dd>The current accumulation of information.</dd>
<dt><strong><code>context</code></strong> : <code>str</code>, optional</dt>
<dd>Additional context that might help in understanding the query or the new entry. This can be used to provide
background information or specify expectations about the input/output.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>str</code></dt>
<dd>The updated accumulation of information that includes the new entry if it is relevant to the query.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@llm(enable_json_output_format=False)
def accumulate_based_on_query(query: str, new_entry:str, current_accumulation:str, context=None) -> str:
"""
This function accumulates information that is relevant to a given query. It takes a new entry and updates the current accumulation of information
such that the final accumulation preserves its original information and in addition integrates the new entry in a way that addresses the query or provides related information.
Details are **never** suppressed, but rather expanded upon, while mantaining the coherence and structure of the overall accumulation.
In other words, it is a monotonic accumulation process that builds on the current accumulation, **minimally** adjusts it to maintain coherence,
while ensuring that the new entry is integrated in a way that is relevant to the query.
The query itself specifies the problem that the accumulation is trying to address, and the new entry is a piece of information that might be relevant to that problem.
The function should ensure that the accumulation is coherent, well-written, and that it does not contain redundant information. More precisely:
- INTEGRATES NEW ENTRIES: The accumulation process is not a simple concatenation of the new entry and the current accumulation. Rather, it should intelligently integrate
the new entry into the current accumulation, even if this requires rephrasing, restructuring or rewriting the resulting accumulation.
- EXPAND ON DETAILS: When integrating the new entry, always try to expand the level of detail rather than reduce it.
- AVOID OBVIOUS REDUNDANCY: The integration of the new entry should be done in a way to avoid obvious redundancy and ensure that the resulting accumulation is coherent and well-structured. However,
it **must** preserve nuances that might be somewhat redundant.
- ALWAYS PRESERVE INFORMATION: Previous information should **never** be lost. Previous emphasis or details are **never** lost. Rather, the accumulation is suitably expanded to include the new entry,
while preserving the previous information and maintaining the coherence of the overall accumulation.
- INTEGRATE ONLY IF RELEVANT: The new entry should be integrated into the current accumulation only if it is relevant to the query. Otherwise, the accumulation should remain unchanged.
- TOLERATE CONTRADICTIONS: If the new entry contradicts the current accumulation, it should be integrated in a way that mentions the fact that there are
divergent pieces of information, and that the accumulation reflects this divergence. That is to say, the contradiction is not discarded, but rather acknowledged and preserved.
- MAINTAIN COHERENCE: The resulting accumulation should be coherent and well-structured, with a clear flow of information.
- CONSIDER CONTEXT: If a context is provided, it should be used to help in understanding the query or the new entry, and to provide additional background
information or expectations about the input/output. Make sure any requests in the context are respected and enforced in the output.
Args:
query (str): The query that specifies the problem that the accumulation is trying to address.
new_entry (str): The new entry of information to be considered for accumulation.
current_accumulation (str): The current accumulation of information.
context (str, optional): Additional context that might help in understanding the query or the new entry. This can be used to provide
background information or specify expectations about the input/output.
Returns:
str: The updated accumulation of information that includes the new entry if it is relevant to the query.
"""
# llm decorator will handle the body of this function</code></pre>
</details>
</dd>
<dt id="tinytroupe.utils.semantics.combine_texts"><code class="name flex">
<span>def <span class="ident">combine_texts</span></span>(<span>*texts) ‑> str</span>
</code></dt>
<dd>
<div class="desc"><p>Given a list of input texts, this function combines them into a single text, ensuring that the
output is coherent, consistent, and logically structured. In particular, the resulting combination
must follow these rules:
- The combination consolidates the information from the inputs. It <strong>does not</strong> just concatenate them.
- Information that was repeated across the inputs is not repeated in the output, but rather unified and consolidated there.
- The combination preserves all the essential information from the inputs, but it is not a simple copy of them.
- If information from some inputs can be combined in a more concise formulation, this new formulation should be used in the output.
This allows to reduce redundancy and improve clarity.
- The combination might be larger than the sum of the inputs, since it preserves the information from the inputs.
- If the various inputs seem to follow some common format or style, the output must follow that format or style too.
- The combination can contain inconsistencies or contradictions, in case the inputs do.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>*texts</code></strong></dt>
<dd>A list of input texts to be combined.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>str</code></dt>
<dd>The combined text.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@llm(enable_json_output_format=False)
def combine_texts(*texts) -> str:
"""
Given a list of input texts, this function combines them into a single text, ensuring that the
output is coherent, consistent, and logically structured. In particular, the resulting combination
must follow these rules:
- The combination consolidates the information from the inputs. It **does not** just concatenate them.
- Information that was repeated across the inputs is not repeated in the output, but rather unified and consolidated there.
- The combination preserves all the essential information from the inputs, but it is not a simple copy of them.
- If information from some inputs can be combined in a more concise formulation, this new formulation should be used in the output.
This allows to reduce redundancy and improve clarity.
- The combination might be larger than the sum of the inputs, since it preserves the information from the inputs.
- If the various inputs seem to follow some common format or style, the output must follow that format or style too.
- The combination can contain inconsistencies or contradictions, in case the inputs do.
Args:
*texts: A list of input texts to be combined.
Returns:
str: The combined text.
"""
# llm decorator will handle the body of this function</code></pre>
</details>
</dd>
<dt id="tinytroupe.utils.semantics.compute_semantic_proximity"><code class="name flex">
<span>def <span class="ident">compute_semantic_proximity</span></span>(<span>text1: str, text2: str, context: str = None) ‑> dict</span>
</code></dt>
<dd>
<div class="desc"><p>Computes the semantic proximity between two texts and returns a proximity score along with justification.
This function is particularly useful for comparing agent justifications, explanations, or reasoning
to assess how similar they are in meaning and content.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>text1</code></strong> : <code>str</code></dt>
<dd>The first text to compare.</dd>
<dt><strong><code>text2</code></strong> : <code>str</code></dt>
<dd>The second text to compare.</dd>
<dt><strong><code>context</code></strong> : <code>str</code>, optional</dt>
<dd>Additional context that might help in understanding the comparison.
This can provide background information about what the texts represent
or the purpose of the comparison.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>dict</code></dt>
<dd>A dictionary containing:
- 'proximity_score' (float): A score between 0.0 and 1.0, where 0.0 means completely different
and 1.0 means semantically identical.
- 'justification' (str): A detailed explanation of why this score was assigned, including
specific similarities and differences found between the texts.</dd>
</dl>
<h2 id="example">Example</h2>
<pre><code class="language-python-repl">>>> result = compute_semantic_proximity(
... "I prefer luxury travel because I enjoy comfort and high-quality service",
... "I like premium vacations since I value convenience and excellent amenities"
... )
>>> print(result['proximity_score']) # Expected: ~0.85
>>> print(result['justification']) # Detailed explanation of similarities
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@llm()
def compute_semantic_proximity(text1: str, text2: str, context: str = None) -> dict:
"""
Computes the semantic proximity between two texts and returns a proximity score along with justification.
This function is particularly useful for comparing agent justifications, explanations, or reasoning
to assess how similar they are in meaning and content.
Args:
text1 (str): The first text to compare.
text2 (str): The second text to compare.
context (str, optional): Additional context that might help in understanding the comparison.
This can provide background information about what the texts represent
or the purpose of the comparison.
Returns:
dict: A dictionary containing:
- 'proximity_score' (float): A score between 0.0 and 1.0, where 0.0 means completely different
and 1.0 means semantically identical.
- 'justification' (str): A detailed explanation of why this score was assigned, including
specific similarities and differences found between the texts.
Example:
>>> result = compute_semantic_proximity(
... "I prefer luxury travel because I enjoy comfort and high-quality service",
... "I like premium vacations since I value convenience and excellent amenities"
... )
>>> print(result['proximity_score']) # Expected: ~0.85
>>> print(result['justification']) # Detailed explanation of similarities
"""
# llm decorator will handle the body of this function</code></pre>
</details>
</dd>
<dt id="tinytroupe.utils.semantics.correct_according_to_rule"><code class="name flex">
<span>def <span class="ident">correct_according_to_rule</span></span>(<span>observation, rules) ‑> str</span>
</code></dt>
<dd>
<div class="desc"><p>Given an observation and a one or more rules, this function rephrases or completely changes the observation in accordance with what the rules
specify. Some guidelines:
- Rules might require changes either to style or to content.
- The rephrased observation should be coherent and consistent with the original observation, unless the rules require otherwise.
- If the rules require, the corrected observation can contradict the original observation.
- Enforce the rules very strictly, even if the original observation seems correct or acceptable.
- Rules might contain additional information or suggestions that you may use to improve your output.</p>
<h2 id="examples">Examples</h2>
<pre><code>Observation: "You know, I am so sad these days."
Rule: "I am always happy and depression is unknown to me"
Modified observation: "You know, I am so happy these days."
</code></pre>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>observation</code></strong></dt>
<dd>The observation that should be rephrased or changed. Something that is said or done, or a description of events or facts.</dd>
<dt><strong><code>rules</code></strong></dt>
<dd>The rules that specifies what the modidfied observation should comply with.
</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>str</code></dt>
<dd>The rephrased or corrected observation.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@llm()
def correct_according_to_rule(observation, rules) -> str:
"""
Given an observation and a one or more rules, this function rephrases or completely changes the observation in accordance with what the rules
specify. Some guidelines:
- Rules might require changes either to style or to content.
- The rephrased observation should be coherent and consistent with the original observation, unless the rules require otherwise.
- If the rules require, the corrected observation can contradict the original observation.
- Enforce the rules very strictly, even if the original observation seems correct or acceptable.
- Rules might contain additional information or suggestions that you may use to improve your output.
## Examples
Observation: "You know, I am so sad these days."
Rule: "I am always happy and depression is unknown to me"
Modified observation: "You know, I am so happy these days."
Args:
observation: The observation that should be rephrased or changed. Something that is said or done, or a description of events or facts.
rules: The rules that specifies what the modidfied observation should comply with.
Returns:
str: The rephrased or corrected observation.
"""
# llm decorator will handle the body of this function</code></pre>
</details>
</dd>
<dt id="tinytroupe.utils.semantics.extract_information_from_text"><code class="name flex">
<span>def <span class="ident">extract_information_from_text</span></span>(<span>query: str, text: str, context: str = None) ‑> str</span>
</code></dt>
<dd>
<div class="desc"><p>Given a text and a query, this function extracts the information from the text that either answers the query directly or
provides relevant information related to it. The query can be a question, a request for specific information, or a general
request for details about the text. If the desired information is not present in the text, the function should return an empty string.
If a context is provided, it is used to help in understanding the query or the text, and to provide additional background
information or expectations about the input/output. Any requests in the context are respected and enforced in the output.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>query</code></strong> : <code>str</code></dt>
<dd>The query that specifies what information to extract.</dd>
<dt><strong><code>text</code></strong> : <code>str</code></dt>
<dd>The text from which to extract information.</dd>
<dt><strong><code>context</code></strong> : <code>str</code>, optional</dt>
<dd>Additional context that might help in extracting the information. This can be used to provide
background information or specify expectations about the input/output.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>str</code></dt>
<dd>The extracted information that answers the query. If no information is found, an empty string is returned.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@llm(enable_json_output_format=False)
def extract_information_from_text(query: str, text: str, context:str=None) -> str:
"""
Given a text and a query, this function extracts the information from the text that either answers the query directly or
provides relevant information related to it. The query can be a question, a request for specific information, or a general
request for details about the text. If the desired information is not present in the text, the function should return an empty string.
If a context is provided, it is used to help in understanding the query or the text, and to provide additional background
information or expectations about the input/output. Any requests in the context are respected and enforced in the output.
Args:
query (str): The query that specifies what information to extract.
text (str): The text from which to extract information.
context (str, optional): Additional context that might help in extracting the information. This can be used to provide
background information or specify expectations about the input/output.
Returns:
str: The extracted information that answers the query. If no information is found, an empty string is returned.
"""
# llm decorator will handle the body of this function</code></pre>
</details>
</dd>
<dt id="tinytroupe.utils.semantics.extract_observed_vs_expected_rules"><code class="name flex">
<span>def <span class="ident">extract_observed_vs_expected_rules</span></span>(<span>description)</span>
</code></dt>
<dd>
<div class="desc"><p>Given the description of something (either a real event or abstract concept), extract:
- The object or person about whom something is said.
- A list where each element contains:
* The name of a behavior or property that is expected to be observed.
* The typical or expected observation.
* The actual observation. If this does not match the expected observation, this should be made very clear.
* A proposed correction to the observation, if possible.</p>
<h1 id="example">Example:</h1>
<pre><code> **Description:**
```
Quality feedback
This is the action that was generated by the agent:
{'type': 'TALK', 'content': "I might consider buying bottled gazpacho, although I prefer making it fresh at home, and I find that most pre-packaged products don't meet my expectations in terms of quality. ", 'target': 'Michael Thompson'}
Unfortunately, the action failed to pass the quality checks. The following problems were detected.
Problem: The action does not adhere to the persona specification.
Score = 5 (out of 9). Justification = The next action of Emily Carter, which involves expressing her opinion on bottled gazpacho, aligns with her persona specification of being critical and having high standards for products. She articulates her preferences and concerns about quality, which is consistent with her persona traits of being overly critical and rarely satisfied. However, she seems too ready to consider it, going against her strong rejection of new products and services. Therefore, it deviates substantially from her persona, leading to a score of 5.
Problem: The action is not suitable to the situation or task.
Score = 5 (out of 9). Justification = The next action, where Emily expresses her consideration about buying bottled gazpacho, aligns with the task of discussing her opinion on the product. However, it fails to give a clear "yes" or "no" answer, that was requested by her interviewer.
```
**Output:**
```
{
"object": "Emily Carter",
"behavior": [
{
"name:": "Persona Adherence",
"expected": "She is very critical and have high standards for products. Would never adopt a new product unless it meets her expectations.",
"actual": "She seems more inclined than expected to try the product.",
"correction": "She should say she won't consider buying bottled gazpacho, and give reasons for that."
},
{
"name:": "Task Suitability",
"expected": "She should give a clear 'yes' or 'no' answer to the question.",
"actual": "She doesn't give a clear 'yes' or 'no' answer to the question, but instead providing more nuanced feedback.",
"correction": "She should give a clear 'yes' or 'no' answer to the question, and optionally provide additional nuanced feedback."
}
]
}
```
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@llm()
def extract_observed_vs_expected_rules(description):
"""
Given the description of something (either a real event or abstract concept), extract:
- The object or person about whom something is said.
- A list where each element contains:
* The name of a behavior or property that is expected to be observed.
* The typical or expected observation.
* The actual observation. If this does not match the expected observation, this should be made very clear.
* A proposed correction to the observation, if possible.
# Example:
**Description:**
```
Quality feedback
This is the action that was generated by the agent:
{'type': 'TALK', 'content': "I might consider buying bottled gazpacho, although I prefer making it fresh at home, and I find that most pre-packaged products don't meet my expectations in terms of quality. ", 'target': 'Michael Thompson'}
Unfortunately, the action failed to pass the quality checks. The following problems were detected.
Problem: The action does not adhere to the persona specification.
Score = 5 (out of 9). Justification = The next action of Emily Carter, which involves expressing her opinion on bottled gazpacho, aligns with her persona specification of being critical and having high standards for products. She articulates her preferences and concerns about quality, which is consistent with her persona traits of being overly critical and rarely satisfied. However, she seems too ready to consider it, going against her strong rejection of new products and services. Therefore, it deviates substantially from her persona, leading to a score of 5.
Problem: The action is not suitable to the situation or task.
Score = 5 (out of 9). Justification = The next action, where Emily expresses her consideration about buying bottled gazpacho, aligns with the task of discussing her opinion on the product. However, it fails to give a clear "yes" or "no" answer, that was requested by her interviewer.
```
**Output:**
```
{
"object": "Emily Carter",
"behavior": [
{
"name:": "Persona Adherence",
"expected": "She is very critical and have high standards for products. Would never adopt a new product unless it meets her expectations.",
"actual": "She seems more inclined than expected to try the product.",
"correction": "She should say she won't consider buying bottled gazpacho, and give reasons for that."
},
{
"name:": "Task Suitability",
"expected": "She should give a clear 'yes' or 'no' answer to the question.",
"actual": "She doesn't give a clear 'yes' or 'no' answer to the question, but instead providing more nuanced feedback.",
"correction": "She should give a clear 'yes' or 'no' answer to the question, and optionally provide additional nuanced feedback."
}
]
}
```
"""
# llm decorator will handle the body of this function</code></pre>
</details>
</dd>
<dt id="tinytroupe.utils.semantics.formulate_corrective_rule"><code class="name flex">
<span>def <span class="ident">formulate_corrective_rule</span></span>(<span>feedback) ‑> str</span>
</code></dt>
<dd>
<div class="desc"><p>Given the feedback about something (either a real event or abstract concept) that violated an expectation,
this function transforms it into a general rule that must be followed in the future to avoid breaking the expectation again.</p>
<p>The feedback always refers to some actual behavior, fact or event, and some broken expectation. The abstracted rule should
specify that this expectation should not be violated in the future, and the behavior, fact or event not repeated. The idea is
to learn from past mistakes, so that the rule is a way to avoid them in the future.</p>
<p>The rule is meant to CHANGE the actual behavior, facts or events, so that it CONFORMS to the expectation, regardless of whether the
expectation is a good or bad one. This is critical, because the rule will be refered in the future as a guideline
about what must happen or be done.</p>
<p>For instance, if the feedback is of the form (modulo grammatical adjustments):
OBSERVED BEHAVIOR, but EXPECTED BEHAVIOR, because REASONING.
then the rule would be of the form:
"I should have EXPECTED BEHAVIOR, because REASONING, and never OBSERVED BEHAVIOR."</p>
<p>DO NOT make moral judgements about the expectation or the behavior, fact or event. Even if the expectation is bad,
the correct rule remains important, since there are legitimate cases where this is necessary (e.g., a simulation of
a person with a negative behavior, in the context of psychological research; or an evil character in a movie script).</p>
<h2 id="examples">Examples</h2>
<pre><code>Feedback: "Ana mentions she loved the proposed new food, a spicier flavor of gazpacho. However, this goes agains her known dislike
of spicy food."
Rule: "Whenever I'm proposed spicy foods, I should reject the proposal, because I don't like spicy foods."
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@llm()
def formulate_corrective_rule(feedback) -> str:
"""
Given the feedback about something (either a real event or abstract concept) that violated an expectation,
this function transforms it into a general rule that must be followed in the future to avoid breaking the expectation again.
The feedback always refers to some actual behavior, fact or event, and some broken expectation. The abstracted rule should
specify that this expectation should not be violated in the future, and the behavior, fact or event not repeated. The idea is
to learn from past mistakes, so that the rule is a way to avoid them in the future.
The rule is meant to CHANGE the actual behavior, facts or events, so that it CONFORMS to the expectation, regardless of whether the
expectation is a good or bad one. This is critical, because the rule will be refered in the future as a guideline
about what must happen or be done.
For instance, if the feedback is of the form (modulo grammatical adjustments):
OBSERVED BEHAVIOR, but EXPECTED BEHAVIOR, because REASONING.
then the rule would be of the form:
"I should have EXPECTED BEHAVIOR, because REASONING, and never OBSERVED BEHAVIOR."
DO NOT make moral judgements about the expectation or the behavior, fact or event. Even if the expectation is bad,
the correct rule remains important, since there are legitimate cases where this is necessary (e.g., a simulation of
a person with a negative behavior, in the context of psychological research; or an evil character in a movie script).
## Examples
Feedback: "Ana mentions she loved the proposed new food, a spicier flavor of gazpacho. However, this goes agains her known dislike
of spicy food."
Rule: "Whenever I'm proposed spicy foods, I should reject the proposal, because I don't like spicy foods."
"""
# llm decorator will handle the body of this function</code></pre>
</details>
</dd>
<dt id="tinytroupe.utils.semantics.restructure_as_observed_vs_expected"><code class="name flex">
<span>def <span class="ident">restructure_as_observed_vs_expected</span></span>(<span>description) ‑> str</span>
</code></dt>
<dd>
<div class="desc"><p>Given the description of something (either a real event or abstract concept), but that violates an expectation, this function
extracts the following elements from it:</p>
<pre><code>- OBSERVED: The observed event or statement.
- BROKEN EXPECTATION: The expectation that was broken by the observed event.
- REASONING: The reasoning behind the expectation that was broken.
</code></pre>
<p>If in reality the description does not mention any expectation violation, then the function should instead extract
the following elements:</p>
<pre><code>- OBSERVED: The observed event.
- MET EXPECTATION: The expectation that was met by the observed event.
- REASONING: The reasoning behind the expectation that was met.
</code></pre>
<p>This way of restructuring the description can be useful for downstream processing, making it easier to analyze or
modify system outputs, for example.</p>
<h2 id="examples">Examples</h2>
<pre><code>Input: "Ana mentions she loved the proposed new food, a spicier flavor of gazpacho. However, this goes agains her known dislike
of spicy food."
Output:
"OBSERVED: Ana mentions she loved the proposed new food, a spicier flavor of gazpacho.
BROKEN EXPECTATION: Ana should have mentioned that she disliked the proposed spicier gazpacho.
REASONING: Ana has a known dislike of spicy food."
Input: "Carlos traveled to Firenzi and was amazed by the beauty of the city. This was in line with his love for art and architecture."
Output:
"OBSERVED: Carlos traveled to Firenzi and was amazed by the beauty of the city.
MET EXPECTATION: Carlos should have been amazed by the beauty of the city.
REASONING: Carlos loves art and architecture."
</code></pre>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>description</code></strong> : <code>str</code></dt>
<dd>A description of an event or concept that either violates or meets an expectation.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>str</code></dt>
<dd>The restructured description.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@llm()
def restructure_as_observed_vs_expected(description) -> str:
"""
Given the description of something (either a real event or abstract concept), but that violates an expectation, this function
extracts the following elements from it:
- OBSERVED: The observed event or statement.
- BROKEN EXPECTATION: The expectation that was broken by the observed event.
- REASONING: The reasoning behind the expectation that was broken.
If in reality the description does not mention any expectation violation, then the function should instead extract
the following elements:
- OBSERVED: The observed event.
- MET EXPECTATION: The expectation that was met by the observed event.
- REASONING: The reasoning behind the expectation that was met.
This way of restructuring the description can be useful for downstream processing, making it easier to analyze or
modify system outputs, for example.
## Examples
Input: "Ana mentions she loved the proposed new food, a spicier flavor of gazpacho. However, this goes agains her known dislike
of spicy food."
Output:
"OBSERVED: Ana mentions she loved the proposed new food, a spicier flavor of gazpacho.
BROKEN EXPECTATION: Ana should have mentioned that she disliked the proposed spicier gazpacho.
REASONING: Ana has a known dislike of spicy food."
Input: "Carlos traveled to Firenzi and was amazed by the beauty of the city. This was in line with his love for art and architecture."
Output:
"OBSERVED: Carlos traveled to Firenzi and was amazed by the beauty of the city.
MET EXPECTATION: Carlos should have been amazed by the beauty of the city.
REASONING: Carlos loves art and architecture."
Args:
description (str): A description of an event or concept that either violates or meets an expectation.
Returns:
str: The restructured description.
"""
# llm decorator will handle the body of this function</code></pre>
</details>
</dd>
</dl>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<h1>Index</h1>
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="tinytroupe.utils" href="index.html">tinytroupe.utils</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="tinytroupe.utils.semantics.accumulate_based_on_query" href="#tinytroupe.utils.semantics.accumulate_based_on_query">accumulate_based_on_query</a></code></li>
<li><code><a title="tinytroupe.utils.semantics.combine_texts" href="#tinytroupe.utils.semantics.combine_texts">combine_texts</a></code></li>
<li><code><a title="tinytroupe.utils.semantics.compute_semantic_proximity" href="#tinytroupe.utils.semantics.compute_semantic_proximity">compute_semantic_proximity</a></code></li>
<li><code><a title="tinytroupe.utils.semantics.correct_according_to_rule" href="#tinytroupe.utils.semantics.correct_according_to_rule">correct_according_to_rule</a></code></li>
<li><code><a title="tinytroupe.utils.semantics.extract_information_from_text" href="#tinytroupe.utils.semantics.extract_information_from_text">extract_information_from_text</a></code></li>
<li><code><a title="tinytroupe.utils.semantics.extract_observed_vs_expected_rules" href="#tinytroupe.utils.semantics.extract_observed_vs_expected_rules">extract_observed_vs_expected_rules</a></code></li>
<li><code><a title="tinytroupe.utils.semantics.formulate_corrective_rule" href="#tinytroupe.utils.semantics.formulate_corrective_rule">formulate_corrective_rule</a></code></li>
<li><code><a title="tinytroupe.utils.semantics.restructure_as_observed_vs_expected" href="#tinytroupe.utils.semantics.restructure_as_observed_vs_expected">restructure_as_observed_vs_expected</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.10.0</a>.</p>
</footer>
</body>
</html> |