Loading...
Loading...
Auto-sort, categorize, or label content using AI. Use when sorting tickets into categories, auto-tagging content, labeling emails, detecting sentiment, routing messages to the right team, triaging support requests, building a spam filter, intent detection, topic classification, or any task where text goes in and a category comes out.
npx skill4agent add lebsral/dspy-programming-not-prompting-lms-skills ai-sortingimport dspy
from typing import Literal
# Your categories
CATEGORIES = ["billing", "technical", "account", "feature_request", "general"]
class SortContent(dspy.Signature):
"""Sort the message into the correct category."""
message: str = dspy.InputField(desc="The content to sort")
category: Literal[tuple(CATEGORIES)] = dspy.OutputField(desc="The assigned category")
sorter = dspy.ChainOfThought(SortContent)LiteralChainOfThoughtPredictclass TagContent(dspy.Signature):
"""Assign all applicable tags to the content."""
message: str = dspy.InputField(desc="The content to tag")
tags: list[Literal[tuple(CATEGORIES)]] = dspy.OutputField(desc="All applicable tags")
tagger = dspy.ChainOfThought(TagContent)from dspy.evaluate import Evaluate
def sorting_metric(example, prediction, trace=None):
return prediction.category == example.category
evaluator = Evaluate(
devset=devset,
metric=sorting_metric,
num_threads=4,
display_progress=True,
display_table=5,
)
score = evaluator(sorter)BootstrapFewShotoptimizer = dspy.BootstrapFewShot(
metric=sorting_metric,
max_bootstrapped_demos=4,
)
optimized_sorter = optimizer.compile(sorter, trainset=trainset)MIPROv2optimizer = dspy.MIPROv2(
metric=sorting_metric,
auto="medium",
)
optimized_sorter = optimizer.compile(sorter, trainset=trainset)result = optimized_sorter(message="I was charged twice on my credit card last month")
print(f"Category: {result.category}")
print(f"Reasoning: {result.reasoning}")LiteralChainOfThoughtPredicthintclass SortWithHint(dspy.Signature):
message: str = dspy.InputField()
hint: str = dspy.InputField(desc="Optional hint for ambiguous cases")
category: Literal[tuple(CATEGORIES)] = dspy.OutputField()hint/ai-scoring/ai-improving-accuracy