Build a customizable LLM Chatbot in Unity
Tags: ai, api, opensource
Published: 2024-02-16 13:31:16

_In this tutorial, we will guide you through the process of integrating personalized AI chatbots into your Unity game using AskYoda by Eden AI. This integration will allow you to create engaging and responsive non-player characters (NPCs) with the help of Language Model (LLM) providers such as OpenAI, Cohere, Anthropic, Google Cloud, and AI21 Labs._

‍

## What is Unity?

![Unity Logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6js6mqm30lcxcjfc4mg2.png)

Founded in 2004, Unity is a leading gaming company offering a robust game development engine that empowers developers to create immersive games for various platforms. 

Unity's integration with artificial intelligence (AI) enables developers to incorporate intelligent behaviors, decision-making processes, and advanced functionalities into their games.

![AI Unity plugin](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r824a8z8o01cxvowx4sr.png)

Unity offers multiple pathways for integrating AI into applications. One notable option is the Unity Eden AI Plugin, which seamlessly interfaces with the Eden AI API, streamlining the integration of AI features, including customizable AI chatbot functionality, into Unity applications.

This integration simplifies the process of incorporating AI into Unity projects, enhancing interactivity, personalization, and immersion in gaming experiences

‍

## Custom Chatbots vs. Standard Chatbots
Standard chatbots typically rely on pre-existing datasets for training, which may not cover all potential user queries or scenarios. As a result, they may struggle to understand or provide accurate responses to certain types of inquiries.

Customizable chatbots offer a solution to these limitations by allowing organizations to tailor the chatbot's capabilities and responses according to their specific needs. 


![Cutomizable AI Chatbot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7axhonfct0pl984qmc3q.jpg)
‍

Organizations can provide their own datasets to train the chatbot, ensuring that it's equipped to handle the specific queries and scenarios relevant to their domain or industry. This enables the chatbot to better understand and respond to user inquiries within that context.

‍

## Benefits of using Custom Chatbots in Unity
Customizable AI chatbots, tailored to specific data in video games, elevate player experiences and equip developers with potent tools for crafting vibrant, personalized game worlds. Consider the following benefits:

‍

### 1. Enhanced Realism
In terms of Enhanced Realism, chatbots trained on specific data forge conversations that are not only more realistic but also contextually pertinent. NPCs, armed with this capability, delve into detailed aspects of the game world, immersing players more deeply.

‍

### 2. Personalized Player Interaction
Personalized Player Interaction reaches new heights as AI chatbots, attuned to individual player data, dynamically adapt responses according to unique player choices and preferences. NPCs can recall and reference past interactions, providing a personalized and tailored gaming experience for each player.

‍

### 3. Adaptive Storytelling
For Adaptive Storytelling, chatbots trained on specific narrative elements contribute to more engaging and dynamic storytelling. NPCs respond dynamically to in-game events, player decisions, and the overall progression of the storyline.

‍

### 4. Targeted Educational Content
In the realm of Targeted Educational Content, customizable chatbots trained on educational data deliver precision. In educational games, NPCs provide context-specific explanations, quizzes, and learning materials tailored to the player's current knowledge level.

‍

### 5. Cultural and Historical Accuracy
Cultural and Historical Accuracy is assured as chatbots, versed in specific cultural or historical data, engage in conversations reflecting the historical or cultural context. This adds authenticity to the gaming experience.

‍

### 6. Genre-Specific Interactions
For Genre-Specific Interactions, chatbots trained on genre-specific data craft dialogues and interactions that seamlessly fit the thematic consistency of the game. In a fantasy game, NPCs use genre-specific language, references, and terminology.

‍

## 7. Simulating Professions and Expertise
Chatbots excel at Simulating Professions and Expertise when trained on profession-specific data. NPCs with medical knowledge, for instance, provide accurate information in a healthcare-themed game, adding realism and depth.

‍

### 8. Dynamic Response to Real-World Events
For Dynamic Response to Real-World Events, chatbots trained on real-world data dynamically respond to external events. NPCs can incorporate real-world news or seasonal events into dialogues, keeping the game world relevant and up-to-date.

‍

### 9. Increased Player Retention
The Increased Player Retention stems from the personalized and dynamic nature of chatbot interactions. Players are more likely to continue playing a game where the story and interactions evolve based on their choices and preferences.

‍

In conclusion, customizable AI chatbots trained on specific data empower game developers to fashion more authentic, adaptive, and engaging gaming experiences, ultimately leading to a more satisfying and immersive journey for players.

‍

## How to Integrate Customizable AI Chatbot into Your Unity Game
Step 1. Install the Eden AI Unity Plugin

### ‍Step 1. Install the [Eden AI Unity Plugin](https://github.com/edenai/unity-plugin?referral=how-to-integrate-custom-chatbot-in-unity)

![Unity Plugin on Eden AI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8u6d988o2ncbnwsoz7ll.png)

Ensure that you have a Unity project open and ready for integration. If you haven't installed the Eden AI plugin, follow these steps:

1. Open your Unity Package Manager

