Code Examples
Common use cases and code examples for the ExoGraph API.
Quick Examples
Simple Chat Query
bash
curl -X POST https://exograph.ai/agent/interactions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "snap",
"messages": [{
"role": "user",
"content": "What is quantum computing?"
}]
}'python
import requests
response = requests.post(
"https://exograph.ai/agent/interactions",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json={
"model": "snap",
"messages": [{
"role": "user",
"content": "What is quantum computing?"
}]
}
)
result = response.json()
answer = result['messages'][-1]['content']
tokens_used = result['usage']['tokens_consumed']
print(f"Answer: {answer}")
print(f"Tokens used: {tokens_used}")javascript
const response = await fetch('https://exograph.ai/agent/interactions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'snap',
messages: [{
role: 'user',
content: 'What is quantum computing?'
}]
})
});
const result = await response.json();
console.log('Answer:', result.messages[result.messages.length - 1].content);
console.log('Tokens used:', result.usage.tokens_consumed);Document Upload
bash
curl -X POST https://exograph.ai/api/documents \
-H "Authorization: Bearer YOUR_API_KEY" \
-F "file=@paper.pdf"python
import requests
with open("paper.pdf", "rb") as file:
response = requests.post(
"https://exograph.ai/api/documents",
headers={"Authorization": "Bearer YOUR_API_KEY"},
files={"file": file}
)
doc = response.json()
print(f"Document ID: {doc['doc_id']}")
print(f"Graph ID: {doc['graph_id']}")javascript
const formData = new FormData();
formData.append('file', fileInput.files[0]);
const response = await fetch('https://exograph.ai/api/documents', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
},
body: formData
});
const doc = await response.json();
console.log(`Document ID: ${doc.doc_id}`);Multi-turn Conversation
python
class ChatSession:
def __init__(self, api_key):
self.api_key = api_key
self.messages = []
def chat(self, question):
self.messages.append({"role": "user", "content": question})
response = requests.post(
"https://exograph.ai/agent/interactions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": "snap",
"reasoning_engine": "graph",
"messages": self.messages
}
)
result = response.json()
self.messages = result['messages']
return result['messages'][-1]['content']
# Use it
session = ChatSession("YOUR_API_KEY")
print(session.chat("What is ExoGraph?"))
print(session.chat("How does it work?"))
print(session.chat("Can you give me an example?"))Autonomous Research
python
def research_topic(topic):
response = requests.post(
"https://exograph.ai/agent/research",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"topic": topic,
"model": "ponder",
"max_results": 10
}
)
research = response.json()
print(f"✅ Research complete!")
print(f" Document: {research['doc_id']}")
print(f" Graph: {research['graph_id']}")
print(f" Sources: {len(research['sources'])}")
print(f" Tokens used: {research['usage']['tokens_consumed']}")
return research
# Use it
result = research_topic("Recent advances in quantum error correction")
# Now query the research results
chat_response = requests.post(
"https://exograph.ai/agent/interactions",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"model": "snap",
"target_doc_id": result['doc_id'],
"messages": [{
"role": "user",
"content": "Summarize the key findings"
}]
}
).json()
print(chat_response['messages'][-1]['content'])Batch Document Processing
python
import os
def process_documents(directory):
results = []
for filename in os.listdir(directory):
if filename.endswith('.pdf'):
with open(f"{directory}/{filename}", "rb") as file:
response = requests.post(
"https://exograph.ai/api/documents",
headers={"Authorization": f"Bearer {API_KEY}"},
files={"file": file}
)
doc = response.json()
results.append({
"filename": filename,
"doc_id": doc['doc_id'],
"graph_id": doc['graph_id'],
"pages": doc['pages_count']
})
print(f"✅ Processed: {filename}")
return results
# Use it
docs = process_documents("./papers")
print(f"\n📊 Processed {len(docs)} documents")
print(f"Total tokens: {sum(5 + d['pages'] for d in docs)}")Knowledge Graph Building
python
# 1. Create a knowledge graph
graph = requests.post(
"https://exograph.ai/api/graphs",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"name": "AI Research KB",
"description": "Collection of AI research papers"
}
).json()
graph_id = graph['graph_id']
# 2. Upload and add documents to the graph
docs = ["paper1.pdf", "paper2.pdf", "paper3.pdf"]
for paper in docs:
# Upload document
with open(paper, "rb") as file:
doc = requests.post(
"https://exograph.ai/api/documents",
headers={"Authorization": f"Bearer {API_KEY}"},
files={"file": file}
).json()
# Import to graph
requests.post(
f"https://exograph.ai/api/graphs/{graph_id}/import-from-document",
headers={"Authorization": f"Bearer {API_KEY}"},
json={"doc_id": doc['doc_id']}
)
# 3. Query the unified knowledge graph
response = requests.post(
"https://exograph.ai/agent/interactions",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"model": "snap",
"reasoning_engine": "graph",
"target_graph_id": graph_id,
"messages": [{
"role": "user",
"content": "What are the common themes across all papers?"
}]
}
).json()
print(response['messages'][-1]['content'])Token Usage Tracking
python
class TokenTracker:
def __init__(self, api_key):
self.api_key = api_key
self.total_tokens = 0
self.operations = []
def chat(self, question, **kwargs):
response = requests.post(
"https://exograph.ai/agent/interactions",
headers={"Authorization": f"Bearer {self.api_key}"},
json={
"model": "snap",
"messages": [{"role": "user", "content": question}],
**kwargs
}
).json()
tokens = response['usage']['tokens_consumed']
self.total_tokens += tokens
self.operations.append({
"type": "chat",
"tokens": tokens,
"balance": response['usage']['balance_remaining']
})
return response
def summary(self):
print(f"📊 Usage Summary")
print(f" Operations: {len(self.operations)}")
print(f" Total tokens: {self.total_tokens}")
print(f" Current balance: {self.operations[-1]['balance']}")
print(f" Cost: ${self.total_tokens / 4:.2f}")
# Use it
tracker = TokenTracker("YOUR_API_KEY")
tracker.chat("What is quantum computing?")
tracker.chat("How does it work?")
tracker.summary()Error Handling
python
def safe_api_call(url, **kwargs):
try:
response = requests.post(url, **kwargs)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
print("❌ Invalid API key")
elif e.response.status_code == 402:
print("❌ Insufficient tokens")
elif e.response.status_code == 429:
print("❌ Rate limit exceeded")
else:
print(f"❌ Error: {e.response.json()['error']['message']}")
return None
# Use it
result = safe_api_call(
"https://exograph.ai/agent/interactions",
headers={"Authorization": f"Bearer {API_KEY}"},
json={"model": "snap", "messages": [...]}
)More Examples
- API Reference - All endpoint documentation
- Best Practices - Production tips
- Use Cases - Real-world applications
Questions? Contact support@exograph.ai