跳至主要内容

ExaRetriever

概述

Exa 是一个搜索引擎,它根据一些输入查询从网络检索相关内容。

本指南将帮助您开始使用 Exa 检索器。有关所有 ExaRetriever 功能和配置的详细文档,请转到 API 参考

集成详细信息

检索器来源
ExaRetriever网络上的信息。@langchain/exa

设置

您需要将您的 API 密钥设置为环境变量。

Exa 类在搜索您的 API 密钥时默认使用 EXASEARCH_API_KEY

process.env.EXASEARCH_API_KEY = "<YOUR API KEY>";

如果您想从单个查询中获取自动跟踪,您也可以通过取消注释以下内容来设置您的 LangSmith API 密钥

// process.env.LANGSMITH_API_KEY = "<YOUR API KEY HERE>";
// process.env.LANGSMITH_TRACING = "true";

安装

此检索器位于 @langchain/exa 包中

yarn add @langchain/exa

实例化

现在我们可以实例化我们的检索器

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

const retriever = new ExaRetriever({
client: new Exa(
process.env.EXASEARCH_API_KEY // default API key
),
searchArgs: {
numResults: 2,
},
});

使用

const query =
"What did the speaker say about Justice Breyer in the 2022 State of the Union?";

await retriever.invoke(query);
[
Document {
pageContent: 'President Biden’s State of the Union Address\n' +
'Madam Speaker, Madam Vice President, and our First Lady and Second Gentleman, members of Congress and the Cabinet, Justices of the Supreme Court, my fellow Americans: Last year, COVID-19 kept us apart. This year, we’re finally together again.\n' +
'Tonight — tonight we meet as Democrats, Republicans, and independents, but, most importantly, as Americans with a duty to one another, to America, to the American people, and to the Constitution, and an unwavering resolve that freedom will always triumph over tyranny.\n' +
'Six — thank you. Six days ago, Russia’s Vladimir Putin sought to shake the very foundations of the free world, thinking he could make it bend to his menacing ways. But he badly miscalculated. He thought he could roll into Ukraine and the world would roll over. Instead, he met with a wall of strength he never anticipated or imagined. He met the Ukrainian people.\n' +
'From President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination literally inspires the world. Groups of citizens blocking tanks with their bodies. Everyone from students to retirees, to teachers turned soldiers defending their homeland.\n' +
'And in this struggle — President Zelenskyy said in his speech to the European Parliament, “Light will win over darkness.”\n' +
'The Ukrainian Ambassador to the United States is here tonight sitting with the First Lady. Let each of us, if you’re able to stand, stand and send an unmistakable signal to the world and Ukraine. Thank you. Thank you, thank you, thank you.\n' +
'She’s bright, she’s strong, and she’s resolved.\n' +
'Yes. We, the United States of America, stand with the Ukrainian people.\n' +
'Throughout our history, we’ve learned this lesson: When dictators do not pay a price for their aggression, they cause more chaos; they keep moving; and the costs, the threats to the America — and America, to the world keeps rising.\n' +
'That’s why the NATO Alliance was created: to secure peace and stability in Europe after World War Two.\n' +
'The United States is a member, along with 29 other nations. It matters. American diplomacy matters. American resolve matters.\n' +
'Putin’s latest attack on Ukraine was premeditated and totally unprovoked. He rejected repeated efforts at diplomacy.\n' +
'He thought the West and NATO wouldn’t respond. He thought he could divide us at home, in this chamber, in this nation. He thought he could divide us in Europe as well.\n' +
'But Putin was wrong. We are ready. We are united. And that’s what we did: We stayed united.\n' +
'We prepared extensively and carefully. We spent months building coalitions of other freedom-loving nations in Europe and the Americas to — from America to the Asian and African continents to confront Putin.\n' +
'Like many of you, I spent countless hours unifying our European Allies.\n' +
'We shared with the world, in advance, what we knew Putin was planning and precisely how he would try to falsely and justify his aggression.\n' +
'We countered Russia’s lies with the truth. And now — now that he’s acted, the free world is holding him accountable, along with 27 members of the European Union — including France, Germany, Italy — as well as countries like the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others. Even Switzerland are inflicting pain on Russia and supporting the people of Ukraine.\n' +
'Putin is now isolated from the world more than he has ever been.\n' +
'Together. Together. Together, along with our Allies, we are right now enforcing powerful economic sanctions. We’re cutting off Russia’s largest banks from the international financial system; preventing Russia’s Central Bank from defending the Russian ruble, making Putin’s $630 billion war fund worthless. We’re choking Russia’s access, we’re choking Russia’s access to technology that will sap its economic strength and weaken its military for years to come.\n' +
'Tonight, I say to the Russian oligarchs and the corrupt leaders who’ve bilked billions of dollars off this violent regime: No more.\n' +
'The United States — I mean it. The United States Department of Justice is assembling a dedicated task force to go after the crimes of the Russian oligarchs.\n' +
'We’re joining with European Allies to find and seize their yachts, their luxury apartments, their private jets. We’re coming for your ill-begotten gains.\n' +
'And, tonight, I’m announcing that we will join our Allies in closing off American air space to all Russian flights, further isolating Russia and adding an additional squeeze on their economy.\n' +
'He has no idea what’s coming.\n' +
'The ruble has already lost 30 percent of its value, the Russian stock market has lost 40 percent of its value, and trading remains suspended.\n' +
'The Russian economy is reeling, and Putin alone is the one to blame.\n' +
'Together with our Allies, we’re providing support to the Ukrainians in their fight for freedom: military assistance, economic assistance, humanitarian assistance. We’re giving more than a billion dollars in direct assistance to Ukraine. And we’ll continue to aid the Ukrainian people as they defend their country and help ease their suffering.\n' +
'But let me be clear: Our forces are not engaged and will not engage in the conflict with Russian forces in Ukraine. Our forces are not going to Europe to fight in Ukraine but to defend our NATO Allies in the event that Putin decides to keep moving west.\n' +
'For that purpose, we have mobilized American ground forces, air squadrons, ship deployments to protect NATO countries, including Poland, Romania, Latvia, Lithuania, and Estonia.\n' +
'And as I’ve made crystal clear, the United States and our Allies will defend every inch of territory that is NATO territory with the full force of our collective power — every single inch.\n' +
'And we’re clear-eyed. The Ukrainians are fighting back with pure courage. But the next few days, weeks, and months will be hard on them.\n' +
'Putin has unleashed violence and chaos. But while he may make gains on the battlefield, he will pay a continuing high price over the long run.\n' +
'And a pound of Ukrainian people — the proud, proud people — pound for pound, ready to fight with every inch of (inaudible) they have. They’ve known 30 years of independence — have repeatedly shown that they will not tolerate anyone who tries to take their country backwards.\n' +
'To all Americans, I’ll be honest with you, as I’ve always promised I would be. A Russian dictator infa- — invading a foreign country has costs around the world. And I’m taking robust action to make sure the pain of our sanctions is targeted at the Russian economy and that we use every tool at our disposal to protect American businesses and consumers.\n' +
'Tonight, I can announce the United States has worked with 30 other countries to release 60 million barrels of oil from reserves around the world. America will lead that effort, releasing 30 million barrels of our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, united with our Allies.\n' +
'These steps will help blunt gas prices here at home. But I know news about what’s happening can seem alarming to all Americans. But I want you to know: We’re going to be okay. We’re going to be okay.\n' +
'When the history of this era is written, Putin’s war on Ukraine will have left Russia weaker and the rest of the world stronger.\n' +
'While it shouldn’t and while it shouldn’t have taken something so terrible for people around the world to see what’s at stake, now everyone sees it clearly.\n' +
'We see the unity among leaders of nations, a more unified Europe, a more unified West.\n' +
'We see unity among the people who are gathering in cities in large crowds around the world, even in Russia, to demonstrate their support for the people of Ukraine.\n' +
'In the battle between democracy and autocracies, democracies are rising to the moment and the world is clearly choosing the side of peace and security.\n' +
'This is the real test, and it’s going to take time. So, let us continue to draw inspiration from the iron will of the Ukrainian people.\n' +
'To our fellow Ukrainian Americans who forged a deep bond that connects our two nations: We stand with you. We stand with you.\n' +
'Putin may circle Kyiv with tanks, but he’ll never gain the hearts and souls of Ukrainian people. He’ll never — he’ll never extinguish their love of freedom. And he will never, never weaken the resolve of the free world.\n' +
'We meet tonight in an America that has lived through two of the hardest years this nation has ever faced. The pandemic has been punishing. And so many families are living paycheck to paycheck, struggling to keep up with the rising cost of food, gas, housing, and so much more.\n' +
'I understand, like many of you did. My dad had to leave his home in Scranton, Pennsylvania, to find work. So, like many of you, I grew up in a family when the price of food went up, it was felt throughout the family; it had an impact.\n' +
'That’s why one of the first things I did as President was fight to pass the American Rescue Plan, because people were hurting. We needed to act and we did.\n' +
'American Rescue Plan \n' +
'Few pieces of legislation have done more at a critical moment in our history to lift us out of a crisis. It fueled our efforts to vaccinate the nation and combat COVID-19. It delivered immediate economic relief to tens of millions of Americans. It helped put food on the table. Remember those long lines of cars waiting for hours just to get a box of food put in their trunk? It cut the cost of healthcare insurance. And as my dad used to say, it gave the people “just a little bit of breathing room.”\n' +
'And unlike the $2 trillion tax cut passed in the previous administration that benefitted the top 1 percent of Americans, the American Rescue Plan helped working people and left no one behind. And, folks — and it worked. It worked.\n' +
'It worked and created jobs — lots of jobs. In fact, our economy created over 6.5 million new jobs just last year, more jobs in one year than ever before in the history of the United States of America.\n' +
'Economic Progress Report \n' +
'The economy grew at a rate of 5.7 last year — the strongest growth'... 35166 more characters,
metadata: {
score: 0.16303963959217072,
title: '2022 State of the Union Address | The White House',
id: 'https://www.whitehouse.gov/state-of-the-union-2022/',
url: 'https://www.whitehouse.gov/state-of-the-union-2022/',
publishedDate: '2022-02-25',
author: ''
},
id: undefined
},
Document {
pageContent: "The President. Thank you all very, very much. Thank you, please. Thank you so much. Madam Speaker, Madam Vice President, and our First Lady and Second Gentleman, Members of Congress and the Cabinet, Justices of the Supreme Court, my fellow Americans: Last year, COVID-19 kept us apart. This year, we're finally together again.\n" +
'Tonight we meet as Democrats, Republicans, and Independents, but most importantly, as Americans with a duty to one another, to America, to the American people, and to the Constitution, and an unwavering resolve that freedom will always triumph over tyranny.\n' +
"Six—[applause]—thank you. Six days ago, Russia's Vladimir Putin sought to shake the very foundations of the free world, thinking he could make it bend to his menacing ways. But he badly miscalculated. He thought he could roll into Ukraine and the world would roll over. Instead, he met with a wall of strength he never anticipated or imagined. He met the Ukrainian people.\n" +
'From President Zelenskiy, their—to every Ukrainian, their fearlessness, their courage, their determination literally inspires the world. Groups of citizens blocking tanks with their bodies. Everyone from students to retirees, to teachers turned soldiers defending their homeland. And in this struggle—President Zelenskiy said in his speech to the European Parliament, "Light will win over darkness."\n' +
"The Ukrainian Ambassador to the United States is here tonight sitting with the First Lady. Let each of us, if you're able to stand, stand and send an unmistakable signal to the world and Ukraine. Thank you. Thank you, thank you, thank you. She's bright, she's strong, and she's resolved. Yes. We, the United States of America, stand with the Ukrainian people.\n" +
"Throughout our history, we've learned this lesson: When dictators do not pay a price for their aggression, they cause more chaos; they keep moving; and the costs, the threats to the America—and America, to the world keeps rising. That's why the NATO alliance was created: to secure peace and stability in Europe after World War II. The United States is a member, along with 29 other nations. It matters. American diplomacy matters. American resolve matters.\n" +
"Putin's latest attack on Ukraine was premeditated and totally unprovoked. He rejected repeated—repeated—efforts at diplomacy. He thought the West and NATO wouldn't respond. He thought he could divide us at home, in this Chamber, in this Nation. He thought he could divide us in Europe as well.\n" +
"But Putin was wrong. We are ready. We are united. And that's what we did: We stayed united. We prepared extensively and carefully. We spent months building coalitions of other freedom-loving nations in Europe and the Americas to—from America to the Asian and African continents to confront Putin.\n" +
"Like many of you, I spent countless hours unifying our European allies. We shared with the world in advance what we knew Putin was planning and precisely how he would try to falsify and justify his aggression. We countered Russia's lies with the truth. And now—now that he's acted, the free world is holding him accountable, along with 27 members of the European Union—including France, Germany, Italy—as well as countries like the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others—even Switzerland—are inflicting pain on Russia and supporting the people of Ukraine. Putin is now isolated from the world more than he has ever been.\n" +
"Together, along with our allies, we are right now enforcing powerful economic sanctions. We're cutting off Russia's largest banks from the international financial system; preventing Russia's Central Bank from defending the Russian ruble, making Putin's $630 billion war fund worthless. We're choking Russia's access to technology that will sap its economic strength and weaken its military for years to come.\n" +
'Tonight I say to the Russian oligarchs and the corrupt leaders who have bilked billions of dollars off this violent regime: No more. The United States—[applause]—I mean it. The United States Department of Justice is assembling a dedicated task force to go after the crimes of the Russian oligarchs.\n' +
"We're joining with European allies to find and seize their yachts, their luxury apartments, their private jets. We're coming for your ill-begotten gains. And tonight I'm announcing that we will join our allies in closing off American air space to all Russian flights, further isolating Russia and adding an additional squeeze on their economy.\n" +
"He has no idea what's coming. The ruble has already lost 30 percent of its value, the Russian stock market has lost 40 percent of its value, and trading remains suspended. The Russian economy is reeling, and Putin alone is the one to blame.\n" +
"Together with our allies, we're providing support to the Ukrainians in their fight for freedom: military assistance, economic assistance, humanitarian assistance. We're giving more than a billion dollars in direct assistance to Ukraine. And we'll continue to aid the Ukrainian people as they defend their country and help ease their suffering.\n" +
"But let me be clear: Our Forces are not engaged and will not engage in the conflict with Russian forces in Ukraine. Our Forces are not going to Europe to fight [in]* Ukraine but to defend our NATO allies in the event that Putin decides to keep moving west. For that purpose, we have mobilized American ground forces, air squadrons, ship deployments to protect NATO countries, including Poland, Romania, Latvia, Lithuania, and Estonia. And as I've made crystal clear, the United States and our allies will defend every inch of territory that is NATO territory with the full force of our collective power—every single inch.\n" +
"And we're clear eyed. The Ukrainians are fighting back with pure courage. But the next few days, weeks, and months will be hard on them. Putin has unleashed violence and chaos. But while he may make gains on the battlefield, he'll pay a continuing high price over the long run. And a pound of Ukrainian people—the proud, proud people—pound for pound, ready to fight with every inch of energy they have. They've known 30 years of independence—have repeatedly shown that they will not tolerate anyone who tries to take their country backwards.\n" +
"To all Americans, I'll be honest with you, as I've always promised I would be. A Russian dictator invading a foreign country has costs around the world. And I'm taking robust action to make sure the pain of our sanctions is targeted at Russian economy and that we use every tool at our disposal to protect American businesses and consumers.\n" +
'Tonight I can announce the United States has worked with 30 other countries to release 60 million barrels of oil from reserves around the world. America will lead that effort, releasing 30 million barrels of our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, united with our allies.\n' +
"These steps will help blunt gas prices here at home. But I know news about what's happening can seem alarming to all Americans. But I want you to know: We're going to be okay. We're going to be okay.\n" +
"When the history of this era is written, Putin's war on Ukraine will have left Russia weaker and the rest of the world stronger.\n" +
"While it shouldn't have taken something so terrible for people around the world to see what's at stake, now everyone sees it clearly. We see the unity among leaders of nations, a more unified Europe, a more unified West. We see unity among the people who are gathering in cities in large crowds around the world, even in Russia, to demonstrate their support for the people of Ukraine.\n" +
"In the battle between democracy and autocracies, democracies are rising to the moment, and the world is clearly choosing the side of peace and security. This is the real test, and it's going to take time. So let us continue to draw inspiration from the iron will of the Ukrainian people.\n" +
"To our fellow Ukrainian Americans who forged a deep bond that connects our two nations: We stand with you. We stand with you. Putin may circle Kiev with tanks, but he'll never gain the hearts and souls of the Uranian [Ukrainian]* people. He'll never extinguish their love of freedom. And he will never, never weaken the resolve of the free world.\n" +
'We meet tonight in an America that has lived through 2 of the hardest years this Nation has ever faced. The pandemic has been punishing. And so many families are living paycheck to paycheck, struggling to keep up with the rising cost of food, gas, housing, and so much more.\n' +
"I understand, like many of you did. My dad had to leave his home in Scranton, Pennsylvania, to find work. So, like many of you, I grew up in a family when the price of food went up, it was felt throughout the family; it had an impact. That's why one of the first things I did as President was fight to pass the American Rescue Plan, because people were hurting. We needed to act, and we did.\n" +
'Few pieces of legislation have done more at a critical moment in our history to lift us out of a crisis. It fueled our efforts to vaccinate the Nation and combat COVID-19. It delivered immediate economic relief to tens of millions of Americans. It helped put food on the table. Remember those long lines of cars waiting for hours just to get a box of food put in their trunk? It cut the cost of health care insurance. And as my dad used to say, it gave the people "just a little bit of breathing room."\n' +
'And unlike the $2 trillion tax cut passed in the previous administration that benefited the top 1 percent of Americans, the American Rescue Plan——\n' +
' Audience members. Boo!\n' +
' The President. ——the American Rescue Plan helped working people and left no one behind. And, folks—and it worked. It worked. It worked and created jobs, lots of jobs. In fact, our economy created over 6.5 million new jobs just last year, more jobs in 1 year than ever before in the history of the United States of America. The economy grew at a rate of 5.7 last year, the strongest growth rate in 40 years and the first step in'... 35254 more characters,
metadata: {
score: 0.16301880776882172,
title: 'Address Before a Joint Session of the Congress on the State of the Union',
id: 'https://www.presidency.ucsb.edu/documents/address-before-joint-session-the-congress-the-state-the-union-28',
url: 'https://www.presidency.ucsb.edu/documents/address-before-joint-session-the-congress-the-state-the-union-28',
publishedDate: '2022-03-01',
author: ''
},
id: undefined
}
]

