Skip to main content
Exa는 LLM에서 사용하도록 완전히 설계된 검색 엔진입니다. 자연어 쿼리를 사용하여 인터넷에서 문서를 검색한 다음, 원하는 문서에서 정제된 HTML 콘텐츠를 검색할 수 있습니다. 키워드 기반 검색(Google)과 달리, Exa의 신경망 검색 기능은 쿼리를 의미론적으로 이해하고 관련 문서를 반환할 수 있습니다. 예를 들어, "fascinating article about cats"를 검색하고 GoogleExa의 검색 결과를 비교할 수 있습니다. Google은 “fascinating”이라는 키워드를 기반으로 SEO에 최적화된 리스트클 형식의 결과를 제공합니다. 반면 Exa는 그냥 잘 작동합니다. 이 노트북은 LangChain에서 Exa Search를 사용하는 방법을 안내합니다.

설정

설치

LangChain Exa 통합 패키지를 설치하세요:
pip install -qU langchain-exa

# and some deps for this notebook
pip install -qU langchain langchain-openai langchain-community

자격 증명

이 통합을 사용하려면 Exa API 키가 필요합니다. 여기에서 가입하여 $10 무료 크레딧을 받으세요(첫 검색 수행과 같은 특정 작업을 완료하면 추가 크레딧을 받을 수 있습니다).
import getpass
import os

if not os.environ.get("EXA_API_KEY"):
    os.environ["EXA_API_KEY"] = getpass.getpass("Exa API key:\n")

ExaSearchResults 도구 사용하기

ExaSearchResults는 LangChain 에이전트와 함께 사용하여 Exa 검색을 수행할 수 있는 도구입니다. 검색 작업을 위한 보다 구조화된 인터페이스를 제공합니다:
from langchain_exa import ExaSearchResults

# Initialize the ExaSearchResults tool
search_tool = ExaSearchResults(exa_api_key=os.environ["EXA_API_KEY"])

# Perform a search query
search_results = search_tool._run(
    query="When was the last time the New York Knicks won the NBA Championship?",
    num_results=5,
    text_contents_options=True,
    highlights=True,
)

print("Search Results:", search_results)

ExaSearchResults의 고급 기능

검색 유형 제어, 라이브 크롤링, 콘텐츠 필터링과 같은 고급 검색 옵션을 사용할 수 있습니다:
# Perform a search query with advanced options
search_results = search_tool._run(
    query="Latest AI research papers",
    num_results=10,  # Number of results (1-100)
    type="auto",  # Can be "neural", "keyword", or "auto"
    livecrawl="always",  # Can be "always", "fallback", or "never"
    text_contents_options={"max_characters": 2000},  # Limit text length
    summary={"query": "generate one liner"},  # Custom summary prompt
)

print("Advanced Search Results:")
print(search_results)

ExaFindSimilarResults 도구 사용하기

ExaFindSimilarResults를 사용하면 주어진 URL과 유사한 웹페이지를 찾을 수 있습니다. 이는 관련 콘텐츠를 찾거나 경쟁사 분석에 유용합니다:
from langchain_exa import ExaFindSimilarResults

# Initialize the ExaFindSimilarResults tool
find_similar_tool = ExaFindSimilarResults(exa_api_key=os.environ["EXA_API_KEY"])

# Find similar results based on a URL
similar_results = find_similar_tool._run(
    url="http://espn.com", num_results=5, text_contents_options=True, highlights=True
)

print("Similar Results:", similar_results)

에이전트 내에서 사용하기

ExaSearchResults와 ExaFindSimilarResults 도구를 LangGraph 에이전트와 함께 사용할 수 있습니다. 이를 통해 에이전트는 사용자의 쿼리를 기반으로 정보를 동적으로 검색하고 유사한 콘텐츠를 찾을 수 있습니다. 먼저 언어 모델을 설정해 보겠습니다. OpenAI API 키를 제공해야 합니다:
import getpass

if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API key:\n")
langgraph를 설치해야 합니다:
pip install -qU langgraph
from langchain.chat_models import init_chat_model
from langchain_exa import ExaFindSimilarResults, ExaSearchResults
from langchain.agents import create_agent


# Initialize the language model
model = init_chat_model(model="gpt-4o", model_provider="openai", temperature=0)

# Initialize Exa Tools
exa_search = ExaSearchResults(
    exa_api_key=os.environ["EXA_API_KEY"],
    max_results=5,
)

exa_find_similar = ExaFindSimilarResults(
    exa_api_key=os.environ["EXA_API_KEY"],
    max_results=5,
)

# Create agent with both tools
agent = create_agent(model, [exa_search, exa_find_similar])

# Example 1: Basic search
user_input = "What are the latest developments in quantum computing?"

for step in agent.stream(
    {"messages": user_input},
    stream_mode="values",
):
    step["messages"][-1].pretty_print()

ExaSearchRetriever 사용하기

ExaSearchRetriever는 Exa Search를 사용하여 관련 문서를 검색하는 retriever입니다.
TextContentsOptionsmax_characters 매개변수는 이전에 max_length라고 불렸으며 현재는 사용되지 않습니다. 대신 max_characters를 사용하세요.

기본 사용법

다음은 ExaSearchRetriever를 사용하는 간단한 예제입니다:
from langchain_exa import ExaSearchRetriever

# Create a new instance of the ExaSearchRetriever
exa = ExaSearchRetriever(exa_api_key=os.environ["EXA_API_KEY"])

# Search for a query and save the results
results = exa.invoke("What is the capital of France?")

# Print the results
print(results)

고급 기능

결과 수 제어, 검색 유형, 라이브 크롤링, 요약 및 텍스트 콘텐츠 옵션과 같은 고급 기능을 사용할 수 있습니다:
from langchain_exa import ExaSearchRetriever

# Create a new instance with advanced options
exa = ExaSearchRetriever(
    exa_api_key=os.environ["EXA_API_KEY"],
    k=20,  # Number of results (1-100)
    type="auto",  # Can be "neural", "keyword", or "auto"
    livecrawl="always",  # Can be "always", "fallback", or "never"
    text_contents_options={"max_characters": 3000},  # Limit text length
    # Custom prompt for an LLM generated summary of page content
    summary={"query": "generate one line summary in simple words."},
)

# Search with advanced options
results = exa.invoke("Latest developments in quantum computing")
print(f"Found {len(results)} results")
for result in results[:3]:  # Print first 3 results
    print(f"Title: {result.metadata.get('title', 'N/A')}")
    print(f"URL: {result.metadata.get('url', 'N/A')}")
    print(f"Summary: {result.metadata.get('summary', 'N/A')}")
    print("-" * 80)

API 레퍼런스

모든 Exa API 기능 및 구성에 대한 자세한 문서는 Exa API 문서를 참조하세요.
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I