Basic Chat Implementation

This tutorial shows how to implement a simple chat interface using the Addis AI API. We'll cover implementations in multiple languages and platforms.

Prerequisites

  • An Addis AI API key
  • Basic knowledge of your chosen programming language
  • A development environment set up for web or application development

JavaScript Implementation (Web)

Setting Up

First, create a basic HTML structure for your chat interface:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Addis AI Chat Demo</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.chat-container {
border: 1px solid #ddd;
border-radius: 8px;
overflow: hidden;
}
.chat-messages {
height: 400px;
overflow-y: auto;
padding: 16px;
background: #f9f9f9;
}
.message {
margin-bottom: 12px;
padding: 8px 12px;
border-radius: 8px;
max-width: 70%;
}
.user-message {
background: #e1f5fe;
margin-left: auto;
}
.assistant-message {
background: #fff;
border: 1px solid #eee;
}
.input-area {
display: flex;
padding: 8px;
border-top: 1px solid #ddd;
}
input {
flex: 1;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
padding: 8px 16px;
background: #2196f3;
color: white;
border: none;
border-radius: 4px;
margin-left: 8px;
cursor: pointer;
}
button:hover {
background: #0b7dda;
}
.language-selector {
margin-bottom: 16px;
}
.loading {
text-align: center;
padding: 12px;
}
</style>
</head>
<body>
<h1>Addis AI Chat Demo</h1>
<div class="language-selector">
<label>Response Language:</label>
<select id="language">
<option value="am">Amharic</option>
<option value="om">Afan Oromo</option>
</select>
</div>
<div class="chat-container">
<div id="chat-messages" class="chat-messages"></div>
<div class="input-area">
<input
type="text"
id="user-input"
placeholder="Type your message here..."
/>
<button id="send-button">Send</button>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
html
Next, create an app.js file for the chat functionality:
// Replace with your API key
const API_KEY = "YOUR_API_KEY";
// DOM elements
const chatMessages = document.getElementById("chat-messages");
const userInput = document.getElementById("user-input");
const sendButton = document.getElementById("send-button");
const languageSelect = document.getElementById("language");
// Conversation history for context
let conversationHistory = [];
// Event listeners
sendButton.addEventListener("click", sendMessage);
userInput.addEventListener("keypress", (e) => {
if (e.key === "Enter") sendMessage();
});
// Function to send user message and get AI response
async function sendMessage() {
const message = userInput.value.trim();
if (!message) return;
// Add user message to chat
addMessage(message, "user");
userInput.value = "";
// Add loading indicator
const loadingDiv = document.createElement("div");
loadingDiv.className = "loading";
loadingDiv.textContent = "Addis AI is thinking...";
chatMessages.appendChild(loadingDiv);
try {
// Get selected language
const language = languageSelect.value;
// Call Addis AI API
const response = await callAddisAI(message, language);
// Remove loading indicator
chatMessages.removeChild(loadingDiv);
// Add AI response to chat
addMessage(response.data.response_text, "assistant");
// Update conversation history
conversationHistory.push(
{ role: "user", content: message },
{ role: "assistant", content: response.response_text },
);
// Auto-scroll to bottom
chatMessages.scrollTop = chatMessages.scrollHeight;
} catch (error) {
// Remove loading indicator
chatMessages.removeChild(loadingDiv);
// Show error message
addMessage("Sorry, there was an error: " + error.message, "assistant");
}
}
// Function to add a message to the chat UI
function addMessage(text, sender) {
const messageDiv = document.createElement("div");
messageDiv.className = `message ${sender}-message`;
messageDiv.textContent = text;
chatMessages.appendChild(messageDiv);
// Auto-scroll to bottom
chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Function to call the Addis AI API
async function callAddisAI(prompt, targetLanguage) {
const url = "https://api.addisassistant.com/api/v1/chat_generate";
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-API-Key": API_KEY,
},
body: JSON.stringify({
prompt: prompt,
target_language: targetLanguage,
conversation_history: conversationHistory,
generation_config: {
temperature: 0.7,
},
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error?.message || "Unknown error");
}
return await response.json();
}
javascript

Running the Web Application

  1. Replace YOUR_API_KEY in the JavaScript code with your actual Addis AI API key
  2. Open the HTML file in a web browser
  3. Start typing messages and receive responses in your selected language

Python Implementation (Command Line)

