### Run Next.js Development Server Source: https://github.com/exa-labs/exa-js/blob/master/examples/next/README.md Commands to start the local development server for a Next.js application. This allows you to view the application in your browser at http://localhost:3000 and enables hot-reloading for development. ```bash npm run dev ``` ```bash yarn dev ``` ```bash pnpm dev ``` ```bash bun dev ``` -------------------------------- ### Run Metaphor Researcher Javascript File Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/README.md This snippet provides the command-line instructions to set up and execute the Metaphor Researcher example project. It involves installing the required SDKs using npm and then running the main Javascript file with Node.js. ```Shell npm install node researcher.mjs ``` -------------------------------- ### Initialize Exa and OpenAI SDKs with API Keys Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This snippet demonstrates how to import the Exa and OpenAI SDKs and initialize their client objects using API keys. It provides import examples for both Deno and NodeJS runtimes, allowing users to choose the appropriate setup for their environment. Users must insert their actual API keys for EXA_API_KEY and OPENAI_API_KEY. ```typescript // Deno imports import Exa from 'npm:exa-js'; import OpenAI from 'npm:openai'; // NodeJS imports //import Exa from 'exa-js'; //import OpenAI from 'openai'; const EXA_API_KEY = // insert or load your API key here const OPENAI_API_KEY = // insert or load your API key here const exa = new Exa(EXA_API_KEY); const openai = new OpenAI({ apiKey: OPENAI_API_KEY }); ``` -------------------------------- ### Install exa-js package Source: https://github.com/exa-labs/exa-js/blob/master/README.md Installs the exa-js JavaScript SDK using npm, the Node.js package manager. ```npm npm install exa-js ``` -------------------------------- ### Exa-JS Websets API Implementation Overview Source: https://github.com/exa-labs/exa-js/blob/master/CLAUDE.md This snippet details the planned implementation of the Websets API in TypeScript, mirroring the existing Python SDK. It describes the core WebsetsClient with its primary methods (create, get, list, update, delete, cancel, wait_until_idle), the presence of sub-clients for specific functionalities (items, searches, enrichments, webhooks), the necessity for extensive type definitions, pagination support for list operations, and the handling of various entity types (company, person, article, research paper, custom). ```APIDOC Websets API: - Mirror Python SDK implementation in TypeScript - Key Components: - WebsetsClient: - Methods: create, get, list, update, delete, cancel, wait_until_idle - Sub-clients: - items - searches - enrichments - webhooks - Type Definitions: - Extensive types for all request/response objects - Pagination: - Proper handling for list operations - Entity Types: - company - person - article - research paper - custom ``` -------------------------------- ### Manage Exa-JS Project: Build, Test, and Document Generation Commands Source: https://github.com/exa-labs/exa-js/blob/master/CLAUDE.md This snippet provides common command-line instructions for building, testing, and generating documentation for the Exa-JS project. It includes commands for full builds, fast builds, running all tests, executing single tests, and generating project documentation. ```Shell npm run build ``` ```Shell npm run build-fast ``` ```Shell npm run test ``` ```Shell npx vitest run test/path/to/test.ts ``` ```Shell npm run generate-docs ``` -------------------------------- ### Test Keyword Query Generation with LLM Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This example demonstrates how to use the `createKeywordQueryGenerationPrompt` function with `getLLMResponse` to generate and display a list of keyword search queries for a specific topic. ```typescript console.log(await getLLMResponse({ system: 'The user will ask you to help generate some search queries. Respond with only the suggested queries in plain text with no extra formatting, each on it\'s own line.', user: createKeywordQueryGenerationPrompt(XYZZY_TOPIC, 3), })); ``` -------------------------------- ### Generating Documentation with npm Source: https://github.com/exa-labs/exa-js/blob/master/CLAUDE.md Command to build and generate the project's documentation, likely from JSDoc comments and source code structure. Essential for maintaining project documentation. ```Bash npm run generate-docs ``` -------------------------------- ### Example Usage of Query Generation Function Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This snippet provides examples of calling the `generateSearchQueries` function. It shows how to generate both keyword-based and neural-based queries for different topics, specifying the number of desired queries. ```typescript const XYZZYQueries = await generateSearchQueries(XYZZY_TOPIC, 3, 'keyword'); const artQueries = await generateSearchQueries(ART_TOPIC, 3, 'neural'); ``` -------------------------------- ### Test Neural Query Generation with LLM Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This example demonstrates how to use the `createNeuralQueryGenerationPrompt` function with `getLLMResponse` to generate and display a list of Exa neural search queries for a specific topic. ```typescript console.log(await getLLMResponse({ system: 'The user will ask you to help generate some search queries. Respond with only the suggested queries in plain text with no extra formatting, each on it\'s own line.', user: createNeuralQueryGenerationPrompt(ART_TOPIC, 3), //model: 'gpt-4' })); ``` -------------------------------- ### Running Single Vitest Test File with npx Source: https://github.com/exa-labs/exa-js/blob/master/CLAUDE.md Utility command using `npx` to run a specific test file specified by its path. This is useful for debugging or focusing on individual test cases. ```Bash npx vitest run test/path/to/test.ts ``` -------------------------------- ### Start Function to Decide Exa Search Type with LLM Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This snippet begins the definition of the `decideSearchType` asynchronous function, which leverages an LLM to determine whether to use 'neural' or 'keyword' search for a given topic. It constructs the initial `userMessage` for the LLM, instructing it to choose between two search types based on a provided guide. The function takes the research topic and optional choice names as input. ```typescript async function decideSearchType(topic, choiceNames = ['neural', 'keyword']){ let userMessage = 'Decide whether to use (1) or (2) search for the provided research topic. Output your choice in a single word: either "(1)" or "(2)". Here is a guide that will help you choose:\n'; ``` -------------------------------- ### Define Example Research Topic Constants Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This snippet defines two constant variables, `XYZZY_TOPIC` and `ART_TOPIC`, to represent example research topics. These constants are used to demonstrate the functionality of the Exa Researcher application and can be easily modified to explore different research subjects. ```typescript const XYZZY_TOPIC = 'xyzzy'; const ART_TOPIC = 'renaissance art'; ``` -------------------------------- ### Exa-JS TypeScript Code Style and Design Guidelines Source: https://github.com/exa-labs/exa-js/blob/master/CLAUDE.md This section outlines the comprehensive code style guidelines for Exa-JS, focusing on TypeScript. It covers language targets, formatting, import conventions, type definitions (including JSDoc, generics, PascalCase for interfaces), naming conventions (PascalCase for classes, camelCase for methods/variables), error handling practices, and API design principles like class-based structure and method overloading. ```APIDOC TypeScript: - ES2020 target - ESNext modules - Strict mode Formatting: - Default Prettier (2.8.4) Imports: - ES imports - Built-in modules first Types: - Comprehensive TypeScript types with JSDoc comments - Generic types for API responses - Interfaces/Types in PascalCase (e.g., SearchOptions) - Optional properties with ? suffix Naming: - Classes: PascalCase (e.g., Exa) - Methods/Variables: camelCase - Consistent patterns (e.g., *Options, *Response) Error Handling: - Explicit errors with descriptive messages - API error handling with status codes API Design: - Class-based design with clear method signatures - Private helper methods for common functionality - Method overloading via optional parameters ``` -------------------------------- ### Define Constant for Search Type Explanation Prompt Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This constant `SEARCH_TYPE_EXPLANATION` holds a detailed description of two search types, referred to as (1) and (2). This text is intended to be used within an LLM prompt to guide the model in deciding between neural and keyword search based on the characteristics of a research topic. The generic numbering allows for programmatic replacement with actual search type names. ```typescript const SEARCH_TYPE_EXPLANATION = `- (1) search is preferred because it lets us retrieve high quality, up-to-date, and semantically relevant data. It is especially suitable when a topic is well-known and popularly discussed on the Internet, allowing the machine learning model to retrieve contents which are more likely recommended by real humans. - (2) search is only necessary when the topic is extremely specific, local or obscure. If the machine learning model might not know about the topic, but relevant documents can be found by directly matching the search query, (2) search is suitable. `; ``` -------------------------------- ### Perform search with date range filters Source: https://github.com/exa-labs/exa-js/blob/master/README.md Executes a search query, filtering results by a specified start and end published date. This helps narrow down results to a specific time frame. ```javascript const dateFilteredResults = await exa.search("This is a Exa query:", { startPublishedDate: "2019-01-01", endPublishedDate: "2019-01-31" }); ``` -------------------------------- ### Test Search Type Decision Function Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This snippet provides example usage and verification for the `decideSearchType` function, showing how it determines the search type ('keyword' or 'neural') for different topics and logs the results. ```typescript console.log(XYZZY_TOPIC, 'expected: keyword, got:', await decideSearchType(XYZZY_TOPIC)); console.log(ART_TOPIC, 'expected: neural, got:', await decideSearchType(ART_TOPIC)); ``` -------------------------------- ### Determine Search Type (Keyword or Neural) with LLM Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This code snippet demonstrates how to use an LLM to decide between 'keyword' and 'neural' search types. It constructs a user message with topic and search options, then sends it to an LLM to get a single-word choice, which determines the search strategy. ```typescript userMessage += SEARCH_TYPE_EXPLANATION; userMessage += `Topic: ${topic}\n`; userMessage += `Search type: `; userMessage = userMessage.replaceAll('(1)', choiceNames[0]).replaceAll('(2)', choiceNames[1]); const response = await getLLMResponse({ system: 'You will be asked to make a choice between two options. Answer with your choice in a single word.', user: userMessage, temperature: 0 }); const useKeyword = response.trim().toLowerCase().startsWith(choiceNames[1].toLowerCase()); return useKeyword ? 'keyword' : 'neural'; ``` -------------------------------- ### Initialize Exa JavaScript SDK Source: https://github.com/exa-labs/exa-js/blob/master/README.md Imports the Exa class and initializes a new Exa client instance using an API key from environment variables. This sets up the client for making API calls. ```javascript import Exa from "exa-js"; const exa = new Exa(process.env.EXA_API_KEY); ``` -------------------------------- ### Exa-JS: Create and Poll Research Task with Schema Source: https://github.com/exa-labs/exa-js/blob/master/README.md Demonstrates how to initialize the Exa-JS client, define a JSON schema for the desired output, create a research task with specific instructions, and then poll the task for its result. It highlights the use of `exa.research.createTask` and `exa.research.pollTask`. ```javascript import Exa from "exa-js"; const exa = new Exa(process.env.EXA_API_KEY); const schema = { type: "object", required: ["answer"], properties: { answer: { type: "string" } }, additionalProperties: false }; const { id: taskId } = await exa.research.createTask({ instructions: "In ≤3 sentences, explain quantum computing.", output: { schema } }); const result = await exa.research.pollTask(taskId); ``` -------------------------------- ### Perform a basic search with Exa Source: https://github.com/exa-labs/exa-js/blob/master/README.md Executes a simple search query using the Exa client to retrieve relevant documents. ```javascript const basicResults = await exa.search("This is a Exa query:"); ``` -------------------------------- ### Exa Research Agent: createTask Method API Reference Source: https://github.com/exa-labs/exa-js/blob/master/README.md Documents the `createTask` method of Exa's research agent, which allows autonomous information gathering and structured JSON output. It details the required `instructions` and optional `output` parameters, including schema definition, and the returned task ID. ```APIDOC Method: exa.research.createTask Parameters: instructions: string - Instructions for the research agent. output: object (optional) - Output configuration. schema: object (optional) - JSON schema for the output. Returns: Promise<{id: string}> - A promise resolving to an object with the task ID. ``` -------------------------------- ### Perform search and retrieve contents with custom options Source: https://github.com/exa-labs/exa-js/blob/master/README.md Executes a search query and fetches content with specified options, such as limiting the maximum number of characters retrieved for each document. ```javascript const searchAndCustomContentsResults = await exa.searchAndContents( "This is a Exa query:", { text: { maxCharacters: 3000 } } ); ``` -------------------------------- ### Generate Keyword Search Query Prompt for LLM Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This function creates a prompt string designed for an LLM to generate Google-like keyword search queries. The prompt specifies the desired format (short, few words, no formatting) and the number of queries needed for a given topic. ```typescript function createKeywordQueryGenerationPrompt(topic, n){ return `I'm writing a research report on ${topic} and need help coming up with Google keyword search queries.\nGoogle keyword searches should just be a few words long. It should not be a complete sentence.\nPlease generate a diverse list of ${n} Google keyword search queries that would be useful for writing a research report on ${topic}. Do not add any formatting or numbering to the queries.` } ``` -------------------------------- ### Find similar documents and retrieve contents Source: https://github.com/exa-labs/exa-js/blob/master/README.md Identifies documents similar to a given URL and simultaneously fetches their text content. This combines the similarity search with immediate content access. ```javascript const similarWithContentsResults = await exa.findSimilarAndContents( "https://example.com", { text: true } ); ``` -------------------------------- ### API Reference: exa.answer method Source: https://github.com/exa-labs/exa-js/blob/master/README.md Generates an answer to a query using search results as context, with an option to retrieve text. ```APIDOC exa.answer(query: string, options?: AnswerOptions): Promise const response = await exa.answer("What is the population of New York City?", { text: true }); ``` -------------------------------- ### API Reference: exa.findSimilar method Source: https://github.com/exa-labs/exa-js/blob/master/README.md Finds content similar to the specified URL, with options for number of results. ```APIDOC exa.findSimilar(url: string, options?: FindSimilarOptions): Promise const response = await exa.findSimilar( "https://waitbutwhy.com/2014/05/fermi-paradox.html", { numResults: 10 } ); ``` -------------------------------- ### Fetch and Log First Webpage Content Extract Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This snippet demonstrates how to call the `getPageContents` function with an array of search result links. It then logs the `extract` property of the first retrieved content object, which typically contains a summary or a portion of the webpage's text. ```typescript const artContent = await getPageContents(artLinks); console.log(artContent[0].extract); // first result of six ``` -------------------------------- ### Retrieve contents with custom options Source: https://github.com/exa-labs/exa-js/blob/master/README.md Fetches content for specified URLs with advanced options, such as including HTML tags and setting a maximum character limit for the retrieved text. ```javascript const customContentsResults = await exa.getContents(["urls"], { text: { includeHtmlTags: true, maxCharacters: 3000 } }); ``` -------------------------------- ### Generate Search Queries with LLM Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This function demonstrates how to generate search queries using a Large Language Model (LLM). It constructs a prompt based on the desired search type (neural or keyword) and sends it to the LLM. The LLM's plain text response is then parsed into an array of individual queries, filtered for non-empty strings. ```typescript async function generateSearchQueries(topic, n, searchType) { const userPrompt = searchType === 'neural' ? createNeuralQueryGenerationPrompt(topic, n) : createKeywordQueryGenerationPrompt(topic, n); const completion = await getLLMResponse({ system: 'The user will ask you to help generate some search queries. Respond with only the suggested queries in plain text with no extra formatting, each on it\'s own line.', user: userPrompt, temperature: 1 }); const queries = completion.split('\n').filter(s => s.trim().length > 0).slice(0, n); return queries; } ``` -------------------------------- ### Stream an answer to a question Source: https://github.com/exa-labs/exa-js/blob/master/README.md Streams the answer to a question in real-time, yielding chunks of content and citations as they become available. This is useful for providing real-time updates in chat interfaces or displaying partial results. ```javascript for await (const chunk of exa.streamAnswer( "What is the population of New York City?" )) { if (chunk.content) { process.stdout.write(chunk.content); } if (chunk.citations) { console.log("\nCitations:", chunk.citations); } } ``` -------------------------------- ### Log Generated Search Queries Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This snippet demonstrates how to print the arrays of search queries generated by the `generateSearchQueries` function to the console, allowing for inspection of the output. ```typescript console.log(XYZZYQueries); console.log(artQueries); ``` -------------------------------- ### Execute Exa Search and Log First Result Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This snippet demonstrates how to call the `getSearchResults` function with previously generated queries and a specified search type. It then logs the first search result object to the console, showing its structure including title, URL, and other metadata. ```typescript const artLinks = await getSearchResults(artQueries, 'neural'); console.log(artLinks[0]); // first result of six ``` -------------------------------- ### Generate Neural Search Query Prompt for Exa LLM Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This function crafts a detailed prompt for an LLM to generate Exa neural search queries. It includes an explanation of Exa's neural search mechanism and specific instructions on how to phrase queries as content recommendations ending in a colon. ```typescript function createNeuralQueryGenerationPrompt(topic, n){ return `I'm writing a research report on ${topic} and need help coming up with Exa keyword search queries.\nExa is a fully neural search engine that uses an embeddings based approach to search. Exa was trained on how people refer to content on the internet. The model is trained given the description to predict the link. For example, if someone tweets "This is an amazing, scientific article about Roman architecture: ", then our model is trained given the description to predict the link, and it is able to beautifully and super strongly learn associations between descriptions and the nature of the content (style, tone, entity type, etc) after being trained on many many examples. Because Exa was trained on examples of how people talk about links on the Internet, the actual Exa queries must actually be formed as if they are content recommendations that someone would make on the Internet where a highly relevant link would naturally follow the recommendation, such as the example shown above.\nExa neural search queries should be phrased like a person on the Internet indicating a webpage to a friend by describing its contents. It should end in a colon :.\nPlease generate a diverse list of ${n} Exa neural search queries for informative and trustworthy sources useful for writing a research report on ${topic}. Do not add any quotations or numbering to the queries.` } ``` -------------------------------- ### TypeScript: Execute and Log Full Research Workflow Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This snippet executes the complete `researcher` workflow for a given topic (`XYZZY_TOPIC`) and then logs the final synthesized research report to the console. ```typescript console.log(await researcher(XYZZY_TOPIC)); ``` -------------------------------- ### Generate an answer to a question Source: https://github.com/exa-labs/exa-js/blob/master/README.md Uses Exa's capabilities to generate a direct answer to a natural language question, leveraging search results as context. ```javascript const answerResult = await exa.answer( "What is the population of New York City?" ); ``` -------------------------------- ### TypeScript: Synthesize Research Report with LLM and Citations Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This asynchronous function processes search results to generate a research report using an LLM. It formats content with URLs, prompts the LLM to create a two-paragraph report with in-text footnote citations, and includes a 'References' section. It relies on an external `getLLMResponse` function. ```typescript async function synthesizeReport(topic, searchContents, contentSlice = 750){ const inputData = searchContents.map(item => "--START ITEM--\nURL: ${item.url}\nCONTENT: ${item.extract.slice(0, contentSlice)}\n--END ITEM--\n").join(''); return await getLLMResponse({ system: 'You are a helpful research assistant. Write a report according to the user\'s instructions.', user: 'Input Data:\n' + inputData + `Write a two paragraph research report about ${topic} based on the provided information. Include as many sources as possible. Provide citations in the text using footnote notation ([#]). First provide the report, followed by a single "References" section that lists all the URLs used, in the format [#] .`, //model: 'gpt-4' //want a better report? use gpt-4 }); } ``` -------------------------------- ### Create Utility Function for OpenAI LLM Responses Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This asynchronous function `getLLMResponse` simplifies interactions with the OpenAI API's chat completions endpoint. It allows direct passing of system and user messages, along with optional temperature and model parameters. The function returns the content of the LLM's response as a string, streamlining subsequent API calls. ```typescript async function getLLMResponse({system = 'You are a helpful assistant.', user = '', temperature = 1, model = 'gpt-3.5-turbo'}){ const completion = await openai.chat.completions.create({ model, temperature, messages: [ {'role': 'system', 'content': system}, {'role': 'user', 'content': user}, ] }); return completion.choices[0].message.content; } ``` -------------------------------- ### Generate an answer with a specified output schema Source: https://github.com/exa-labs/exa-js/blob/master/README.md Generates an answer to a question, ensuring the output conforms to a provided JSON schema. This allows for structured and predictable responses. ```javascript const answerResult = await exa.answer( "What is the population of New York City?", { outputSchema: { type: "object", required: ["answer"], additionalProperties: false, properties: { answer: { type: "number" } } } } ); ``` -------------------------------- ### Configure ESLint parserOptions for Type-Aware Linting Source: https://github.com/exa-labs/exa-js/blob/master/examples/vite/README.md This JavaScript code snippet demonstrates how to configure the `parserOptions` within your ESLint configuration file. It's essential for enabling type-aware linting rules in a React and TypeScript project, specifying the ECMAScript version, module source type, and paths to your TypeScript configuration files. ```js parserOptions: { ecmaVersion: 'latest', sourceType: 'module', project: ['./tsconfig.json', './tsconfig.node.json'], tsconfigRootDir: __dirname, }, ``` -------------------------------- ### API Reference: exa.streamAnswer method Source: https://github.com/exa-labs/exa-js/blob/master/README.md Streams an answer as it's being generated, yielding chunks of text and citations. This is useful for providing real-time updates in chat interfaces or displaying partial results as they become available. Each chunk contains: `content` (A string containing the next piece of generated text) and `citations` (An array of citation objects containing source information). ```APIDOC exa.streamAnswer(query: string, options?: { text?: boolean }): AsyncGenerator // Basic streaming example for await (const chunk of exa.streamAnswer("What is quantum computing?")) { if (chunk.content) { process.stdout.write(chunk.content); } if (chunk.citations) { console.log("\nCitations:", chunk.citations); } } for await (const chunk of exa.streamAnswer("What is quantum computing?", { text: true, })) { } ``` -------------------------------- ### TypeScript: Orchestrate Full Research Workflow Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This asynchronous function encapsulates the entire research process. It dynamically determines search type, generates queries, fetches results, retrieves page contents, and finally synthesizes a report using `synthesizeReport`. It includes console logs for tracing the workflow. ```typescript async function researcher(topic){ const searchType = await decideSearchType(topic); const searchQueries = await generateSearchQueries(topic, 3, searchType); console.log(searchQueries); const searchResults = await getSearchResults(searchQueries, searchType); console.log(searchResults[0]); const searchContents = await getPageContents(searchResults); console.log(searchContents[0]); const report = await synthesizeReport(topic, searchContents); return report; } ``` -------------------------------- ### API Reference: exa.search method Source: https://github.com/exa-labs/exa-js/blob/master/README.md Performs a search on the Exa system with the given parameters. Supports various options like number of results, domain filters, and date ranges. ```APIDOC exa.search(query: string, options?: SearchOptions): Promise const response = await exa.search("funny article about tech culture", { numResults: 5, includeDomains: ["nytimes.com", "wsj.com"], startPublishedDate: "2023-06-12" }); ``` -------------------------------- ### Perform Exa Search for Multiple Queries Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This asynchronous function iterates through a list of generated search queries and performs a search using the `exa.search` API for each. It allows specifying the search type (neural or keyword) and the number of links to retrieve per query. All results are aggregated and returned. ```typescript async function getSearchResults(queries, type, linksPerQuery=2){ let results = []; for (const query of queries){ const searchResponse = await exa.search(query, { type, numResults: linksPerQuery, useAutoprompt: false }); results.push(...searchResponse.results); } return results; } ``` -------------------------------- ### Perform search and retrieve text contents Source: https://github.com/exa-labs/exa-js/blob/master/README.md Executes a search query and simultaneously fetches the text content of the results. This is useful for immediate access to document content after a search. ```javascript const searchAndTextResults = await exa.searchAndContents( "This is a Exa query:", { text: true } ); ``` -------------------------------- ### TypeScript: Generate Art Research Report Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This snippet demonstrates calling the `synthesizeReport` function with a specific topic (`ART_TOPIC`) and pre-fetched content (`artContent`) to generate a research report on art. The result is stored in the `artReport` variable. ```typescript const artReport = await synthesizeReport(ART_TOPIC, artContent); ``` -------------------------------- ### Find documents similar to a URL Source: https://github.com/exa-labs/exa-js/blob/master/README.md Identifies and retrieves documents that are semantically similar to the content found at a given URL. ```javascript const similarResults = await exa.findSimilar("https://example.com"); ``` -------------------------------- ### Retrieve text contents for specified URLs Source: https://github.com/exa-labs/exa-js/blob/master/README.md Fetches the text content for a list of provided URLs or result objects. This allows direct retrieval of content for known documents. ```javascript const textContentsResults = await exa.getContents(["urls"], { text: true }); ``` -------------------------------- ### Find similar documents excluding source domain Source: https://github.com/exa-labs/exa-js/blob/master/README.md Identifies documents similar to a given URL, but explicitly excludes results originating from the source domain itself. This prevents finding the same or very similar documents from the original site. ```javascript const similarExcludingSourceResults = await exa.findSimilar( "https://example.com", { excludeSourceDomain: true } ); ``` -------------------------------- ### API Reference: exa.getContents method Source: https://github.com/exa-labs/exa-js/blob/master/README.md Retrieves the contents of the specified documents by URL or Result objects. ```APIDOC exa.getContents(urls: string[] | Result[]): Promise const response = await exa.getContents([ "https://blog.samaltman.com/how-to-be-successful" ]); ``` -------------------------------- ### Perform search with domain filters Source: https://github.com/exa-labs/exa-js/blob/master/README.md Executes a search query, including results only from specified domains. This allows focusing the search on trusted or relevant websites. ```javascript const domainFilteredResults = await exa.search("This is a Exa query:", { includeDomains: ["www.cnn.com", "www.nytimes.com"] }); ``` -------------------------------- ### Orchestrate Search Query Generation by Type Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This function serves as an orchestrator, taking a topic, number of queries, and a specified search type ('keyword' or 'neural') to delegate query generation to the appropriate underlying function. It includes basic validation for the search type. ```typescript async function generateSearchQueries(topic, n, searchType){ if(searchType !== 'keyword' && searchType !== 'neural'){ throw 'invalid searchType'; } ``` -------------------------------- ### Retrieve Webpage Contents with Exa Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This asynchronous function takes an array of search results (e.g., from `exa.search`) and uses the `exa.getContents` API to fetch the full content for each result. It returns an array of content objects. ```typescript async function getPageContents(searchResults){ const contentsResponse = await exa.getContents(searchResults); return contentsResponse.contents; } ``` -------------------------------- ### TypeScript: Display Generated Report Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This snippet outputs the content of the `artReport` variable, which holds the synthesized research report, to the console for review. ```typescript console.log(artReport) ``` -------------------------------- ### JavaScript Object for Web Page Metadata Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This JavaScript object literal defines a structure for storing basic metadata about a web page, such as its title, URL, author, and a unique identifier. It's commonly used in data processing or content management systems. ```javascript { title: "Xyzzy (computing) - Wikipedia", url: "https://en.wikipedia.org/wiki/Xyzzy_(computing)", author: null, id: "ac05e07a-722a-4de5-afc8-856c8192c5d2" } ``` -------------------------------- ### JavaScript Object with HTML Content Extract Source: https://github.com/exa-labs/exa-js/blob/master/examples/researcher/researcher.md This JavaScript object literal extends the web page metadata structure by including an 'extract' field. This field contains a string of HTML content, likely representing a snippet or full body of the web page, useful for content analysis or display. ```javascript { id: "ac05e07a-722a-4de5-afc8-856c8192c5d2", url: "https://en.wikipedia.org/wiki/Xyzzy_(computing)", title: "Xyzzy (computing)", author: null, extract: "
\n" + "

From Wikipedia, the free encyclopedia

\n" + "
\n" + "'

In