Getting Started
REST API Integration
Connect your QwryAI agents to any app or workflow with the QwryAI API
Overview
The QwryAI API lets you put your agent's answers inside your own app, automate customer conversations and manage your workspace from code.
The Chat API sends messages to an agent and streams its replies over Server-Sent Events, with structured error codes. The Tools API reads and changes the rest of your workspace, such as agents, conversations and sources, with the same API key.
Base URL:
https://api.qwryai.com/api/v2Quick Start
- Get Your API Key
Workspace settings › API keys
- Open your QwryAI dashboard.
- Go to Workspace settings › API keys.
- Select Create API key, keep Chat with agents switched on and select Confirm. Then open the new key's ⋯ menu and choose Copy key.
- Get Your Agent ID
Call the
list_agentstool with your key. Each agent in the response has anid; use it wherever this guide showsYOUR_AGENT_ID.curl -X POST 'https://api.qwryai.com/public/v1/tools/list_agents' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{}' - Send Your First Message
Test your setup with a simple chat request:
curl -X POST 'https://api.qwryai.com/api/v2/agents/YOUR_AGENT_ID/chat' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{ "message": "Hello! How can you help me?", "stream": false }'Expected Response:
{ "data": { "id": "5b0e7c1a-2f4d-4c55-9a51-6d8e3f2b9c10", "role": "assistant", "parts": [ { "type": "text", "text": "Hi! I can answer questions about our products, orders and shipping. What do you need?" } ], "metadata": { "conversationId": "fd5ae9e1-9b30-4503-b346-ccd4d7ef16a3", "userMessageId": "0c4f6a2e-8d13-4b7a-b0e9-1a2c3d4e5f60", "userId": null, "finishReason": "stop", "usage": { "credits": 1 } } } } - Continue the Conversation
QwryAI keeps the conversation history, so you don't resend earlier messages. Pass the
conversationIdfrom the last response to send a follow-up:curl -X POST 'https://api.qwryai.com/api/v2/agents/YOUR_AGENT_ID/chat' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{ "message": "Tell me more about your pricing.", "conversationId": "fd5ae9e1-9b30-4503-b346-ccd4d7ef16a3", "stream": false }'To link a new conversation to one of your users, pass a
userIdwith the first message. See User Conversations.
Chat API Streaming
The chat endpoint streams replies as Server-Sent Events. Each event is a data: line holding a JSON object with a type, and the stream ends with data: [DONE]. Join the text-delta events to build the reply, and read the conversationId from the finish event to continue the conversation.
// streamer.js (Node.js 18+)
const apiKey = process.env.QWRYAI_API_KEY
const agentId = 'YOUR_AGENT_ID'
const apiUrl = `https://api.qwryai.com/api/v2/agents/${agentId}/chat`
async function readAgentReply() {
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: 'Do you ship to Canada?',
stream: true,
// conversationId: 'CONVERSATION_ID', // leave out to start a new conversation
}),
})
if (!response.ok) {
const { error } = await response.json()
throw new Error(`${error.code}: ${error.message}`)
}
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
let conversationId
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() // keep a partial line for the next chunk
for (const line of lines) {
if (!line.startsWith('data: ')) continue
const data = line.slice('data: '.length)
if (data === '[DONE]') continue
const event = JSON.parse(data)
switch (event.type) {
case 'text-delta':
process.stdout.write(event.delta)
break
case 'finish':
conversationId = event.messageMetadata.conversationId
break
case 'error':
console.error('\nStream error:', event.errorText)
break
}
}
}
console.log('\nConversation ID:', conversationId)
}
readAgentReply().catch((error) => console.log('Error:', error.message))# streamer.py
import json
import os
import requests
api_key = os.environ['QWRYAI_API_KEY']
agent_id = 'YOUR_AGENT_ID'
api_url = f'https://api.qwryai.com/api/v2/agents/{agent_id}/chat'
def read_agent_reply():
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json',
}
data = {
'message': 'Do you ship to Canada?',
'stream': True,
# 'conversationId': 'CONVERSATION_ID', # leave out to start a new conversation
}
response = requests.post(api_url, json=data, headers=headers, stream=True)
if not response.ok:
error = response.json()['error']
raise RuntimeError(f"{error['code']}: {error['message']}")
conversation_id = None
for line in response.iter_lines(decode_unicode=True):
if not line or not line.startswith('data: '):
continue
payload = line[len('data: '):]
if payload == '[DONE]':
continue
event = json.loads(payload)
if event['type'] == 'text-delta':
print(event['delta'], end='', flush=True)
elif event['type'] == 'finish':
conversation_id = event['messageMetadata']['conversationId']
elif event['type'] == 'error':
print(f"\nStream error: {event['errorText']}")
print(f'\nConversation ID: {conversation_id}')
read_agent_reply()Error Handling
Errors come back with a machine-readable code:
{
"error": {
"code": "RATE_LIMIT_TOO_MANY_REQUESTS",
"message": "Too many requests, please try again later"
}
}Every Chat API response has an x-request-id header; include it when you contact support. See Error Handling for every code and Rate limiting for limits and retries.
Performance Best Practices
Key API Endpoints
Chat API
Send messages and stream your agent's replies.
AI Agent Management
Read and configure your agents with the Tools API.
Conversations
Search chat history and read conversation messages.
Sources
Add and manage the sources your agents learn from.
API Overview
The full reference: authentication, streaming, client actions and pagination.