Build Your Own AI Chatbot for Free with a Deepseek API
Do you want to leverage the power of AI in your own applications without incurring costs? This article will guide you through creating your own apps with a free AI integration.
Understanding APIs
An API, or Application Programming Interface, is a crucial component that allows different software applications to communicate with each other. It enables developers to access specific features or data from a service without needing to understand its complex internal operations. For instance, if you want to use ChatGPT-like features in your application, you would use an API from OpenAI. Typically, service providers sell subscriptions to their APIs, and costs can vary based on usage.
The exciting news is that there's a way to get an API from an AI provider that will not cost anything. You can use AI for free in your own applications. Imagine if you are a WordPress or React.js developer; you can integrate AI into your own website or your clients' websites without paying for API usage. All you have to do is get a free API key from a provider. In our case, we'll use Deepseek.
How to Obtain a Free API Key
To get a free API key, we will use OpenRouter.
- Navigate to the OpenRouter website and sign in with a free account.
- Agree to the terms of service. You will need an account to generate a free API key.
- This platform provides API keys for numerous LLMs. From the top search bar, look for a model such as "Deepseek."
- You will see several Deepseek AI options, including
deepseek-coder-v2
anddeepseek-chat
. You can use these models for free. - Select your preferred model. From the model's page, click API.
- By clicking the Create Key button, you can generate an API key for free. Give your key a memorable name.
- The platform provides code patterns for implementation in Python and TypeScript, which will also work for JavaScript.
On the keys page, you can manage your keys by editing or deleting them later and also view the activity for each API key.
Building a Simple AI Chatbot
With the API key in hand, we can now build a simple chatbot application.
For this project, we'll use a basic HTML page styled with Bootstrap. To convert the AI's markdown response into readable HTML, we'll include the marked
library from a CDN.
Here is some basic CSS to improve the appearance of the response container:
#response {
border: 1px solid #ccc;
padding: 15px;
margin-top: 20px;
min-height: 100px;
white-space: pre-wrap;
background-color: #f9f9f9;
}
The HTML Structure
The HTML consists of a container, a heading, an input field, a button that triggers a sendMessage
function, and a div
to display the response.
<div class="container mt-5">
<h1>Free AI Chatbot</h1>
<div class="input-group mb-3">
<input type="text" id="userInput" class="form-control" placeholder="Ask something...">
<button class="btn btn-primary" onclick="sendMessage()">Ask</button>
</div>
<div id="response"></div>
</div>
The Core JavaScript Functionality
The sendMessage
function is triggered when the user clicks the button. This asynchronous function will handle getting the user's input, sending it to the AI, and displaying the response.
async function sendMessage() {
const userInput = document.getElementById('userInput');
const responseDiv = document.getElementById('response');
const input = userInput.value.trim();
if (input === '') {
responseDiv.innerHTML = 'Please enter a question.';
return;
}
responseDiv.innerHTML = 'Loading...';
try {
const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer YOUR_API_KEY`, // Replace with your key
"Content-Type": "application/json"
},
body: JSON.stringify({
"model": "deepseek/deepseek-chat", // Or your chosen model
"messages": [
{ "role": "user", "content": input }
]
})
});
const data = await response.json();
// Safely access the response content
const messageContent = data.choices?.[0]?.message?.content;
if (messageContent) {
// Convert markdown to HTML using the marked library
responseDiv.innerHTML = marked.parse(messageContent);
} else {
responseDiv.innerHTML = 'No response received.';
}
} catch (error) {
console.error('Error:', error);
responseDiv.innerHTML = 'An error occurred while fetching the response.';
}
}
Note: In the fetch
call, you must replace YOUR_API_KEY
with the actual key you generated from OpenRouter. The optional chaining operator (?.
) is used to safely access deeply nested properties of an object, preventing errors if any part of the chain is null
or undefined
.
Testing the Application
Let's test the chatbot with a couple of questions.
Question 1:
capital of USA
Response:
The capital of the United States of America is Washington, D.C. (formerly known as the District of Columbia).
Question 2:
how to write hello world in JavaScript
Response:
You can write "Hello, World!" in JavaScript in several ways. Here are a few common methods:
1. Using
console.log()
This is the most common method for debugging and outputting information to the web console.
javascript console.log("Hello, World!");
2. Using
alert()
This displays a simple popup dialog box in the browser.
javascript alert("Hello, World!");
3. Using
document.write()
This method writes directly into the HTML document.
html <!DOCTYPE html> <html> <body> <script> document.write("Hello, World!"); </script> </body> </html>
Things to Note: -
console.log()
is generally preferred for development. -alert()
can be intrusive to the user experience. -document.write()
should be used with caution as it can overwrite the entire document if used after the page has loaded.
As you can see, we have successfully created a functional chatbot using a free AI API, capable of providing detailed and well-formatted answers.
Join the 10xdev Community
Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.