Skip to content
This repository has been archived by the owner on May 7, 2024. It is now read-only.

gabrielluizsf/openai-go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

42 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

OpenAI Go

APIs

  • Chat Completion
  • Audio Transcription
  • Text To Speech

Examples

Fiber

package main

import (
	"os"

	"github.com/gabrielluizsf/openai-go/pkg/openai"
	"github.com/gabrielluizsf/openai-go/pkg/openai/chat"
	"github.com/gofiber/fiber/v2"
)

type RequestBody struct {
	System  string `json:"system"`
	Message string `json:"message"`
}

func main() {
	app := fiber.New()
	apiKey := os.Getenv("OPENAI_KEY")
	app.Post("/", func(c *fiber.Ctx) error {
		body := new(RequestBody)
		if err := c.BodyParser(body); err != nil {
			return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
				"errMessage": "Invalid Request Body",
			})
		}
		openai := openai.WithContext(c.Context(), apiKey)
		response, err := openai.ChatGPT(&openai.ChatCompletionRequestParams{
			Model: "gpt-3.5-turbo",
			Messages: []chat.Message{
				{Role: "system", Content: body.System},
				{Role: "user", Content: body.Message},
			},
		})
		if err != nil {
			return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
				"errMessage": err.Error(),
			})
		}
		return c.JSON(response)
	})

	app.Listen(":3000")
}

Echo

package main

import (
	"net/http"
	"os"

	"github.com/gabrielluizsf/openai-go/pkg/openai"
	"github.com/gabrielluizsf/openai-go/pkg/openai/chat"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

type RequestBody struct {
	System  string `json:"system"`
	Message string `json:"message"`
}

func main() {
	e := echo.New()

	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	apiKey := os.Getenv("OPENAI_KEY")

	e.POST("/", func(c echo.Context) error {
		body := new(RequestBody)
		if err := c.Bind(body); err != nil {
			return c.JSON(http.StatusBadRequest, map[string]string{"errMessage": "Invalid Request Body"})
		}

		openaiClient := openai.WithContext(c.Request().Context(), apiKey)
		response, err := openaiClient.ChatGPT(&openai.ChatCompletionRequestParams{
			Model: "gpt-3.5-turbo",
			Messages:[]chat.Message{
				{Role: "system", Content: body.System},
				{Role: "user", Content: body.Message},
			},
		})
		if err != nil {
			return c.JSON(http.StatusBadRequest, map[string]string{"errMessage": err.Error()})
		}

		return c.JSON(http.StatusOK, response)
	})

	e.Logger.Fatal(e.Start(":3000"))
}

About

OpenAI API GO library 📖

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages