// Basic Addis AI API clientclass AddisAIClient {constructor(apiKey) {this.apiKey = apiKey;this.baseUrl = "https://api.addisassistant.com/api/v1";this.conversationHistory = [];}// Send a message to the chat APIasync 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 historythis.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 historyclearConversation() {this.conversationHistory = [];}// Text-to-speech conversionasync 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 exampledocument.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 messageappendMessage("user", message);messageInput.value = "";try {// Send to API and get responseconst response = await client.sendMessage(message);// Display AI responseappendMessage("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;}});
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 messagesconst scrollToBottom = () => {messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });};useEffect(() => {scrollToBottom();}, [messages]);const sendMessage = async () => {if (!input.trim()) return;// Add user message to UIconst userMessage = { role: "user", content: input };setMessages((prev) => [...prev, userMessage]);setInput("");setIsLoading(true);try {// Call Addis AI APIconst 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 UIconst assistantMessage = {role: "assistant",content: data.response_text,};setMessages((prev) => [...prev, assistantMessage]);// Update conversation history for next requestsetConversationHistory((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"><inputtype="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;
<template><div class="chat-container"><div class="chat-messages" ref="messagesContainer"><divv-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"><inputtype="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 messageconst userMessage = { role: "user", content: this.inputMessage };this.messages.push(userMessage);const message = this.inputMessage;this.inputMessage = "";this.isLoading = true;try {// Call Addis AI APIconst 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 responseconst assistantMessage = {role: "assistant",content: data.response_text,};this.messages.push(assistantMessage);// Update conversation historythis.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>
FormData
API:
// Example function to send image with textasync 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;}}