ExaSearchResults 통합

ExaSearchResults 통합

LangChain JavaScript로 ExaSearchResults 도구를 통합하는 방법을 알아봅니다.

Exa(구 Metaphor Search)는 LLM 사용을 위해 설계된 검색 엔진입니다. 자연어 쿼리로 인터넷에서 문서를 검색한 다음, 원하는 문서에서 정리된 HTML 콘텐츠를 가져올 수 있습니다.

키워드 기반 검색(Google)과 달리, Exa의 신경망 검색 기능은 쿼리를 의미적으로 이해하고 관련 문서를 반환할 수 있습니다. 예를 들어 "fascinating article about cats"를 검색하고 Google과 Exa의 검색 결과를 비교해 보겠습니다. Google은 "fascinating"이라는 키워드에 기반한 SEO 최적화 리스트(기사 나열형 콘텐츠)를 제공합니다. Exa는 그냥 잘 작동합니다.

이 페이지는 LangChain에서 ExaSearchResults를 사용하는 방법을 다룹니다.

개요

통합 상세

Class Package Serializable PY 지원 Version
ExaSearchResults @langchain/exa NPM - Version

설정

이 통합은 @langchain/exa 패키지에 포함되어 있습니다.

npm install @langchain/exa @langchain/core
yarn add @langchain/exa @langchain/core
pnpm add @langchain/exa @langchain/core

자격 증명

먼저 Exa API 키를 받아 환경 변수로 추가하세요. Exa에 가입하면 매월 1000회의 무료 검색을 사용할 수 있습니다.

export EXASEARCH_API_KEY="your-api-key"

또한 최고 수준의 관측성(observability)을 위해 LangSmith를 설정하는 것도 도움이 됩니다(필수는 아님):

process.env.LANGSMITH_TRACING="true"
process.env.LANGSMITH_API_KEY="your-api-key"

인스턴스화

여기서는 ExaSearchResults 도구의 인스턴스를 생성하는 방법을 보여줍니다:

import { ExaSearchResults } from "@langchain/exa"
import Exa from "exa-js";

// @lc-ts-ignore
const client = new Exa(process.env.EXASEARCH_API_KEY)

const tool = new ExaSearchResults({
  // @lc-ts-ignore
  client,
  searchArgs: {
    numResults: 2,
  }
})

호출

인자로 직접 호출

