Skip to main content
Tavily의 Search API는 AI 에이전트(LLM)를 위해 특별히 제작된 검색 엔진으로, 실시간으로 정확하고 사실적인 결과를 빠르게 제공합니다.

개요

통합 세부 정보

ClassPackageSerializableJS supportVersion
TavilySearchlangchain-tavilyPyPI - Version

도구 기능

Returns artifactNative asyncReturn dataPricing
title, URL, content snippet, raw_content, answer, images월 1,000회 무료 검색

설정

이 통합은 langchain-tavily 패키지에 포함되어 있습니다.
pip install -qU langchain-tavily

자격 증명

Tavily API 키도 설정해야 합니다. 이 사이트를 방문하여 계정을 생성하면 API 키를 받을 수 있습니다.
import getpass
import os

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

인스턴스화

여기서는 Tavily 검색 도구의 인스턴스를 생성하는 방법을 보여드립니다. 이 도구는 검색을 사용자 지정할 수 있는 다양한 매개변수를 허용합니다. 인스턴스화 후 간단한 쿼리로 도구를 호출합니다. 이 도구를 사용하면 Tavily의 Search API 엔드포인트를 통해 검색 쿼리를 완료할 수 있습니다. 인스턴스화 도구는 인스턴스화 시 다양한 매개변수를 허용합니다:
  • max_results (선택 사항, int): 반환할 최대 검색 결과 수입니다. 기본값은 5입니다.
  • topic (선택 사항, str): 검색 카테고리입니다. “general”, “news”, “finance” 중 하나를 선택할 수 있습니다. 기본값은 “general”입니다.
  • include_answer (선택 사항, bool): 결과에 원본 쿼리에 대한 답변을 포함할지 여부입니다. 기본값은 False입니다.
  • include_raw_content (선택 사항, bool): 각 검색 결과의 정리되고 파싱된 HTML을 포함할지 여부입니다. 기본값은 False입니다.
  • include_images (선택 사항, bool): 응답에 쿼리 관련 이미지 목록을 포함할지 여부입니다. 기본값은 False입니다.
  • include_image_descriptions (선택 사항, bool): 각 이미지에 대한 설명 텍스트를 포함할지 여부입니다. 기본값은 False입니다.
  • search_depth (선택 사항, str): 검색 깊이로, “basic” 또는 “advanced” 중 하나입니다. 기본값은 “basic”입니다.
  • time_range (선택 사항, str): 현재 날짜로부터 결과를 필터링할 시간 범위로, “day”, “week”, “month”, “year” 중 하나입니다. 기본값은 None입니다.
  • include_domains (선택 사항, List[str]): 특별히 포함할 도메인 목록입니다. 기본값은 None입니다.
  • exclude_domains (선택 사항, List[str]): 특별히 제외할 도메인 목록입니다. 기본값은 None입니다.
사용 가능한 매개변수에 대한 포괄적인 개요는 Tavily Search API 문서를 참조하세요.
from langchain_tavily import TavilySearch

tool = TavilySearch(
    max_results=5,
    topic="general",
    # include_answer=False,
    # include_raw_content=False,
    # include_images=False,
    # include_image_descriptions=False,
    # search_depth="basic",
    # time_range="day",
    # include_domains=None,
    # exclude_domains=None
)

호출

인수로 직접 호출

Tavily 검색 도구는 호출 시 다음 인수를 허용합니다:
  • query (필수): 자연어 검색 쿼리
  • 다음 인수들도 호출 시 설정할 수 있습니다: include_images, search_depth , time_range, include_domains, exclude_domains, include_images
  • 신뢰성과 성능상의 이유로, 응답 크기에 영향을 주는 특정 매개변수는 호출 시 수정할 수 없습니다: include_answerinclude_raw_content. 이러한 제한은 예상치 못한 컨텍스트 윈도우 문제를 방지하고 일관된 결과를 보장합니다.
참고: 선택적 인수는 에이전트가 동적으로 설정할 수 있습니다. 인스턴스화 시 인수를 설정한 후 다른 값으로 도구를 호출하면, 도구는 호출 시 전달한 값을 사용합니다.
tool.invoke({"query": "What happened at the last wimbledon"})

ToolCall로 호출

모델에서 생성된 ToolCall로 도구를 호출할 수도 있으며, 이 경우 ToolMessage가 반환됩니다:
# This is usually generated by a model, but we'll create a tool call directly for demo purposes.
model_generated_tool_call = {
    "args": {"query": "euro 2024 host nation"},
    "id": "1",
    "name": "tavily",
    "type": "tool_call",
}
tool_msg = tool.invoke(model_generated_tool_call)