在链中使用

与其他检索器一样,ExaRetriever 可以通过 被整合到 LLM 应用程序中。

我们将需要一个 LLM 或聊天模型

选择您的聊天模型

安装依赖项

yarn add @langchain/openai 

添加环境变量

OPENAI_API_KEY=your-api-key

实例化模型

import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({
model: "gpt-4o-mini",
temperature: 0
});
import { ChatPromptTemplate } from "@langchain/core/prompts";
import {
RunnablePassthrough,
RunnableSequence,
} from "@langchain/core/runnables";
import { StringOutputParser } from "@langchain/core/output_parsers";

import type { Document } from "@langchain/core/documents";

const prompt = ChatPromptTemplate.fromTemplate(`
Answer the question based only on the context provided.

Context: {context}

Question: {question}`);

const formatDocs = (docs: Document[]) => {
return docs.map((doc) => doc.pageContent).join("\n\n");
};

// See https://js.langchain.ac.cn/v0.2/docs/tutorials/rag
const ragChain = RunnableSequence.from([
{
context: retriever.pipe(formatDocs),
question: new RunnablePassthrough(),
},
prompt,
llm,
new StringOutputParser(),
]);
await ragChain.invoke(
"What did the speaker say about Justice Breyer in the 2022 State of the Union?"
);
In the 2022 State of the Union Address, the speaker, President Biden, honored Justice Breyer, describing him as someone who has dedicated his life to serve the country. He acknowledged Justice Breyer as an Army veteran and a constitutional scholar, and he expressed gratitude for his service. President Biden also mentioned that one of the most serious constitutional responsibilities of a President is nominating someone to serve on the United States Supreme Court, and he highlighted his nomination of Ketanji Brown Jackson to succeed Justice Breyer.

API 参考

有关所有 ExaRetriever 功能和配置的详细文档,请转到 API 参考


此页面对您有帮助吗?


您也可以留下详细的反馈 在 GitHub 上.