Chat

In this tutorial we'll take what you've seen so far and use it to build your first chatbot.

A Basic Interaction Loop

Fundamentally, a chatbot is just a loop where the user sends a prompt, the prompt is submitted to the LLM, and receives the response. You've already seen the two pieces we'll use in that loop

  • yr.text_input lets you request text input from the user.
  • yr.response lets you send a prompt to the active LLM.

Let's start by importing Yera and creating a chatbot function. You'll want a loop with the input and response bits inside

import yera as yr

@yr.app
def chatbot():
    while True:
      prompt = yr.text_input()
      yr.response(prompt)

Try it out now.

Notice that there's no easy way to quit the program, it'll just keep looping unless you force it to quit. This clearly isn't a great user experience.

We don't want them stuck in there forever, so we should also add the ability to quit by typing /quit. Inside the loop, between the input and response we detect this, and trigger yr.quit and break out of the loop.

yr.quit is a new function for you and represents a normal exit of a Yera program such as a user quitting. It clears up the running process and other bits that are supporting your app behind the scenes.

Give it a try by running your program again, asking a few questions and then typing "/quit". You should see your chatbot exit gracefully.

Here's what you should have now.

import yera as yr

@yr.app
def chatbot():
    while True:
        prompt = yr.text_input()

        if prompt.startswith("/quit"):
            yr.quit()
            break

        yr.response(prompt)

The yr.chat Function

The code you just wrote is a pattern used repeatedly when building interactive agents: get input, check for user quit, do something with it. Yera has a handy function that implements it for you so you don't have to keep writing it yourself.

Using yr.chat you can build a chatbot in a few lines:

import yera as yr

@yr.app
def chatbot():
    for prompt in yr.chat():
        yr.response(prompt)

Try running this and doing the same stuff as before. You'll see it behaves the same way and exits gracefully when asked as well.

Summary

You now have your first working chatbot and know how to build interactive agent loops in Yera. In the next tutorial we'll look at yr.Struct, Yera's feature for extracting structured data from text. This is the first step towards building your first data pipeline.