|
| 1 | +from typing import Literal |
| 2 | + |
| 3 | +from mellea import generative, start_session |
| 4 | +from mellea.stdlib.genslot import PreconditionException |
| 5 | +from mellea.stdlib.requirement import Requirement, simple_validate |
| 6 | +from mellea.stdlib.sampling.base import RejectionSamplingStrategy |
| 7 | + |
| 8 | + |
| 9 | +@generative |
| 10 | +def classify_sentiment(text: str) -> Literal["positive", "negative", "unknown"]: |
| 11 | + """Classify the sentiment of the text.""" |
| 12 | + ... |
| 13 | + |
| 14 | + |
| 15 | +if __name__ == "__main__": |
| 16 | + m = start_session() |
| 17 | + |
| 18 | + # Add preconditions and requirements. |
| 19 | + sentiment_component = classify_sentiment( |
| 20 | + m, |
| 21 | + text="I love this!", |
| 22 | + # Preconditions are only checked with basic validation. Don't use the strategy. |
| 23 | + precondition_requirements=["the text arg should be less than 100 words"], |
| 24 | + # Reqs to use with the strategy. You could also just remove "unknown" from the structured output for this. |
| 25 | + requirements=["avoid classifying the sentiment as unknown"], |
| 26 | + strategy=RejectionSamplingStrategy(), # Must specify a strategy for gen slots |
| 27 | + ) |
| 28 | + |
| 29 | + print( |
| 30 | + f"Prompt to the model looked like:\n```\n{m.last_prompt()[0]['content']}\n```" |
| 31 | + ) # type: ignore |
| 32 | + # Prompt to the model looked like: |
| 33 | + # ``` |
| 34 | + # Your task is to imitate the output of the following function for the given arguments. |
| 35 | + # Reply Nothing else but the output of the function. |
| 36 | + |
| 37 | + # Function: |
| 38 | + # def classify_sentiment(text: str) -> Literal['positive', 'negative', 'unknown']: |
| 39 | + # """Classify the sentiment of the text. |
| 40 | + |
| 41 | + # Postconditions: |
| 42 | + # - avoid classifying the sentiment as unknown |
| 43 | + # """ |
| 44 | + |
| 45 | + # Arguments: |
| 46 | + # - text: "I love this!" (type: <class 'str'>) |
| 47 | + # ``` |
| 48 | + |
| 49 | + print("\nOutput sentiment is:", sentiment_component) |
| 50 | + |
| 51 | + # We can also force a precondition failure. |
| 52 | + try: |
| 53 | + sentiment_component = classify_sentiment( |
| 54 | + m, |
| 55 | + text="I hate this!", |
| 56 | + # Requirement always fails to validate given the lambda. |
| 57 | + precondition_requirements=[ |
| 58 | + Requirement( |
| 59 | + "the text arg should be only one word", |
| 60 | + validation_fn=simple_validate(lambda x: (False, "Forced to fail!")), |
| 61 | + ) |
| 62 | + ], |
| 63 | + ) |
| 64 | + except PreconditionException as e: |
| 65 | + print(f"exception: {str(e)}") |
| 66 | + |
| 67 | + # Look at why the precondition validation failed. |
| 68 | + print("Failure reasons:") |
| 69 | + for val_result in e.validation: |
| 70 | + print("-", val_result.reason) |
0 commit comments