Skip to main content

How to Use Exa with TypeScript

1. Create an account and grab an API key

First, generate and grab an API key for Exa:

Get API Key

Follow this link to get your API key

2. Install the SDK

Install the Exa TypeScript SDK using npm:
Bash
npm install exa-js

3. Instantiate the client

Create a new TypeScript file (e.g., exa-example.ts) and instantiate the Exa client:
TypeScript

import Exa from 'exa-js';

const exa = new Exa(process.env.EXA_API_KEY);
Make sure to set the EXA_API_KEY environment variable with your API key.

4. Make a search using the searchAndContents method

Here’s an example of how to use the searchAndContents method:
TypeScript

async function exampleSearch() {
  try {
    const result = await exa.searchAndContents(
      "hottest AI startups",
      {
        type: "neural",
        useAutoprompt: true,
        numResults: 10,
        text: true,
      }
    );

    console.log(JSON.stringify(result, null, 2));
  } catch (error) {
    console.error("Error:", error);
  }
}

exampleSearch();

5. Set up OpenAI and pass the Exa query results to perform RAG

First, install the OpenAI library:
Bash
npm install openai
Now, set up the OpenAI client and use it to summarize Exa search results, creating a RAG system:
TypeScript
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

async function performRAG() {
  try {
    const exaResult = await exa.searchAndContents(
      "hottest AI startups",
      {
        type: "neural",
        useAutoprompt: true,
        numResults: 10,
        text: true,
      }
    );

    const systemPrompt = "You are a helpful AI assistant. Summarize the given search results about AI startups.";
    const userMessage = "Please provide a brief summary of the top AI startups based on the search results.";

    const response = await openai.chat.completions.create({
      model: "gpt-3.5-turbo",
      messages: [
        { role: "system", content: systemPrompt },
        { role: "user", content: `Search results: ${JSON.stringify(exaResult)}\n\n${userMessage}` }
      ]
    });

    console.log(response.choices[0].message.content);
  } catch (error) {
    console.error("Error:", error);
  }
}

performRAG();
Make sure to set the OPENAI_API_KEY environment variable with your OpenAI API key. This completes the guide, demonstrating how to set up Exa and OpenAI, use Exa’s search capabilities, and then use OpenAI to summarize the results in a RAG system. The combination of Exa’s powerful search capabilities with OpenAI’s language model allows for the creation of a system that can retrieve relevant, up-to-date information and generate insightful summaries based on that information.