Here's a simple command-line chat application using Python:
import requests
import json
# Replace with your API key
API_KEY = "YOUR_API_KEY"
# API endpoint
URL = "https://api.addisassistant.com/api/v1/chat_generate"
# Headers
headers = {
"Content-Type": "application/json",
"X-API-Key": API_KEY,
}
def call_addis_ai(prompt, target_language, conversation_history=None):
"""
Call the Addis AI API.
Args:
prompt (str): User message
target_language (str): Target language code (am/om)
conversation_history (list): Previous conversation messages
Returns:
dict: API response
"""
# Prepare request data
data = {
"prompt": prompt,
"target_language": target_language,
"generation_config": {
"temperature": 0.7
}
}
if conversation_history:
data["conversation_history"] = conversation_history
try:
# Make API request
response = requests.post(URL, headers=headers, json=data)
# Check for errors
if response.status_code != 200:
error_data = response.json()
error_message = error_data.get("error", {}).get("message", "Unknown error")
print(f"Error: {error_message}")
return None
# Return response data
return response.json()
except Exception as e:
print(f"Request failed: {str(e)}")
return None
def main():
print("Addis AI Chat Demo")
print("Type 'quit' to exit")
# Select language
print("\nSelect language:")
print("1. Amharic (am)")
print("2. Afan Oromo (om)")
language_choice = input("Enter your choice (1/2): ")
target_language = "am" if language_choice == "1" else "om"
# Initialize conversation history
conversation_history = []
# Main chat loop
while True:
# Get user input
user_message = input("\nYou: ")
# Check for exit command
if user_message.lower() in ["quit", "exit", "q"]:
print("Goodbye!")
break
# Call API
print("Addis AI is thinking...")
response = call_addis_ai(user_message, target_language, conversation_history)
if response:
# Extract response text
ai_message = response["response_text"]
# Print response
print(f"\nAddis AI: {ai_message}")
# Update conversation history
conversation_history.append({"role": "user", "content": user_message})
conversation_history.append({"role": "assistant", "content": ai_message})
if __name__ == "__main__":
main()
python

Running the Python Application

  1. Install the required package: pip install requests
  2. Replace YOUR_API_KEY with your actual Addis AI API key
  3. Run the script: python chat_app.py
  4. Follow the prompts to select a language and start chatting

React Native Implementation (Mobile)

For mobile applications, here's a basic implementation using React Native:

Setting Up

# Create a new React Native project
npx react-native init AddisAIChat
# Navigate to project directory
cd AddisAIChat
# Install dependencies
npm install @react-native-picker/picker
bash

Implementation

