Files
genai-toolbox/internal/server/api.go
Kurtis Van Gent 27edd3b5f6 feat: add preliminary parsing of parameters (#13)
This PR adds preliminary parsing of parameters. Currently it only
supports 4 types: string, int, float32, and bool. Almost certainly we
will need to introduce more complicated parsing configuration (to handle
objects and arrays), but my initial attempts got quickly complicated, so
I simplified in the short term.

This also makes 2 breaking changes to config.yaml:
- changes "parameters" to be a list over object -- this is because
parameter ordering is important, and needs to be preserved
- removed the "required" field from parameter objects -- we need to
determine how to handle optional parameters in SQL queries
2024-10-08 15:18:49 -06:00

79 lines
2.1 KiB
Go

// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
)
// apiRouter creates a router that represents the routes under /api
func apiRouter(s *Server) chi.Router {
r := chi.NewRouter()
r.Get("/toolset/{toolsetName}", toolsetHandler(s))
r.Route("/tool/{toolName}", func(r chi.Router) {
r.Use(middleware.AllowContentType("application/json"))
r.Post("/", toolHandler(s))
})
return r
}
func toolsetHandler(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
toolsetName := chi.URLParam(r, "toolsetName")
_, _ = w.Write([]byte(fmt.Sprintf("Stub for toolset %s manifest!", toolsetName)))
}
}
func toolHandler(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
toolName := chi.URLParam(r, "toolName")
tool, ok := s.tools[toolName]
if !ok {
render.Status(r, http.StatusInternalServerError)
_, _ = w.Write([]byte(fmt.Sprintf("Tool %q does not exist", toolName)))
return
}
var data map[string]interface{}
if err := render.DecodeJSON(r.Body, &data); err != nil {
render.Status(r, http.StatusBadRequest)
return
}
params, err := tool.ParseParams(data)
if err != nil {
render.Status(r, http.StatusBadRequest)
// TODO: More robust error formatting (probably JSON)
render.PlainText(w, r, err.Error())
return
}
res, err := tool.Invoke(params)
if err != nil {
render.Status(r, http.StatusInternalServerError)
return
}
_, _ = w.Write([]byte(fmt.Sprintf("Tool Result: %s", res)))
}
}