Docs/Resources

Code Examples

Real-world integration examples for common use cases.

Copy-paste starting points for common things people build. Swap in your own key and model.

Customer support chatbot

A chat UI with message history. The browser talks to your backend, and your backend calls Tarqa, so the API key never reaches the browser.

import { useState } from 'react';

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

  const sendMessage = async () => {
    if (!input.trim()) return;
    const next = [...messages, { role: 'user', content: input }];
    setMessages(next);
    setInput('');
    setLoading(true);
    try {
      // Your own backend route (see the next tab) — never call Tarqa from the browser
      const res = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ messages: next }),
      });
      const { reply } = await res.json();
      setMessages(prev => [...prev, { role: 'assistant', content: reply }]);
    } 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)}
        onKeyDown={(e) => e.key === 'Enter' && sendMessage()}
        disabled={loading}
      />
    </div>
  );
}

Ask questions about a PDF

Extract the text from a PDF, index it with RAG, then ask a question.

Python
import requests
import PyPDF2

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

def analyze_document(pdf_path: str, question: str) -> str:
    # Extract text from the 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}/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}/v1/rag/index",
        json={"conversationId": conv_id, "documentText": document_text, "metadata": {"filename": pdf_path}},
        headers=headers,
    )

    # 3. Ask — the answer comes from the indexed content
    resp = requests.post(
        f"{BASE_URL}/v1/rag/chat",
        json={"conversationId": conv_id, "message": question, "model": "gemini-2.5-flash", "topK": 5},
        headers=headers,
    ).json()
    return resp["answer"]

print(analyze_document("contract.pdf", "What are the termination clauses?"))

More ideas

BuildHow
Multi-language translatorChat API with a translation system prompt, streamed for real-time output.
Sales email generatorBatch requests, each with a different customer context.
Content moderationAsk the model to classify text into fixed labels with a structured prompt.
Data extractionAsk for JSON output with the fields you need from unstructured text.