2. [Add package](https://github.com/edenai/unity-plugin.git?referral=how-to-integrate-custom-chatbot-in-unity) from GitHub
‍

### Step 2. Obtain your Eden AI API Key
To get started with the Eden AI API, you need to [sign up for an account on the Eden AI platform](https://app.edenai.run/user/register?referral=how-to-integrate-custom-chatbot-in-unity) (receive free credits upon registration!).

[‍Try Eden AI for FREE](https://app.edenai.run/user/register?referral=how-to-integrate-custom-chatbot-in-unity)


Once registered, you will get an API key which you will need to use the Eden AI Unity Plugin. You can set it in your script or add a file auth.json to your user folder (path: _~/.edenai_ (Linux/Mac) or _%USERPROFILE%/.edenai/_ (Windows)) as follows:


```
{  "api_key": "YOUR_EDENAI_API_KEY"}
```
‍

Alternatively, you can pass the API key as a parameter when creating an instance of the _EdenAIApi_ class. If the API key is not provided, it will attempt to read it from the auth.json file in your user folder.

‍

### Step 3: Create your AskYoda Project on Eden AI
[Go to AskYoda](https://app.edenai.run/bricks/edenai-products/askyoda/default?referral=how-to-integrate-custom-chatbot-in-unity) on the Eden AI platform. Here is the [link](https://github.com/edenai/unity-plugin?tab=readme-ov-file#ask-your-data?referral=how-to-integrate-custom-chatbot-in-unity) to the GitHub repository.

Initiate your AskYoda project, obtaining the unique project ID.


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

### Step 4. Integrate Custom AI Chatbot with [AskYoda](https://docs.edenai.co/docs/ask-yoda?referral=how-to-integrate-custom-chatbot-in-unity)
Revitalize your non-player characters (NPCs) by allowing them to articulate thoughts through the integration of customizable chatbot functionality with large language models (LLMs).

AksYoda by Eden AI is a chatbot builder allowing users to create customized AI assistants using their own data. It is powered by LLMs and is designed to be easily integrate an array of AI Chatbot APIs, such as OpenAI, Google, and Replicate, into your Unity project (please refer to our [documentation](https://github.com/edenai/edenai-apis/blob/master/AVAILABLES_FEATURES_AND_PROVIDERS.md?referral=how-to-integrate-custom-chatbot-in-unity)).

This capability empowers you to personalize the engine model and adjust the assistant's behavior, providing a versatile solution to tailor the desired ambiance of your game.

1. Open your script file where you want to implement AskYoda functionality.

2. Import the required namespaces at the beginning of your script:

```
using EdenAI;
using System;
using System.Threading.Tasks;
```
‍

3. Create an instance of the Eden AI API class by passing your API key as a parameter. If the API key is not provided, it will attempt to read it from the auth.json file in your user folder.

```
EdenAIApi edenAI = new EdenAIApi();
```
‍

4. Implement the SendYodaRequest function with the necessary parameters:

```
class Program
{
    static async Task Main(string[] args)
    {
        string projectID = "YOUR_YODA_PROJECT_ID";
        string query = "Which product is the most expensive?";

        EdenAIApi edenAI = new EdenAIApi();
        YodaResponse response = await edenAI.SendYodaRequest(projectID, query);
    }
}
```
‍

_Note: When using the chat functionality, it's important to note that the chatbot is designed to provide responses in the same language as the incoming message. For instance, if you send a message in French, the chatbot will respond in French. The language specification is handled automatically without the need for explicit instructions in the request._

‍

### Step 5: Handle the AskYoda Response
The SendYodaRequest function returns a YodaResponse object.

Access the response attribute result for the large language model (LLM) response:


```
if (!string.IsNullOrEmpty(response.result))
{
    // Use the LLM response as needed in your Unity project
}
else
{
    // Handle the case where the interaction with AskYoda fails
}
```
‍

### Step 6: Customize Parameters (Optional)
Adjust optional parameters based on your preferences:

- query (string) : The question or query about the data.
- history (List<Dictionary<string, string>>) (optional) : A list containing all the previous conversations between the user and the chatbot AI. Each dictionary item in the list should contain alternating "user" and "assistant" messages, with their associated roles and text. For example : new List<Dictionary<string, string>>{new Dictionary<string, string> { { "user", "Hi!" }, { "assistant", "Hi, how can I help you?" }}};.
- k (int) (optional) : The number of result chunk to return.
- llmModel (string) (optional) : The model to use for language processing.
- llmProvider (string) (optional) : The provider for the large language model (LLM) for processing. For a list of available providers, please refer to our documentation.
‍

### Step 6: Test and Debug
Run your Unity project and test the AskYoda functionality. Monitor the console for any potential errors or exceptions, making adjustments as necessary.

‍

## Conclusion
Now, your Unity project is equipped with AskYoda functionality, allowing you to personalize AI-powered NPCs using your data and large language models. Experiment with different queries and responses to create engaging and responsive in-game characters.

Feel free to refer back to this tutorial whenever you need to implement or refine AskYoda capabilities in your Unity projects. Now, go ahead and bring unique and personalized interactions to your AI-powered NPCs!

Feel free to explore additional [AI functionalities on Unity](https://github.com/edenai/unity-plugin?referral=how-to-integrate-custom-chatbot-in-unity) offered by Eden AI to further elevate your game development. 

‍

## About Eden AI
Eden AI is the future of AI usage in companies: our app allows you to call multiple AI APIs.

![Multiple AI engines in one API — Eden AI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gq9xj4tivouitgl6ij4k.gif)


- Centralized and fully monitored billing
- Unified API: quick switch between AI models and providers
- Standardized response format: the JSON output format is the same for all suppliers.
- The best Artificial Intelligence APIs in the market are available
- Data protection: Eden AI will not store or use any data.

[Create your Account on Eden AI](https://app.edenai.run/user/register?referral=how-to-integrate-custom-chatbot-in-unity)