Build a Custom ChatGPT-like Chatbot with Chainlit
Tags: ai, api, tutorial
Published: 2024-03-12 09:39:03

_This tutorial will guide you through building a custom chatbot using Chainlit and AskYoda, providing a powerful and customizable conversational AI tool for various applications 🙌_

‍ ‍

## Advantages of Eden AI and Chainlit for AI Chatbot Development
AskYoda and Chainlit offer significant advantages for those looking to create and customize AI chatbots.

Chainlit, an open-source Python framework, provides the capability to develop Conversation AI interfaces with ease, allowing for customization through various providers.

![Chainlit and Eden AI logos](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o3abgrlqzh0dm1dns5ar.png)

On the other hand, AskYoda, developed by Eden AI, empowers users to craft and train AI chatbots using their specific data.

AskYoda’s integration with providers such as [OpenAI](https://www.edenai.co/providers/openai?referral=askyoda-chainlit), [Cohere](https://www.edenai.co/providers/cohere?referral=askyoda-chainlit), and [Google Cloud](https://www.edenai.co/providers/google-cloud?referral=askyoda-chainlit) expands its functionality, addressing limitations by enabling seamless data integration and training in multiple programming languages.‍

## How to build a custom chatbot using ChainLit?‍

### Step 1. Prerequisites
💡 Make sure you have the following libraries installed: _chainlit, requests, json, dotenv, os_

```
import chainlit as cl 
import requests 
import json 
from dotenv 
import load_dotenv 
import os 
from typing import Optional 
from chainlit.types import ThreadDict 
from chainlit.input_widget import Select, Slider‍
```

### Step 2. Decorator and Chat Settings
Chainlit works with decorators for handling interactions, so you will need to use it for each of the interaction you want to handle. Here’s an example decorator, followed by the function that will be triggered when a new message is posted.

```
@cl.on_message #The decorator 
async def main(message: cl.Message): 
    await cl.Avatar( 
        name="AskYoda", 
        path = "public/logo_light.png" 
        ).send()‍
```

You can also customize chat settings using cl.ChatSettings in the triggered function:

```
cl.ChatSettings( 
        [ 
            Select( 
               id="llm_provider", 
               label="LLM Provider", 
               values=["cohere", "amazon", "anthropic", "ai21labs", "openai", "google"], 
               initial_index = 4 
               ), 
             Select( 
               id="llm_model", 
               label="LLM Model", 
               values= [ 
                  "command", 
                  "command-light" 
)])‍
```

### Step 3. Retrieve Chat Settings
You can retrieve the selected chat settings like this:

```
llm_model = cl.user_session.get("llm_model") 
llm_provider = cl.user_session.get("llm_provider")‍
```

### Step 4. Create a project in AskYoda
‍

**1. Create an Account**

To begin utilizing AskYoda, the first step is to [create a free account on Eden AI.](https://app.edenai.run/user/register?referral=askyoda-chainlit)

Once registered, you can obtain your API key 🔑 directly from the homepage. This key can then be used with the complimentary credits provided by Eden AI.

![Eden AI App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wzwvf025ehawt8gji8vb.jpg)

[G‍et your API key for FREE.](https://app.edenai.run/user/register?referral=askyoda-chainlit)

**2. Create a new project**

Once logged in, navigate to the [AskYoda feature](https://app.edenai.run/bricks/edenai-products/askyoda/default?referral=askyoda-chainlit). Start by creating a new project within AskYoda.

![Eden AI App - AskYoda](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nx8412uaxey86j4axwck.png)


**3. Upload Your Data‍**

Upload the data you want to train your chatbot on.

![Eden AI App - AskYoda](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zws62escfxzeczf96ewf.png)

**4. Chat with Your Data**

Once your project is set up, you can start chatting on the interface using your own data:‍

![Eden AI App - AskYoda](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y97n6xavty8omte36fex.png)

If you want to go further check our [article](https://www.edenai.co/post/askyoda-a-versatile-solution-for-customizable-ai-chatbots?referral=askyoda-chainlit) on our website

‍

### Step 5. Make API Calls to AskYoda
Before making API calls, ensure you have the bearer token and project ID ready:

```
headers = {"Authorization": f"Bearer {Api_Key}"} 
url = f"https://api.edenai.run/v2/aiproducts/askyoda/{project_id}/ask_llm"‍
```

Then, gather all the necessary information and make the API call to Eden AI:

```
json_payload = {"query" : f"{message.content}", 
            "llm_provider" : llm_provider, 
            "history" : history, 
            "llm_model" : llm_model, 
            #Customize the personnality of your assistant 
            "personnality" : {}, 
            "chunks" : chunks 
            } 
    response = requests.post(url, json=json_payload, headers=headers) 
    result = json.loads(response.text) 

    if 'result' in result: 
            a = str(result['result']) 
            history.append({"user": f"{message.content}", "assistant": f"{a}"}) 
            # Send a response back to the user 
            await cl.Message( 
                  content=f"{result['result']}", author = 'AskYoda' 

            ).send() 
    else: 
            await cl.Message( 
                content=f"Key 'result' not found in the response. : {result}", 
            ).send()‍
```

### Step 6. Run the Chat Interface
To run your custom ChatGPT interface with AskYoda using Chainlit, type:
**chainlit run app.py**

![Custom ChatGPT with AskYoda using Chainlit](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ufetaksudx63x9z8459c.gif)



Congratulations! 😎 You’ve created your own AskYoda chatbot interface using Chainlit!

You can now use it with the LLM of your choice from a diverse selection of providers on Eden AI, including [OpenAI](https://www.edenai.co/providers/openai?referral=askyoda-chainlit), [Google](https://www.edenai.co/providers/google-cloud?referral=askyoda-chainlit), [Cohere](https://www.edenai.co/providers/cohere?referral=askyoda-chainlit), [Anthropic](https://www.edenai.co/providers/anthropic?referral=askyoda-chainlit), [AI21 Labs](https://www.edenai.co/providers/ai21labs?referral=askyoda-chainlit), [Amazon](https://www.edenai.co/providers/amazon-web-services?referral=askyoda-chainlit), and many others!

![Custom ChatGPT with AskYoda using Chainlit](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w017lj4rxx3usaqttx4p.gif)

There are still opportunities for further improvements such as authentication, chat history management, and adding more features as needed.

Explore more possibilities with Chainlit and AskYoda for creating powerful AI conversational agents tailored to your needs.‍

## 7. Embed your chat on your app/product
The chat is deployable in Copilot. Learn more about Copilot deployment [here](https://docs.chainlit.io/deployment/copilot?referral=askyoda-chainlit).

The Copilot is tailored to assist users in maximizing their app experience by offering contextual guidance and performing actions on their behalf:

[Check it out!](https://assets-global.website-files.com/61e7d259b7746e3f63f0b6be/65def1d23d80c5913ad8a5e8_copilot.gif)






**_[Create your Account on Eden AI.](https://app.edenai.run/user/register?referral=askyoda-chainlit)_**