await tool.invoke("what is the weather in wailea?")
{"results":[{"score":0.16085544228553772,"title":"Hawaii Weather Forecast","id":"https://www.willyweather.com/hi/hawaii.html","url":"https://www.willyweather.com/hi/hawaii.html","publishedDate":"2023-01-01","author":"","text":"Get an account to remove ads    View More Real-Time Extremes   Nation State County      Hottest 78.8 °FFaleolo Intl / Apia, Samoa, HI    Coldest 51.6 °FBradshaw Army Air Field / Hawaii, HI    Windiest 12.7mphBradshaw Army Air Field / Hawaii, HI    Most Humid 100%Hilo, Hilo International Airport, HI    Least Humid 73.32%Kailua / Kona, Keahole Airport, HI    Highest Pressure 1030.5 hPaBradshaw Army Air Field / Hawaii, HI    Lowest Pressure 1008 hPaFaleolo Intl / Apia, Samoa, HI"},{"score":0.1591680943965912,"title":"The Hawaii Climate To Prepare For Your Maui Wedding","id":"https://mymauiwedding.weebly.com/blog6/the-hawaii-climate-to-prepare-for-your-maui-wedding","url":"https://mymauiwedding.weebly.com/blog6/the-hawaii-climate-to-prepare-for-your-maui-wedding","publishedDate":"2012-04-26","author":"","text":"Since the The hawaiian islands environment is very constant throughout the season with only slight heat range changes, you can travel there any season. While the moisture is very high, the continuous exotic sea breezes keep the circumstances very relaxed throughout the season. During the day you will be relaxed in a T-shirt or an Aloha clothing and a couple of shoes. Once the sun places you will probably want to wear a light coat since the circumstances can fall around ten levels. The protecting impact of the hills and the variations in climate at various levels make a variety of environment areas. The unique micro-climates are specific for the internal valleys, hill hills and seashores in The hawaiian islands. Located at the side of the exotic location and due to year-round heated sea exterior circumstances, which keep the overlying environment heated, The hawaiian islands has only two circumstances, both of them heated and one with a litt... [truncated]

ToolCall로 호출

도구를 모델이 생성한 ToolCall로 호출할 수도 있습니다. 이 경우 ToolMessage가 반환됩니다:

// This is usually generated by a model, but we'll create a tool call directly for demo purposes.
const modelGeneratedToolCall = {
  args: {
    input: "what is the weather in wailea"
  },
  id: "1",
  name: tool.name,
  type: "tool_call",
}
await tool.invoke(modelGeneratedToolCall)
ToolMessage {
  "content": "{\"results\":[{\"score\":0.12955062091350555,\"title\":\"Urban Dictionary: Waianae\",\"id\":\"https://www.urbandictionary.com/define.php?term=Waianae\",\"url\":\"https://www.urbandictionary.com/define.php?term=Waianae\",\"publishedDate\":\"2006-04-19\",\"author\":\"\",\"text\":\"Hot but good time for go beach ,in this part of Hawaii you HAVE to have respect ,with people and their stuff, but Some people like act dumb and stupid so that’s the only thing that make Waianae look bad , but foreal kine in this part of Hawaii we have respect and if we don’t get that respect you gon expect no respect back .   Get the Waianae mug.    Advertise here for $5/day    Located on the west end of Oahu. Waianae gets a bad reputation for being poor, dirty, scary, etc. Its hot and dry out west and the beaches are super nice. Makaha, Yokes, and Pray for Sex are some great beaches to name a few. Mostly locals and the majority of the homeless live out here. Even though its a little rough, the people have a lot of aloha who live out here. Most important thing here is to have respect for other people and their stuff.   Get the WAIANAE mug.    Advertise here for $5/day    When going too the island of Honolulu if you go to an amazing part for the island called Waianae, say ho sole u know where can find 1 top banggahh like get 1 Waianae special. Then say shoots boto  by   August 1, 2021   Get the Waianae special mug.\"},{\"score\":0.12563708424568176,\"title\":\"Mount Waialeale: One of the Wettest Spots on Earth | Hawaii.com\",\"id\":\"https://www.hawaii.com/trip-ideas/mount-waialeale-one-of-the-wettest-spots-on-earth/\",\"url\":\"https://www.hawaii.com/trip-ideas/mount-waialeale-one-of-the-wettest-spots-on-earth/\",\"publishedDate\":\"2022-01-18\",\"author\":\"Matthew Jones\",\"text\":\"Wai’ale’ale, Kauai without much cloud cover.  Photo:  WiseTim .   \\nMount Wai‘ale‘ale on the gorgeous island of Kaua‘i is often referred to as the wettest spot on earth. While the more than 5,000-... [truncated]
  "name": "exa_search_results_json",
  "additional_kwargs": {},
  "response_metadata": {},
  "tool_call_id": "1"
}

체이닝

도구를 도구 호출 모델에 먼저 바인딩한 다음 호출하는 방식으로 체인에서 사용할 수 있습니다:

// @lc-docs-hide-cell

import { ChatOpenAI } from "@langchain/openai"

const llm = new ChatOpenAI({
  model: "gpt-5.4-mini",
})
import { ChatPromptTemplate } from "@langchain/core/prompts"
import { RunnableConfig } from "@langchain/core/runnables"
import { AIMessage } from "@langchain/core/messages"

const prompt = ChatPromptTemplate.fromMessages(
  [
    ["system", "You are a helpful assistant."],
    ["human", "{user_input}"],
    ["placeholder", "{messages}"],
  ]
)

// specifying tool_choice will force the model to call this tool.
const llmWithTools = llm.bindTools([tool], {
  tool_choice: tool.name
})

const llmChain = prompt.pipe(llmWithTools);

const toolChain = async (userInput: string, config?: RunnableConfig): Promise<AIMessage> => {
  const input_ = { user_input: userInput };
  const aiMsg = await llmChain.invoke(input_, config);
  const toolMsgs = await tool.batch(aiMsg.tool_calls, config);
  return llmChain.invoke({ ...input_, messages: [aiMsg, ...toolMsgs] }, config);
};

const toolChainResult = await toolChain("What is Anthropic's estimated revenue for 2024?");
const { tool_calls, content } = toolChainResult;

console.log("AIMessage", JSON.stringify({
  tool_calls,
  content
}, null, 2))
AIMessage {
  "tool_calls": [
    {
      "name": "exa_search_results_json",
      "args": {
        "input": "Anthropic revenue 2024 projections"
      },
      "type": "tool_call",
      "id": "call_cgC1G9vjXIjHub0TkVfxiDcr"
    }
  ],
  "content": ""
}

에이전트와 함께 사용

ExaRetrievercreateRetrieverTool을 사용하는 LangChain 도구를 만들 수 있습니다. 이러한 도구를 사용하여 어떤 주제에 대해서도 질문에 답할 수 있는 간단한 검색 에이전트를 구성할 수 있습니다.

에이전트를 만들기 위해 LangGraph를 사용합니다. @langchain/langgraph가 설치되어 있는지 확인하세요:

npm install @langchain/langgraph
yarn add @langchain/langgraph
pnpm add @langchain/langgraph

그런 다음 에이전트와 함께 사용할 LLM을 정의합니다:

// @lc-docs-hide-cell
import { ChatOpenAI } from "@langchain/openai";

const llmForAgent = new ChatOpenAI({
  model: "gpt-5.5",
  temperature: 0
})
import Exa from "exa-js";
import { createRetrieverTool } from "@langchain/classic/tools/retriever";
import { ExaRetriever } from "@langchain/exa";
import { createAgent } from "@langchain/classic";

// @lc-ts-ignore
const agentClient = new Exa(process.env.EXASEARCH_API_KEY);

const exaRetrieverForAgent = new ExaRetriever({
  // @lc-ts-ignore
  client: agentClient,
  searchArgs: {
    numResults: 2,
  },
});

// Convert the ExaRetriever into a tool
const searchToolForAgent = createRetrieverTool(exaRetrieverForAgent, {
  name: "search",
  description: "Get the contents of a webpage given a string search query.",
});

const toolsForAgent = [searchToolForAgent];

const agentExecutor = createAgent({
  llm: llmForAgent,
  tools: toolsForAgent,
})
const exampleQuery = "Summarize for me a fascinating article about cats."

const events = await agentExecutor.stream(
  { messages: [
    [
      "system",
      `You are a web researcher who answers user questions by looking up information on the internet and retrieving contents of helpful documents. Cite your sources.`,
    ],
    ["human", exampleQuery],
  ] },
  { streamMode: "values", }
)

for await (const event of events) {
  const lastMsg = event.messages[event.messages.length - 1];
  if (lastMsg.tool_calls?.length) {
    console.dir(lastMsg.tool_calls, { depth: null });
  } else if (lastMsg.content) {
    console.log(lastMsg.content);
  }
}
[
  {
    name: 'search',
    args: { query: 'fascinating article about cats' },
    type: 'tool_call',
    id: 'call_EcA0tmWsyNktO7HAsGQnqLVt'
  }
]
No one seems to think brushing kitty's teeth is worth the hassle.      Tyler Comrie / The Atlantic; Getty      On the list of perfect pet parents, Mikel Delgado, a professional feline-behavior consultant, probably ranks high. The Ph.D. expert in animal cognition spends half an hour each evening playing with her three torbie cats, Ruby, Coriander, and Professor Scribbles. She’s trained them to take pills in gelatin capsules, just in case they eventually need meds. She even commissioned a screened-in backyard catio so that the girls can safely venture outside. Delgado would do anything for her cats—well, almost anything. “Guilty as charged,” Delgado told me. “I do not brush my cats’ teeth.” To be fair, most cat owners don’t—probably because they’re well aware that it’s weird, if not downright terrifying, to stick one’s fingers inside an ornery cat’s mouth. Reliable stats are scarce, but informal surveys suggest that less than 5 percent of owners give their cats the dental scrub-a-dub-dub—an estimate that the vets I spoke with endorse. “I’m always very shocked if someone says they brush their cat’s teeth,” says Anson Tsugawa, a veterinary dentist in California. When Steve Valeika, a vet in North Carolina, suggests the practice to his clients, many of them “look at me like I’ve totally lost it,” he told me. (This is where I out myself as one of the loons: My cats, Calvin and Hobbes, get their teeth brushed thrice weekly.) There certainly is an element of absurdity to all of this. Lions, after all, aren’t skulking the savannas for Oral-Bs. But our pets don’t share the diets and lifestyles of their wild counterparts, and their teeth are quite susceptible to the buildup of bacteria that can eventually invade the gums to trigger prolonged, painful disease. Studies suggest that most domestic cats older than four end up developing some sort of gum affliction; several experts told me that the rates of periodontal disease in household felines can exceed 80 percent. Left untreat... [truncated]

Last night I watched the Netflix documentary,  Inside the Mind of a Cat . It was a good show that demonstrated cats are thoughtful creatures and amazing predators and that they may have intellectual capacities on par with dogs.
In addition to learning about the research, I watched the show from my perspective as a mental behaviorist. A mental behavioral position is one that bridges and resolves the old divide in psychology between the behaviorists (who say that the mind is not a scientific construct and thus they just study behavior) and the mentalists (who say they study overt behaviors and then infer mental processes that are presumed to cause the behaviors).
The mental behavioral view says that animals like cats are “minded” creatures, and that they exhibit mental behaviors. To see this, imagine three cats in a tree; one is dead, one is anesthetized, and one is alive and well. Now drop the cats. The mental behaviorist says all three cats behave, but they exhibit different kinds of behaviors as they fall. The first cat falls through the air and lands on the ground. Its behavior is “physical” in that it is caused by the laws and forces of the material world as mapped by the physical sciences. The second cat also falls much like the first. However, if we were to peer inside the cat, we would see that its physiology is very active in maintaining its complex organization. The behaviors of the cat’s cells and organ systems that keep it alive are living behaviors studied by the biological sciences.
The third cat rotates, lands on its feet, and takes off. This is a different kind of behavior that cannot be well-described as either physical or biological. Rather, the proper description is mental. Mental behavior is a particular kind of functional awareness and responsivity that animals exhibit. Such behaviors are actions mediated by the brain and nervous system and the complex active body of the cat. More specifically, mental behaviors are a pattern of activity that emerges as function of a complex adaptive, sensory-motor looping system.
Just as we consider entities like cells that exhibit living behaviors to be alive, we should consider creatures like cats that exhibit mental behaviors to be “minded.” The mental behaviorist argues that mindedness is one of the most important concepts that both science and most modern people are blind to. I say “modern people” because, historically, most cultures have seen clearly that animals behave very differently when compared to plants or bacteria, and most cultures have had some kind of category for specifying this difference. For example, Aristotle divided the "soul" into the vegetative, animal, and human layers. In addition, the Great Chain of Being differentiated animals from the rest of the living world. However, our modern scientific system does not have a word for the way animals are in the world that makes them so different. We just call it "animal behavior." And this gap is a major blind spot in our grammar for understanding the world around us.
Returning to the documentary, if we did not really look inside "the mind" of cats, what did the documentary actually show? It showed the mental behavioral investment patterns of cats. That is, it showed how cats demonstrate functional awareness and responsivity to various kinds of situations and stimuli. For example, it showed they clearly recognize and respond to their names, it showed they prefer their owners to strangers, and it showed they really do have a unique skill set in their capacity to land on their feet. In other words, it showed cats are minded creatures that exhibit complex adaptive patterns of mental behavior.
Although it becomes obvious when you know how to see the world this way (i.e., when I go for a walk in the woods, the mindedness of the squirrels, birds, and bees is as blatantly apparent to me as the living behaviors of the trees and mushrooms), it nevertheless takes practice to learn how to see mindedness in the world. However, we need to make the effort because failing to see mindedness in the world results in much blindness.
I found a fascinating article from The Atlantic that delves into the often-overlooked aspect of feline care: brushing cats' teeth. Despite being a crucial part of maintaining a cat's health, very few cat owners actually brush their pets' teeth. The article highlights the challenges and absurdities of this task, noting that less than 5% of cat owners engage in this practice.

Veterinary experts emphasize the importance of dental hygiene for cats, as most domestic cats over the age of four develop some form of gum disease, which can lead to severe health issues if left untreated. The article discusses various tools and techniques, such as poultry-flavored toothpaste and cat-sized toothbrushes, that can make the process easier. However, it also acknowledges the difficulties and resistance many cats show towards toothbrushing.

Interestingly, the article also touches on the broader context of pet care, noting how the expectations and practices around pet maintenance have evolved over time. It suggests that while brushing a cat's teeth is ideal, alternative methods like dental treats and specialized kibble can also be effective.

For more details, you can read the [full Atlantic article](https://www.theatlantic.com/health/archive/2023/10/cat-dental-care-toothbrushing/675123/).

관련 자료

API 참고 자료

ExaSearchResults의 모든 기능과 구성에 대한 자세한 문서는 API reference에서 확인할 수 있습니다.

출처: 문서

더 알아보기 (Learn more)