Build an AI App

Getting Company Info

First, let's set up our dependencies and initialize the Exa client. We'll be using this for a web search tool.

shared.ts
import "dotenv/config";
import Exa from "exa-js";
 
export const exa = new Exa(process.env.EXA_API_KEY);

Define a shared prompt.

company-info.ts
const companyInfoPrompt = (company: string) => `For the following company provide:
- a brief company description
- what do they sell / what products do they offer
 
<company>${company}</company>`

Create a function to fetch company info using Perplexity's Sonar model:

company-info.ts
const fetchCompanyInfoWithPerplexity = async (company: string) => {
  const { text: description, sources } = await generateText({
    model: perplexity("sonar-pro"),
    prompt: companyInfoPrompt(company),
  });
  return { description, sources };
};

Create a function to fetch company info from web sources using GPT-4o:

company-info.ts
const fetchCompanyInfoFromWeb = async (company: string) => {
  const { experimental_output: object } = await generateText({
    model: openai("gpt-4o"),
    prompt: companyInfoPrompt(company),
    tools: {
      searchWeb: tool({
        description: "Search the web for information about a company",
        parameters: z.object({
          query: z.string().min(1).max(100).describe("The search query"),
        }),
        execute: async ({ query }) => {
          const { results } = await exa.searchAndContents(query, {
            livecrawl: "always",
            numResults: 5,
          });
          return { results };
        },
      }),
    },
    maxSteps: 3,
    experimental_output: Output.object({
      schema: z.object({
        description: z.string(),
        products: z.array(z.string()).describe("The products offered by the company"),
      }),
    }),
  });
  return object;
};

Finally, combine the results from both sources into a comprehensive company overview:

export const getCompanyInfo = async (company: string) => {
  const results = await Promise.all([
    await fetchCompanyInfoWithPerplexity(company),
    await fetchCompanyInfoFromWeb(company),
  ]);
  const { object } = await generateObject({
    model: openai("gpt-4o"),
    prompt: `The user has asked for a detailed overview of ${company}.
    Synthesize from the following sources:\n${JSON.stringify(results)}`,
    schema: z.object({
      description: z.string(),
      products: z.array(z.string()).describe("The products offered by the company"),
      sources: z.array(z.string()).describe("The sources used"),
    }),
  });
  return object;
};