Replace the contents of App.js with the following:
import React, { useState, useRef } from "react";
import {
SafeAreaView,
StyleSheet,
View,
Text,
TextInput,
TouchableOpacity,
FlatList,
ActivityIndicator,
KeyboardAvoidingView,
Platform,
} from "react-native";
import { Picker } from "@react-native-picker/picker";
// Replace with your API key
const API_KEY = "YOUR_API_KEY";
const App = () => {
const [messages, setMessages] = useState([]);
const [inputText, setInputText] = useState("");
const [language, setLanguage] = useState("am");
const [loading, setLoading] = useState(false);
const [conversationHistory, setConversationHistory] = useState([]);
const flatListRef = useRef();
// Function to send message
const sendMessage = async () => {
if (!inputText.trim()) return;
// Add user message
const userMessage = {
id: Date.now().toString(),
text: inputText,
sender: "user",
};
setMessages((prevMessages) => [...prevMessages, userMessage]);
setInputText("");
setLoading(true);
try {
// Call Addis AI API
const response = await fetch(
"https://api.addisassistant.com/api/v1/chat_generate",
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-API-Key": API_KEY,
},
body: JSON.stringify({
prompt: userMessage.text,
target_language: language,
conversation_history: conversationHistory,
generation_config: {
temperature: 0.7,
},
}),
},
);
const data = await response.json();
if (response.ok) {
// Add AI response
const aiMessage = {
id: (Date.now() + 1).toString(),
text: data.response_text,
sender: "assistant",
};
setMessages((prevMessages) => [...prevMessages, aiMessage]);
// Update conversation history
const updatedHistory = [
...conversationHistory,
{ role: "user", content: userMessage.text },
{ role: "assistant", content: data.response_text },
];
setConversationHistory(updatedHistory);
} else {
// Handle error
const errorMessage = {
id: (Date.now() + 1).toString(),
text: `Error: ${data.error?.message || "Something went wrong"}`,
sender: "assistant",
};
setMessages((prevMessages) => [...prevMessages, errorMessage]);
}
} catch (error) {
// Handle exception
const errorMessage = {
id: (Date.now() + 1).toString(),
text: `Error: ${error.message}`,
sender: "assistant",
};
setMessages((prevMessages) => [...prevMessages, errorMessage]);
} finally {
setLoading(false);
}
};
// Render message item
const renderMessageItem = ({ item }) => (
<View
style={[
styles.messageBubble,
item.sender === "user" ? styles.userBubble : styles.aiBubble,
]}
>
<Text style={styles.messageText}>{item.text}</Text>
</View>
);
return (
<SafeAreaView style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>Addis AI Chat</Text>
</View>
<View style={styles.languageSelector}>
<Text>Response Language:</Text>
<Picker
selectedValue={language}
style={styles.picker}
onValueChange={(itemValue) => setLanguage(itemValue)}
>
<Picker.Item label="Amharic" value="am" />
<Picker.Item label="Afan Oromo" value="om" />
</Picker>
</View>
<FlatList
ref={flatListRef}
data={messages}
renderItem={renderMessageItem}
keyExtractor={(item) => item.id}
style={styles.messageList}
contentContainerStyle={styles.messageListContent}
onContentSizeChange={() =>
flatListRef.current?.scrollToEnd({ animated: true })
}
/>
{loading && (
<View style={styles.loadingContainer}>
<ActivityIndicator size="small" color="#2196F3" />
<Text style={styles.loadingText}>Addis AI is thinking...</Text>
</View>
)}
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.inputContainer}
>
<TextInput
style={styles.input}
value={inputText}
onChangeText={setInputText}
placeholder="Type your message here..."
onSubmitEditing={sendMessage}
returnKeyType="send"
/>
<TouchableOpacity style={styles.sendButton} onPress={sendMessage}>
<Text style={styles.sendButtonText}>Send</Text>
</TouchableOpacity>
</KeyboardAvoidingView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
},
header: {
padding: 16,
borderBottomWidth: 1,
borderBottomColor: "#eee",
backgroundColor: "#2196F3",
},
headerText: {
fontSize: 18,
fontWeight: "bold",
color: "white",
},
languageSelector: {
flexDirection: "row",
alignItems: "center",
padding: 12,
borderBottomWidth: 1,
borderBottomColor: "#eee",
},
picker: {
flex: 1,
height: 50,
},
messageList: {
flex: 1,
},
messageListContent: {
padding: 16,
},
messageBubble: {
maxWidth: "80%",
padding: 12,
borderRadius: 16,
marginBottom: 12,
},
userBubble: {
backgroundColor: "#e1f5fe",
alignSelf: "flex-end",
},
aiBubble: {
backgroundColor: "#f1f1f1",
alignSelf: "flex-start",
},
messageText: {
fontSize: 16,
},
inputContainer: {
flexDirection: "row",
padding: 12,
borderTopWidth: 1,
borderTopColor: "#eee",
},
input: {
flex: 1,
borderWidth: 1,
borderColor: "#ddd",
borderRadius: 24,
paddingHorizontal: 16,
paddingVertical: 8,
backgroundColor: "#f9f9f9",
},
sendButton: {
marginLeft: 12,
padding: 12,
backgroundColor: "#2196F3",
borderRadius: 24,
justifyContent: "center",
},
sendButtonText: {
color: "white",
fontWeight: "bold",
},
loadingContainer: {
position: "absolute",
bottom: 80,
left: 0,
right: 0,
alignItems: "center",
padding: 8,
},
loadingText: {
marginTop: 4,
color: "#666",
},
});
export default App;
jsx

Running the React Native App

  1. Replace YOUR_API_KEY with your actual Addis AI API key
  2. Run the app:
    • iOS: npx react-native run-ios
    • Android: npx react-native run-android

Next Steps

Now that you've implemented a basic chat interface, you can enhance it with:
  1. Speech-to-Text: Add voice input using your platform's speech recognition capabilities
  2. Text-to-Speech: Integrate the Addis AI /audio endpoint to speak the responses
  3. Multi-modal Input: Add image upload capability to send images along with text
  4. Streaming Responses: Implement streaming for more responsive interactions
Visit our Voice Interface Implementation tutorial to learn how to enhance your chat application with speech capabilities.

Troubleshooting

Common Issues

  1. Authentication errors: Make sure your API key is valid and correctly formatted
  2. Network errors: Check your internet connection and API endpoint URL
  3. Response format errors: Verify you're parsing the response correctly
For more detailed troubleshooting, refer to our FAQ and Troubleshooting guide.