Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
44 replies
Simvolick

tRPC and querying data from external api

I am trying to set up the following this.

User writes a text in the form. He presses the button, the button puts input into tRPC and does a query(or maybe a mutation?) to send a completion request to OpenAI API and returns a result from there. I take this result and display it in the new text format bellow the button.

Right now I know I have realised it incorrectly as it is not working, but I have no idea how to solve this or what is the best practice. Maybe I shouldn't be using tRPC at all.

import { z } from "zod";
import { env } from "../../../env.mjs";
import { useState } from "react";

import { createTRPCRouter, publicProcedure, protectedProcedure } from "../trpc";

import type { NextApiRequest, NextApiResponse } from 'next';
import { Configuration, OpenAIApi } from 'openai';


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


// router to use gpt3 openai api
export const gptRouter = createTRPCRouter({
  gptUse: publicProcedure
    .input(z.object({
      text: z.string().nullish(),
    }))
    .query(async ({ input }) => {
      const completion = await openai.createCompletion({
        model: 'gpt-3.5-turbo',
        prompt: input?.text ?? "write 'no text'",
        temperature: 0.7,
        top_p: 1,
        max_tokens: 1000,
      })
      const result = completion.data
      return result
    }),

    gtpUseMutate: publicProcedure
    .input(z.object({
      text: z.string().nullish(),
    }))
    .mutation(async req => {
      const completion = await openai.createCompletion({
        model: 'gpt-3.5-turbo',
        prompt: req.input?.text ?? "write 'no text'",
        temperature: 0.7,
        top_p: 1,
        max_tokens: 1000,
      })
      const result = completion.data
      return result
    }
    )
Was this page helpful?