PyPI: https://pypi.org/project/langchoice
switch-case, but for free-form sentences. A one-liner for if-then-else over similar sentences.
The LangChoice library allows you to condition your structured programs over natural language sentence predicates or triggers. Makes it easy to define conditional flows over user inputs without implementing the sentence match operator over and over again.
pip install langchoice
Suppose we want to detect if an incoming user message triggered belongs to one of the following (greeting, politics) topics. Do this in a few lines using langchoice.
First define the text messages that define each topic category (a message group).
triggers =
'''
greeting:
- hello
- hi
- what's up?
politics:
- what are your political beliefs?
- thoughts on the president?
- left wing
- right wing
'''LangStore data container.data = yaml.safe_load(triggers)
S = LangStore(data)user_msg, simply match with topics!match S.match(user_msg, threshold=1.2, debug=True):
case 'greeting', _ : #user_msg matches the greeting message cluster
say_hello()
case 'politics', _ : #user_msg matches the politics message cluster
change_topic()
case x :
print(x)
print(f'No defined triggers detected. Ask an LLM for response.')Add or remove sentences from each topic or introduce new topics. Works on-the-fly!
Supports multiple matching modes:
S.match returns the topic of nearest message.S.match_centroid to instead find the nearest topic centroid .S.match returns None if the nearest topic distance is greater than the threshold.debug=True and debug_k=5 to
user_msg to different topics.Coming Soon!
The langchoice package enables you to make controlled chatbot flows as well as build guardrails very quickly.
The key motivation is to allow users to have maximal control when designing the bot:
Check out the sales lead filtering and appointment-booking bots under examples.
Nishant Sinha, Founder, Consulting Scientist, OffNote Labs.
For insights on Generative AI evolution and applications, follow on Linkedin, and read our articles on Substack.