Code Examples

Real-world integration examples for common use cases

Customer support chatbot

Real-time streaming chat with message history
React Component
import { useState } from 'react';

function SupportChatbot() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);

  const sendMessage = async () => {
    if (!input.trim()) return;

    const userMessage = { role: 'user', content: input };
    setMessages(prev => [...prev, userMessage]);
    setInput('');
    setLoading(true);

    try {
      const response = await fetch(`${BASE_URL}/v1/chat/completions`, {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          model: 'gemini-2.5-flash',
          messages: [...messages, userMessage],
          stream: false
        })
      });

      const data = await response.json();
      const aiMessage = {
        role: 'assistant',
        content: data.choices[0].message.content
      };

      setMessages(prev => [...prev, aiMessage]);
    } catch (error) {
      console.error('Chat error:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="chat-container">
      <div className="messages">
        {messages.map((msg, i) => (
          <div key={i} className={`message ${msg.role}`}>
            {msg.content}
          </div>
        ))}
      </div>
      <input
        value={input}
        onChange={(e) => setInput(e.target.value)}
        onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
        disabled={loading}
      />
    </div>
  );
}

Document analysis tool

Upload PDFs and ask questions using RAG
Python Backend
import requests
import PyPDF2

API_KEY = "YOUR_TARQA_API_KEY"
BASE_URL = "https://tarqaai.com"
headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
}

def analyze_document(pdf_path: str, question: str) -> str:
    # Extract text from PDF
    with open(pdf_path, "rb") as f:
        reader = PyPDF2.PdfReader(f)
        document_text = "\n".join(
            page.extract_text() for page in reader.pages
        )

    # 1. Create a RAG conversation
    conv = requests.post(
        f"{BASE_URL}/api/v1/context/conversations/create",
        json={"title": "Document Analysis", "knowledgeBaseType": "custom"},
        headers=headers,
    ).json()
    conv_id = conv["data"]["id"]

    # 2. Index the document text
    requests.post(
        f"{BASE_URL}/api/v1/rag/index",
        json={
            "conversationId": conv_id,
            "documentText": document_text,
            "metadata": {"filename": pdf_path},
        },
        headers=headers,
    )

    # 3. Ask a question — AI answers from indexed content
    resp = requests.post(
        f"{BASE_URL}/api/v1/rag/chat",
        json={
            "conversationId": conv_id,
            "message": question,
            "model": "gemini-2.5-flash",
            "topK": 5,
        },
        headers=headers,
    ).json()

    return resp["answer"]

# Usage
answer = analyze_document(
    "contract.pdf",
    "What are the termination clauses?",
)
print(answer)

Multi-language translator

Real-time translation using streaming responses
Use Chat API with system prompt for translation

Sales email generator

Generate personalized sales emails at scale
Batch requests with different contexts

Content moderation

Automatically flag inappropriate content
Classification with structured prompts

Data extraction

Extract structured data from unstructured text
JSON output formatting with prompts