Exa AI Tutorial: Neural Search API for AI Applications and RAG
Exa AI is a search engine designed specifically for AI applications and Large Language Models (LLMs). Unlike traditional search engines that rely on keyword matching, Exa uses neural embeddings to understand the semantic meaning of search queries. This makes it an incredibly powerful tool for building Retrieval-Augmented Generation (RAG) systems, AI agents, and other search-based applications.
In this tutorial, we will learn how to use the Exa AI Python SDK comprehensively, from basic search operations to building integrated RAG pipelines with LLMs.
Why Exa AI?
Conventional search engines like Google are designed for human users. Their results are web pages that need to be parsed and their content extracted. Exa takes a different approach:
- Neural Search: Understands query meaning, not just keyword matching
- Content Extraction: Retrieves web page content directly in clean format
- Similarity Search: Finds pages similar to a given URL
- Structured Filtering: Filter by date, domain, category, and more
- API-First: Built from the ground up to be consumed by programs, not humans
Installation and Setup
Install the SDK
pip install exa-py
Getting Your API Key
Sign up at dashboard.exa.ai to get your API key. Exa provides free credits to get started.
Configuration
import os
from exapy import Exa
exa = Exa(apikey=os.environ.get("EXAAPIKEY"))
Store your API key in an environment variable:
export EXAAPIKEY="your-api-key-here"
Basic Search
Exa provides three search modes: neural, keyword, and auto.
Neural Search
Neural search uses embeddings to understand query meaning. This mode is ideal for natural language queries.
from exapy import Exa
exa = Exa(api
key="YOURAPIKEY")
results = exa.search(
query="best tutorials for learning machine learning from scratch",
type="neural",
numresults=5
)
for result in results.results:
print(f"Title: {result.title}")
print(f"URL: {result.url}")
print(f"Score: {result.score}")
print("---")
Keyword Search
Keyword search uses traditional keyword matching, suitable for searching specific technical terms.
results = exa.search(
query="PyTorch transformer implementation",
type="keyword",
numresults=5
)
Auto Search
Auto mode lets Exa choose the best search method based on the query.
results = exa.search(
query="how to fine-tune LLaMA model",
type="auto",
numresults=10
)
Retrieving Page Content
One of Exa's most powerful features is its ability to extract web page content directly.
Search and Contents
Combine search with content extraction in a single API call:
results = exa.searchandcontents(
query="complete guide to RAG with LangChain",
type="neural",
num
results=3,
text=True
)
for result in results.results:
print(f"Title: {result.title}")
print(f"URL: {result.url}")
print(f"Text (500 chars): {result.text[:500]}")
print("===")
Highlights
Get the most relevant portions of a page without fetching the entire content:
results = exa.searchandcontents(
query="best practices deploying ML models to production",
type="neural",
numresults=5,
highlights={
"numsentences": 3,
"highlightsperurl": 2
}
)
for result in results.results:
print(f"Title: {result.title}")
for highlight in result.highlights:
print(f" - {highlight}")
print("---")
Summary
Ask Exa to generate a summary for each page:
results = exa.searchandcontents(
query="recent advances in multimodal AI",
type="neural",
numresults=5,
summary=True
)
for result in results.results:
print(f"Title: {result.title}")
print(f"Summary: {result.summary}")
print("---")
Get Contents by URL
If you already have URLs, retrieve their content directly:
contents = exa.getcontents(
urls=[
"https://arxiv.org/abs/2301.00234",
"https://huggingface.co/blog/peft"
],
text=True
)
for item in contents.results:
print(f"Title: {item.title}")
print(f"Content length: {len(item.text)} chars")
Similarity Search
Find pages similar to a given URL. This feature is invaluable for content recommendation.
similar = exa.findsimilar(
url="https://lilianweng.github.io/posts/2023-06-23-agent/",
num
results=5
)
print("Pages similar to Lilian Weng's AI Agents blog post:")
for result in similar.results:
print(f" - {result.title}: {result.url}")
Combine with content extraction:
similar = exa.findsimilarandcontents(
url="https://jalammar.github.io/illustrated-transformer/",
num
results=3,
highlights={"numsentences": 2}
)
Filtering and Advanced Parameters
Date Filtering
from datetime import datetime, timedelta
onemonthago = (datetime.now() - timedelta(days=30)).strftime("%Y-%m-%d")
results = exa.search(
query="LLM optimization techniques",
type="neural",
numresults=10,
startpublisheddate=onemonthago
)
Domain Filtering
Restrict search to specific domains:
results = exa.search(
query="machine learning tutorial",
type="neural",
numresults=5,
includedomains=["arxiv.org", "huggingface.co", "github.com"]
)
Or exclude certain domains:
results = exa.search(
query="python data science",
type="neural",
numresults=5,
excludedomains=["medium.com", "towardsdatascience.com"]
)
Category Filtering
Exa supports filtering by content category:
results = exa.search(
query="AI startup funding 2026",
type="neural",
numresults=10,
category="news"
)
Available categories: company, research paper, news, pdf, github, tweet, personal site, linkedin profile, and more.
Text Filtering
Ensure results contain or exclude specific text:
results = exa.search(
query="deep learning framework comparison",
type="neural",
numresults=5,
includetext=["PyTorch", "benchmark"],
excludetext=["TensorFlow 1.x"]
)
LangChain Integration
Exa has an official LangChain integration through the langchain-exa package.
pip install langchain-exa langchain-openai langchain
Exa as a Retriever
from langchainexa import ExaSearchRetriever
from langchain
openai import ChatOpenAI
from langchaincore.prompts import ChatPromptTemplate
from langchaincore.outputparsers import StrOutputParser
retriever = ExaSearchRetriever(
k=3,
highlights=True,
exaapikey="YOUREXAKEY"
)
llm = ChatOpenAI(model="gpt-4o-mini")
prompt = ChatPromptTemplate.fromtemplate("""
Based on the following context, answer the question in detail.
Context:
{context}
Question: {question}
Answer:
""")
def formatdocs(docs):
return "\n\n".join(
f"Source: {doc.metadata['url']}\n{doc.pagecontent}"
for doc in docs
)
chain = (
{"context": retriever | formatdocs, "question": lambda x: x}
| prompt
| llm
| StrOutputParser()
)
answer = chain.invoke("What are the latest developments in LLM fine-tuning?")
print(answer)
Exa as a Tool for Agents
from langchainexa import ExaSearchResults
from langchain.agents import createtoolcallingagent, AgentExecutor
from langchainopenai import ChatOpenAI
from langchaincore.prompts import ChatPromptTemplate
exatool = ExaSearchResults(exaapikey="YOUREXAKEY")
tools = [exatool]
prompt = ChatPromptTemplate.frommessages([
("system", "You are an AI research assistant that helps find up-to-date information."),
("human", "{input}"),
("placeholder", "{agentscratchpad}")
])
llm = ChatOpenAI(model="gpt-4o-mini")
agent = createtoolcallingagent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
result = executor.invoke({
"input": "Search for the latest papers on mixture of experts and provide a summary"
})
print(result["output"])
Building a RAG Pipeline with Exa
Here is a complete example of building a RAG system using Exa as the retriever and Claude as the LLM:
import anthropic
from exapy import Exa
exa = Exa(apikey="YOUREXAKEY")
client = anthropic.Anthropic(apikey="YOURANTHROPICKEY")
def searchandanswer(question: str) -> str:
searchresults = exa.searchandcontents(
query=question,
type="auto",
numresults=5,
highlights={
"numsentences": 3,
"highlightsperurl": 2
}
)
contextparts = []
sources = []
for result in searchresults.results:
sources.append(f"- {result.title}")
for highlight in result.highlights:
contextparts.append(f"[{result.title}]: {highlight}")
context = "\n\n".join(contextparts)
sourcestext = "\n".join(sources)
message = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=1024,
messages=[
{
"role": "user",
"content": f"""Based on the following search context, answer the question with detail and accuracy.
If the information is insufficient, say so honestly.
Context:
{context}
Question: {question}
Provide a structured answer and include insights from the discovered sources."""
}
]
)
answer = message.content[0].text
return f"{answer}\n\nSources:\n{sourcestext}"
response = searchandanswer("How to optimize LLM inference for production?")
print(response)
Asynchronous Usage
For high-performance applications, use the async client:
import asyncio
from exapy import Exa
exa = Exa(apikey="YOUREXAKEY")
async def parallelsearch():
queries = [
"latest breakthroughs in protein folding AI",
"state of the art text to image models 2026",
"efficient LLM serving techniques"
]
tasks = [
exa.searchandcontentsasync(
query=q,
type="neural",
numresults=3,
highlights={"numsentences": 2}
)
for q in queries
]
results = await asyncio.gather(*tasks)
for query, result in zip(queries, results):
print(f"\nQuery: {query}")
for r in result.results:
print(f" - {r.title}")
asyncio.run(parallelsearch())
Example Application: Research Assistant
Here is a complete example of a research assistant that uses Exa to find academic papers and generate summaries:
from exapy import Exa
import json
exa = Exa(api
key="YOUREXAKEY")
def researchtopic(topic: str, maxpapers: int = 5) -> dict:
papers = exa.searchandcontents(
query=topic,
type="neural",
numresults=maxpapers,
category="research paper",
highlights={
"numsentences": 5,
"highlightsperurl": 3
},
startpublisheddate="2025-01-01"
)
researchsummary = {
"topic": topic,
"papersfound": len(papers.results),
"papers": []
}
for paper in papers.results:
paperinfo = {
"title": paper.title,
"url": paper.url,
"publisheddate": paper.publisheddate,
"keyfindings": paper.highlights if paper.highlights else []
}
researchsummary["papers"].append(paperinfo)
return researchsummary
result = researchtopic("retrieval augmented generation optimization techniques")
print(json.dumps(result, indent=2))
Best Practices
1. Choose the Right Search Mode
- Use
neuralfor natural language and conceptual queries - Use
keywordfor searching specific technical terms, product names, or code - Use
autowhen unsure; Exa will select the best method
2. Optimize Result Count
Do not request too many results if not needed. For RAG, 3-5 results are usually sufficient. For deep research, 10-15 results are more appropriate.
3. Use Highlights for Efficiency
If you do not need the full page content, use highlights to save tokens and speed up responses.
results = exa.searchandcontents(
query="your query",
highlights={"num
sentences": 3, "highlightsperurl": 2}
)
4. Implement Caching
For frequently repeated queries, implement caching to reduce API calls:
from functools import lrucache
import hashlib
@lru
cache(maxsize=100)
def cachedsearch(query: str, numresults: int = 5):
return exa.searchandcontents(
query=query,
type="auto",
numresults=numresults,
text=True
)
5. Error Handling
from exapy import Exa
from exa
py.api import ExaError
exa = Exa(apikey="YOUREXAKEY")
try:
results = exa.search(
query="machine learning",
type="neural",
numresults=5
)
except ExaError as e:
print(f"Exa API error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
6. Use Filters for Quality
Combine domain and date filters to get high-quality results:
results = exa.searchandcontents(
query="transformer architecture explained",
type="neural",
numresults=5,
includedomains=["arxiv.org", "github.com", "huggingface.co"],
startpublisheddate="2025-01-01",
highlights={"num_sentences": 3}
)
Comparison with Alternatives
| Feature | Exa AI | Tavily | SerpAPI |
|---------|--------|--------|---------|
| Neural Search | Yes | Yes | No |
| Content Extraction | Yes | Yes | No |
| Similarity Search | Yes | No | No |
| Category Filter | Yes | No | No |
| Research Paper Filter | Yes | No | No |
| Highlight Extraction | Yes | Yes | No |
| LangChain Integration | Yes | Yes | Yes |
| Free Tier | Yes | Yes | Yes |
Conclusion
Exa AI provides a modern approach to web search that is purpose-built for AI applications. With neural search, content extraction, and similarity search, Exa is a strong choice for building RAG systems, research assistants, and AI agents that need access to up-to-date information from the web.
The key advantages of Exa over traditional search are its ability to understand query meaning semantically, extract page content directly, and provide sophisticated filtering by category and domain. Its integration with frameworks like LangChain makes it easy to incorporate into existing AI pipelines.
To get started, sign up at the Exa dashboard for a free API key, install the Python SDK, and begin experimenting with the various search modes and content extraction features available.