Working with query resolvers and OpenAI

Working with query resolvers and OpenAI

Resolvers are a powerful way to extend your Grafbase backend with data from other data sources. We can use resolvers to compute custom business logic, make network requests, invoke dependencies, and lots more.

In this guide, we'll create a new GraphQL API using Grafbase that exposes a single query resolver that you can use with GPT-3.5 to ask OpenAI a question.

Inside of a new directory or an existing project run the following command:

npx grafbase init

We're going to be using the Completions API from OpenAI. We will add a query that accepts a prompt and returns a list of Choices from GPT-3.5.

Open the file grafbase/schema.graphql and replace the contents with this schema:

extend type Query { ask(prompt: String!): [Choice] @resolver(name: "ask") } type Choice { text: String }

The schema includes the custom query ask that points to the resolver file ask but we don't have one, let's create that now.

Create the file grafbase/resolvers/ask.js and add the following:

export default async function Resolver(_, { prompt }) { // ... }

You'll notice we are destructuring the prompt argument from the second parameter. We need this to pass to OpenAI next.

We'll be forwarding questions to OpenAI so you will need to create an account, and from your account settings generate a new API key.

Make sure to copy and store your API key in a safe place.

OpenAI API Keys

Now add your API key to the file grafbase/.env in this format:

OPENAI_API_KEY=

Next we'll use the OpenAI API to call /v1/completions and send it the required arguments in the body as JSON:

export default async function Resolver(_, { prompt }) { const response = await fetch('https://api.openai.com/v1/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, }, body: JSON.stringify({ model: 'text-davinci-003', prompt, max_tokens: 200, temperature: 0, }), }) const data = await response.json() return data.choices || [] }

You can learn more about OpenAI by following the official quickstart.

We're now ready to ask OpenAI a question!

Start the Grafbase CLI:

npx grafbase dev

Then go to http://localhost:4000 and execute the following GraphQL query:

{ ask(prompt: "Who invented GraphQL?") { text } }

That's it! You should see a response from OpenAI that answers your question.

Get Started

Start building your graph now.