Integrating with Web Applications

This guide explains how to integrate Addis AI into your web applications, focusing on common frontend frameworks and standard JavaScript.

Getting Started

Before integrating Addis AI into your web application, you'll need:
  1. An API key from Addis AI
  2. Basic understanding of modern JavaScript and HTTP requests
  3. A framework-specific implementation (or vanilla JavaScript)

Key Integration Points

When integrating Addis AI into web applications, consider these key points:
  1. Authentication: Securely managing your API key
  2. Request Handling: Making HTTP requests to the Addis AI API
  3. Response Processing: Handling and displaying the responses
  4. Conversation Management: Maintaining conversation history
  5. Error Handling: Gracefully handling API errors
  6. User Experience: Creating a responsive interface

JavaScript Fetch Implementation

Here's a basic implementation using vanilla JavaScript:
// Basic Addis AI API client
class AddisAIClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = "https://api.addisassistant.com/api/v1";
this.conversationHistory = [];
}
// Send a message to the chat API
async sendMessage(message, targetLanguage = "am") {
try {
const response = await fetch(`${this.baseUrl}/chat_generate`, {
method: "POST",
headers: {
"X-API-Key": this.apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({
prompt: message,
target_language: targetLanguage,
conversation_history: this.conversationHistory,
generation_config: {
temperature: 0.7,
},
}),
});
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
// Update conversation history
this.conversationHistory.push(
{ role: "user", content: message },
{ role: "assistant", content: data.response_text },
);
return data;
} catch (error) {
console.error("Error sending message:", error);
throw error;
}
}
// Clear conversation history
clearConversation() {
this.conversationHistory = [];
}
// Text-to-speech conversion
async textToSpeech(text, language = "am") {
try {
const response = await fetch(`${this.baseUrl}/audio`, {
method: "POST",
headers: {
"X-API-Key": this.apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({
text,
language,
}),
});
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
return data.audio; // Base64-encoded audio
} catch (error) {
console.error("Error generating audio:", error);
throw error;
}
}
}
// Usage example
document.addEventListener("DOMContentLoaded", () => {
const client = new AddisAIClient("YOUR_API_KEY");
const messageInput = document.getElementById("message-input");
const sendButton = document.getElementById("send-button");
const chatContainer = document.getElementById("chat-container");
sendButton.addEventListener("click", async () => {
const message = messageInput.value.trim();
if (!message) return;
// Display user message
appendMessage("user", message);
messageInput.value = "";
try {
// Send to API and get response
const response = await client.sendMessage(message);
// Display AI response
appendMessage("assistant", response.response_text);
} catch (error) {
appendMessage("system", "Error: Could not get response");
}
});
function appendMessage(role, content) {
const messageElement = document.createElement("div");
messageElement.className = `message ${role}`;
messageElement.textContent = content;
chatContainer.appendChild(messageElement);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
});
javascript

React Implementation

Here's how to integrate Addis AI with a React application:
import React, { useState, useEffect, useRef } from "react";
import "./ChatApp.css";
const AddisAIChat = ({ apiKey }) => {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [conversationHistory, setConversationHistory] = useState([]);
const messagesEndRef = useRef(null);
// Scroll to bottom of messages
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
useEffect(() => {
scrollToBottom();
}, [messages]);
const sendMessage = async () => {
if (!input.trim()) return;
// Add user message to UI
const userMessage = { role: "user", content: input };
setMessages((prev) => [...prev, userMessage]);
setInput("");
setIsLoading(true);
try {
// Call Addis AI API
const response = await fetch(
"https://api.addisassistant.com/api/v1/chat_generate",
{
method: "POST",
headers: {
"X-API-Key": apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({
prompt: input,
target_language: "am",
conversation_history: conversationHistory,
generation_config: { temperature: 0.7 },
}),
},
);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
// Add assistant response to UI
const assistantMessage = {
role: "assistant",
content: data.response_text,
};
setMessages((prev) => [...prev, assistantMessage]);
// Update conversation history for next request
setConversationHistory((prev) => [
...prev,
userMessage,
assistantMessage,
]);
} catch (error) {
console.error("Error:", error);
setMessages((prev) => [
...prev,
{
role: "system",
content: "Sorry, there was an error processing your request.",
},
]);
} finally {
setIsLoading(false);
}
};
return (
<div className="chat-container">
<div className="chat-messages">
{messages.map((message, index) => (
<div key={index} className={`message ${message.role}`}>
<div className="message-content">{message.content}</div>
</div>
))}
{isLoading && (
<div className="message assistant loading">
<div className="typing-indicator">
<span></span>
<span></span>
<span></span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
<div className="chat-input">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === "Enter" && sendMessage()}
placeholder="Type a message..."
disabled={isLoading}
/>
<button onClick={sendMessage} disabled={isLoading}>
Send
</button>
</div>
</div>
);
};
export default AddisAIChat;
jsx

Vue Implementation

Here's how to implement Addis AI chat in a Vue.js application:
<template>
<div class="chat-container">
<div class="chat-messages" ref="messagesContainer">
<div
v-for="(message, index) in messages"
:key="index"
:class="['message', message.role]"
>
{{ message.content }}
</div>
<div v-if="isLoading" class="message assistant loading">
<div class="typing-indicator">
<span></span><span></span><span></span>
</div>
</div>
</div>
<div class="chat-input">
<input
type="text"
v-model="inputMessage"
@keyup.enter="sendMessage"
placeholder="Type a message..."
:disabled="isLoading"
/>
<button @click="sendMessage" :disabled="isLoading">Send</button>
</div>
</div>
</template>
<script>
export default {
name: "AddisAIChat",
props: {
apiKey: {
type: String,
required: true,
},
},
data() {
return {
messages: [],
inputMessage: "",
isLoading: false,
conversationHistory: [],
};
},
methods: {
async sendMessage() {
if (!this.inputMessage.trim()) return;
// Add user message
const userMessage = { role: "user", content: this.inputMessage };
this.messages.push(userMessage);
const message = this.inputMessage;
this.inputMessage = "";
this.isLoading = true;
try {
// Call Addis AI API
const response = await fetch(
"https://api.addisassistant.com/api/v1/chat_generate",
{
method: "POST",
headers: {
"X-API-Key": this.apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({
prompt: message,
target_language: "am",
conversation_history: this.conversationHistory,
generation_config: { temperature: 0.7 },
}),
},
);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
// Add assistant response
const assistantMessage = {
role: "assistant",
content: data.response_text,
};
this.messages.push(assistantMessage);
// Update conversation history
this.conversationHistory.push(userMessage, assistantMessage);
} catch (error) {
console.error("Error:", error);
this.messages.push({
role: "system",
content: "Sorry, there was an error processing your request.",
});
} finally {
this.isLoading = false;
this.$nextTick(() => this.scrollToBottom());
}
},
scrollToBottom() {
const container = this.$refs.messagesContainer;
container.scrollTop = container.scrollHeight;
},
},
updated() {
this.scrollToBottom();
},
};
</script>
<style scoped>
.chat-container {
display: flex;
flex-direction: column;
height: 500px;
border: 1px solid #ccc;
border-radius: 8px;
overflow: hidden;
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 16px;
}
.message {
margin-bottom: 12px;
padding: 8px 12px;
border-radius: 8px;
max-width: 80%;
}
.user {
background-color: #dcf8c6;
align-self: flex-end;
margin-left: auto;
}
.assistant {
background-color: #f1f1f1;
align-self: flex-start;
}
.system {
background-color: #ffdddd;
align-self: center;
margin: 0 auto;
}
.chat-input {
display: flex;
padding: 8px;
border-top: 1px solid #ccc;
}
.chat-input input {
flex: 1;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
margin-right: 8px;
}
.chat-input button {
padding: 8px 16px;
background-color: #4caf50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.chat-input button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.loading .typing-indicator {
display: flex;
gap: 4px;
}
.typing-indicator span {
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #888;
animation: bounce 1.5s infinite;
}
.typing-indicator span:nth-child(2) {
animation-delay: 0.2s;
}
.typing-indicator span:nth-child(3) {
animation-delay: 0.4s;
}
@keyframes bounce {
0%,
60%,
100% {
transform: translateY(0);
}
30% {
transform: translateY(-6px);
}
}
</style>
text

Multi-modal Integration (Images + Text)

To support multi-modal inputs (sending images with text), use the FormData API:
// Example function to send image with text
async function sendImageWithText(imageFile, textPrompt, apiKey) {
const formData = new FormData();
formData.append("image1", imageFile);
formData.append(
"request_data",
JSON.stringify({
prompt: textPrompt,
target_language: "am",
attachment_field_names: ["image1"],
}),
);
try {
const response = await fetch(
"https://api.addisassistant.com/api/v1/chat_generate",
{
method: "POST",
headers: {
"X-API-Key": apiKey,
},
body: formData,
},
);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Error sending image with text:", error);
throw error;
}
}
javascript

Best Practices for Web Integration

  1. API Key Security: Never expose your API key in frontend code for production applications. Use a backend service to proxy requests to Addis AI.
  2. Error Handling: Implement comprehensive error handling to manage API failures, network issues, and unexpected responses.
  3. Loading States: Show clear loading indicators during API calls to improve user experience.
  4. Progressive Enhancement: Design your application to work even when the API is slow or temporarily unavailable.
  5. Performance Optimization:
    • Implement debouncing for rapid user inputs
    • Consider caching common responses
    • Limit the conversation history length for better performance
  6. Accessibility: Ensure your chat interface is accessible, including keyboard navigation and screen reader support.
  7. Mobile Responsiveness: Design your chat interface to work well on both desktop and mobile devices.

Common Issues and Solutions

CORS Issues

If you encounter CORS (Cross-Origin Resource Sharing) issues when calling the API directly from the browser, you'll need to:
  1. Set up a proxy server that adds the necessary CORS headers
  2. Use a serverless function (like AWS Lambda, Vercel Functions, etc.) to make the API calls

API Key Protection

To protect your API key in web applications:
  1. Create a backend API that proxies requests to Addis AI
  2. Use environment variables for server-side rendering frameworks
  3. Implement user authentication and rate limiting on your proxy

Large Attachments

When sending large files (images, audio):
  1. Compress files before sending when possible
  2. Implement progress indicators for uploads
  3. Consider chunked uploads for very large files

Handling Long Conversations

For managing long conversations:
  1. Implement token management as described in the Conversation Management documentation
  2. Consider session timeouts for inactive users
  3. Provide "clear conversation" functionality

Next Steps

Now that you've integrated Addis AI into your web application, you might want to:
  1. Explore Streaming Implementation for real-time responses
  2. Understand more about Multi-modal Input for richer interactions
  3. Check out Mobile Applications if you're building a hybrid app