Code Examples
🐍 Python
import requests
import time
import os
# Configuration
API_KEY = "your_api_key_here"
BASE_URL = "https://gamma.joinable.ai/api"
headers = {
"X-API-Key": API_KEY,
"Content-Type": "application/json"
}
def print_response(response, title):
"""Helper function to print API responses"""
print(f"\n{title}:")
print(f"Status Code: {response.status_code}")
try:
data = response.json()
print("Response:", data)
return data
except Exception as e:
print(f"Error parsing response: {e}")
return None
def upload_file_to_collection(collection_id, file_path):
"""Upload a file to a collection using multipart form data"""
print(f"📤 Uploading {file_path} to collection {collection_id}...")
if not os.path.exists(file_path):
print(f"❌ File not found: {file_path}")
return None
try:
# Prepare file for multipart upload
with open(file_path, 'rb') as f:
files = [('files', (os.path.basename(file_path), f.read(), 'application/octet-stream'))]
# Upload file
upload_headers = {"X-API-Key": API_KEY}
response = requests.post(
f"{BASE_URL}/api/rag/collections/{collection_id}/documents/add/",
headers=upload_headers,
files=files
)
result = print_response(response, f"Upload {file_path}")
return result if result and result.get("status") == "success" else None
except Exception as e:
print(f"❌ Upload exception: {e}")
return None
def wait_for_vectordb_ready(collection_id, max_wait_time=300):
"""Wait for vector database to be ready"""
print(f"\n⏳ Waiting for vector database to be ready...")
print(f"⏰ Maximum wait time: {max_wait_time} seconds")
start_time = time.time()
while time.time() - start_time < max_wait_time:
try:
response = requests.get(
f"{BASE_URL}/api/rag/collections/{collection_id}/",
headers=headers
)
data = response.json()
if data.get("status") == "success":
collection = data.get("collection", {})
is_ready = collection.get("is_vectordb_ready", False)
if is_ready:
elapsed = int(time.time() - start_time)
print(f"✅ Vector database is ready! (took {elapsed} seconds)")
return True
else:
elapsed = int(time.time() - start_time)
print(f"⏰ Still processing... ({elapsed}s elapsed)", end="\r")
time.sleep(5) # Check every 5 seconds
else:
print(f"❌ Failed to get collection status: {data.get('message', 'Unknown error')}")
return False
except Exception as e:
print(f"❌ Error checking vector database status: {e}")
return False
print(f"\n❌ Vector database not ready after {max_wait_time} seconds")
return False
def main():
"""Complete RAG API workflow demonstration"""
print("🚀 STARTING RAG API COMPLETE WORKFLOW TEST")
print("="*60)
# Step 1: Create a new collection
print("\n📁 STEP 1: Creating new collection 'hello ragbox'")
print("="*60)
create_response = requests.post(
f"{BASE_URL}/api/rag/collections/create/",
headers=headers,
json={
"name": "hello ragbox",
"description": "A test collection for RAG API workflow",
"type": "knowledge-base",
"collection_external_knowledge_mode": False
}
)
create_result = print_response(create_response, "Create Collection")
if not create_result or create_result.get("status") != "success":
print("❌ Failed to create collection. Exiting.")
return
collection_id = create_result["collection"]["id"]
print(f"✅ Created collection with ID: {collection_id}")
# Step 2: Upload first file
print("\n📄 STEP 2: Uploading '5GTalk4.pdf'")
print("="*60)
upload_result = upload_file_to_collection(collection_id, "5GTalk4.pdf")
if not upload_result:
print("❌ Failed to upload first file. Exiting.")
return
# Step 3: Wait for vector database to be ready
print("\n🧠 STEP 3: Waiting for vector database processing")
print("="*60)
if not wait_for_vectordb_ready(collection_id):
print("❌ Vector database processing failed. Exiting.")
return
# Step 4: Create chat
print("\n💬 STEP 4: Creating chat")
print("="*60)
chat_response = requests.post(
f"{BASE_URL}/api/rag/{collection_id}/chat/",
headers=headers,
json={
"message": "What are the requirements for a 5G network?",
"modelProvider": "llama-4-17b",
"markdown": False
}
)
chat_result = print_response(chat_response, "Create Chat")
if not chat_result or chat_result.get("status") != "success":
print("❌ Failed to create chat. Exiting.")
return
chat_id = chat_result["chat_id"]
print(f"✅ Created chat with ID: {chat_id}")
# Step 5: Send follow-up message
print("\n💬 STEP 5: Sending follow-up message")
print("="*60)
send_response = requests.post(
f"{BASE_URL}/api/rag/{collection_id}/chat/{chat_id}/send/",
headers=headers,
json={
"message": "Explain better!",
"modelProvider": "llama-4-17b",
"markdown": False
}
)
send_result = print_response(send_response, "Send Message")
if not send_result or send_result.get("status") != "success":
print("❌ Failed to send message.")
# Step 6: Delete collection
print("\n🗑️ STEP 6: Deleting collection")
print("="*60)
delete_response = requests.delete(
f"{BASE_URL}/api/rag/collections/{collection_id}/delete/",
headers=headers
)
delete_result = print_response(delete_response, "Delete Collection")
if delete_result and delete_result.get("status") == "success":
print("✅ Collection deleted successfully!")
else:
print("❌ Failed to delete collection.")
print("\n" + "="*60)
print("🎉 RAG API COMPLETE WORKFLOW TEST FINISHED")
print("="*60)
if __name__ == "__main__":
main()
⚛️ JavaScript / TypeScript
const API_KEY = "your_api_key";
const BASE_URL = "https://gamma.joinable.ai/api";
const headersBase = {
"X-API-Key": API_KEY,
"Content-Type": "application/json"
};
async function jsonOrThrow(res: Response) {
const data = await res.json();
if (!res.ok || data.status !== "success") {
throw new Error(`API error ${res.status}: ${data?.message ?? "unknown"}`);
}
return data;
}
export async function createChat(collectionId: string, message: string) {
const res = await fetch(`${BASE_URL}/rag/${collectionId}/chat/`, {
method: "POST",
headers: headersBase,
body: JSON.stringify({ message, modelProvider: "llama-4-17b", markdown: false })
});
const data = await jsonOrThrow(res);
return data.chat_id;
}
export async function sendMessage(collectionId: string, chatId: string, message: string) {
const res = await fetch(`${BASE_URL}/rag/${collectionId}/chat/${chatId}/send/`, {
method: "POST",
headers: headersBase,
body: JSON.stringify({ message, modelProvider: "llama-4-17b", markdown: false })
});
return await jsonOrThrow(res);
}
export async function getChatHistory(collectionId: string, chatId: string) {
const res = await fetch(`${BASE_URL}/rag/${collectionId}/chat/${chatId}/messages/`, {
headers: headersBase
});
const data = await jsonOrThrow(res);
return data.messages;
}
// Example usage
(async () => {
const collection = "my-collection";
const chatId = await createChat(collection, "What is this collection about?");
const sendResp = await sendMessage(collection, chatId, "Tell me more about the first document");
const lastMsg = sendResp.messages.at(-1);
console.log("Assistant:", lastMsg.content);
if (lastMsg.sources?.length) {
console.log("Sources:");
lastMsg.sources.forEach(s =>
console.log(`- ${s.title ?? "Unknown"} (Page ${s.page ?? "N/A"})`)
);
}
const history = await getChatHistory(collection, chatId);
console.log("Full history:", history);
})();
🌀 cURL (Shell)
#!/usr/bin/env bash
BASE="https://gamma.joinable.ai/api"
COLLECTION="my-collection"
API_KEY="YOUR_API_KEY"
CHAT_ID="550e8400-e29b-41d4-a716-446655440000" # Replace after chat creation
# Step 1: Create chat session
curl -X POST "$BASE/rag/$COLLECTION/chat/" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{"message":"What is this collection about?","modelProvider":"llama-4-17b","markdown":false}'
# Step 2: Send message
curl -X POST "$BASE/rag/$COLLECTION/chat/$CHAT_ID/send/" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{"message":"Tell me more about the first document","modelProvider":"llama-4-17b","markdown":false}'
# Step 3: Get chat history
curl -X GET "$BASE/rag/$COLLECTION/chat/$CHAT_ID/messages/" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json"
Last updated