# The content is a JSON string of results
print(tool_msg.content[:400])
{"query": "euro 2024 host nation", "follow_up_questions": null, "answer": null, "images": [], "results": [{"title": "UEFA Euro 2024 - Wikipedia", "url": "https://en.wikipedia.org/wiki/UEFA_Euro_2024", "content": "Tournament details Host country Germany Dates 14 June – 14 July Teams 24 Venue(s) 10 (in 10 host cities) Final positions Champions Spain (4th title) Runners-up England Tournament statisti

에이전트 내에서 사용

도구를 에이전트에 바인딩하여 에이전트 실행기와 함께 직접 사용할 수 있습니다. 이를 통해 에이전트는 Tavily 검색 도구에 사용 가능한 인수를 동적으로 설정할 수 있습니다. 아래 예시에서 에이전트에게 “What nation hosted the Euro 2024? Include only wikipedia sources.”를 물어보면, 에이전트는 인수를 동적으로 설정하고 Tavily 검색 도구를 호출합니다: tavily_search{'query': 'Euro 2024 host nation', 'include_domains': ['wikipedia.org']로 호출합니다.
if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = getpass.getpass("OPENAI_API_KEY:\n")
# | output: false
# | echo: false

# !pip install -qU langchain langchain-openai
from langchain.chat_models import init_chat_model

model = init_chat_model(model="gpt-4o", model_provider="openai", temperature=0)
langgraph를 설치해야 합니다:
pip install -qU langgraph
from langchain_tavily import TavilySearch
from langchain.agents import create_agent


# Initialize Tavily Search Tool
tavily_search_tool = TavilySearch(
    max_results=5,
    topic="general",
)

agent = create_agent(model, [tavily_search_tool])

user_input = "What nation hosted the Euro 2024? Include only wikipedia sources."

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

What nation hosted the Euro 2024? Include only wikipedia sources.
================================== Ai Message ==================================
Tool Calls:
  tavily_search (call_yxmR4K2uadsQ8LKoyi8JyoLD)
 Call ID: call_yxmR4K2uadsQ8LKoyi8JyoLD
  Args:
    query: Euro 2024 host nation
    include_domains: ['wikipedia.org']
================================= Tool Message =================================
Name: tavily_search

{"query": "Euro 2024 host nation", "follow_up_questions": null, "answer": null, "images": [], "results": [{"title": "UEFA Euro 2024 - Wikipedia", "url": "https://en.wikipedia.org/wiki/UEFA_Euro_2024", "content": "Tournament details Host country Germany Dates 14 June – 14 July Teams 24 Venue(s) 10 (in 10 host cities) Final positions Champions Spain (4th title) Runners-up England Tournament statistics Matches played 51 Goals scored 117 (2.29 per match) Attendance 2,681,288 (52,574 per match) Top scorer(s) Harry Kane Georges Mikautadze Jamal Musiala Cody Gakpo Ivan Schranz Dani Olmo (3 goals each) Best player(s) Rodri Best young player Lamine Yamal ← 2020 2028 → The 2024 UEFA European Football Championship, commonly referred to as UEFA Euro 2024 (stylised as UEFA EURO 2024) or simply Euro 2024, was the 17th UEFA European Championship, the quadrennial international football championship organised by UEFA for the European men's national teams of their member associations. Germany hosted the tournament, which took place from 14 June to 14 July 2024. The tournament involved 24 teams, with Georgia making their European Championship debut. [4] Host nation Germany were eliminated by Spain in the quarter-finals; Spain went on to win the tournament for a record fourth time after defeating England 2–1 in the final.", "score": 0.9104262, "raw_content": null}, {"title": "UEFA Euro 2024 - Simple English Wikipedia, the free encyclopedia", "url": "https://simple.wikipedia.org/wiki/UEFA_Euro_2024", "content": "The 2024 UEFA European Football Championship, also known as UEFA Euro 2024 or simply Euro 2024, was the 17th edition of the UEFA European Championship. Germany was hosting the tournament. ... The UEFA Executive Committee voted for the host in a secret ballot, with only a simple majority (more than half of the valid votes) required to determine", "score": 0.81418616, "raw_content": null}, {"title": "Championnat d'Europe de football 2024 — Wikipédia", "url": "https://fr.wikipedia.org/wiki/Championnat_d'Europe_de_football_2024", "content": "Le Championnat d'Europe de l'UEFA de football 2024 est la 17 e édition du Championnat d'Europe de football, communément abrégé en Euro 2024, compétition organisée par l'UEFA et rassemblant les meilleures équipes nationales masculines européennes. L'Allemagne est désignée pays organisateur de la compétition le 27 septembre 2018. C'est la troisième fois que des matches du Championnat", "score": 0.8055255, "raw_content": null}, {"title": "UEFA Euro 2024 bids - Wikipedia", "url": "https://en.wikipedia.org/wiki/UEFA_Euro_2024_bids", "content": "The bidding process of UEFA Euro 2024 ended on 27 September 2018 in Nyon, Switzerland, when Germany was announced to be the host. [1] Two bids came before the deadline, 3 March 2017, which were Germany and Turkey as single bids. ... Press agencies revealed on 24 October 2013, that the European football governing body UEFA would have decided on", "score": 0.7882741, "raw_content": null}, {"title": "2024 UEFA European Under-19 Championship - Wikipedia", "url": "https://en.wikipedia.org/wiki/2024_UEFA_European_Under-19_Championship", "content": "The 2024 UEFA European Under-19 Championship (also known as UEFA Under-19 Euro 2024) was the 21st edition of the UEFA European Under-19 Championship (71st edition if the Under-18 and Junior eras are included), the annual international youth football championship organised by UEFA for the men's under-19 national teams of Europe. Northern Ireland hosted the tournament from 15 to 28 July 2024.", "score": 0.7783298, "raw_content": null}], "response_time": 1.67}
================================== Ai Message ==================================

The nation that hosted Euro 2024 was Germany. You can find more information on the [Wikipedia page for UEFA Euro 2024](https://en.wikipedia.org/wiki/UEFA_Euro_2024).

API 레퍼런스

모든 Tavily Search API 기능과 구성에 대한 자세한 문서는 API 레퍼런스를 참조하세요: docs.tavily.com/documentation/api-reference/endpoint/search
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I