openai.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package server
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "github.com/labstack/echo/v4"
  6. "github.com/usememos/memos/api"
  7. "github.com/usememos/memos/common"
  8. "github.com/usememos/memos/plugin/openai"
  9. )
  10. func (s *Server) registerOpenAIRoutes(g *echo.Group) {
  11. g.POST("/openai/chat-completion", func(c echo.Context) error {
  12. ctx := c.Request().Context()
  13. openAIConfigSetting, err := s.Store.FindSystemSetting(ctx, &api.SystemSettingFind{
  14. Name: api.SystemSettingOpenAIConfigName,
  15. })
  16. if err != nil && common.ErrorCode(err) != common.NotFound {
  17. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find openai key").SetInternal(err)
  18. }
  19. openAIConfig := api.OpenAIConfig{}
  20. if openAIConfigSetting != nil {
  21. err = json.Unmarshal([]byte(openAIConfigSetting.Value), &openAIConfig)
  22. if err != nil {
  23. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to unmarshal openai system setting value").SetInternal(err)
  24. }
  25. }
  26. if openAIConfig.Key == "" {
  27. return echo.NewHTTPError(http.StatusBadRequest, "OpenAI API key not set")
  28. }
  29. messages := []openai.ChatCompletionMessage{}
  30. if err := json.NewDecoder(c.Request().Body).Decode(&messages); err != nil {
  31. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post chat completion request").SetInternal(err)
  32. }
  33. if len(messages) == 0 {
  34. return echo.NewHTTPError(http.StatusBadRequest, "No messages provided")
  35. }
  36. result, err := openai.PostChatCompletion(messages, openAIConfig.Key, openAIConfig.Host)
  37. if err != nil {
  38. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to post chat completion").SetInternal(err)
  39. }
  40. return c.JSON(http.StatusOK, composeResponse(result))
  41. })
  42. }