mirror of
https://github.com/googleapis/genai-toolbox.git
synced 2026-02-08 14:15:36 -05:00
Logging support 4 different types of logging (debug, info, warn, error).
The default logging level is Info.
User will be able to set flag for log level (allowed values: "debug",
"info", "warn", "error"), example:
`go run . --log-level debug`
User will be able to set flag for logging format (allowed values:
"standard", "JSON"), example:
`go run . --logging-format json`
**sample http request log - std:**
server
```
2024-11-12T15:08:11.451377-08:00 INFO "Initalized 0 sources.\n"
```
httplog
```
2024-11-26T15:15:53.947287-08:00 INFO Response: 200 OK service: "httplog" httpRequest: {url: "http://127.0.0.1:5000/" method: "GET" path: "/" remoteIP: "127.0.0.1:64216" proto: "HTTP/1.1" requestID: "macbookpro.roam.interna/..." scheme: "http" header: {user-agent: "curl/8.7.1" accept: "*/*"}} httpResponse: {status: 200 bytes: 22 elapsed: 0.012417}
```
**sample http request log - structured:**
server
```
{
"timestamp":"2024-11-04T16:45:11.987299-08:00",
"severity":"ERROR",
"logging.googleapis.com/sourceLocation":{
"function":"github.com/googleapis/genai-toolbox/internal/log.(*StructuredLogger).Errorf",
"file":"/Users/yuanteoh/github/genai-toolbox/internal/log/log.go","line":157
},
"message":"unable to parse tool file at \"tools.yaml\": \"cloud-sql-postgres1\" is not a valid kind of data source"
}
```
httplog
```
{
"timestamp":"2024-11-26T15:12:49.290974-08:00",
"severity":"INFO",
"logging.googleapis.com/sourceLocation":{
"function":"github.com/go-chi/httplog/v2.(*RequestLoggerEntry).Write",
"file":"/Users/yuanteoh/go/pkg/mod/github.com/go-chi/httplog/v2@v2.1.1/httplog.go","line":173
},
"message":"Response: 200 OK",
"service":"httplog",
"httpRequest":{
"url":"http://127.0.0.1:5000/",
"method":"GET",
"path":"/",
"remoteIP":"127.0.0.1:64140",
"proto":"HTTP/1.1",
"requestID":"yuanteoh-macbookpro.roam.internal/NBrtYBu3q9-000001",
"scheme":"http",
"header":{"user-agent":"curl/8.7.1","accept":"*/*"}
},
"httpResponse":{"status":200,"bytes":22,"elapsed":0.0115}
}
```
152 lines
4.9 KiB
Go
152 lines
4.9 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"
|
|
"github.com/googleapis/genai-toolbox/internal/tools"
|
|
)
|
|
|
|
// apiRouter creates a router that represents the routes under /api
|
|
func apiRouter(s *Server) (chi.Router, error) {
|
|
r := chi.NewRouter()
|
|
|
|
r.Use(middleware.AllowContentType("application/json"))
|
|
r.Use(middleware.StripSlashes)
|
|
r.Use(render.SetContentType(render.ContentTypeJSON))
|
|
|
|
r.Get("/toolset", func(w http.ResponseWriter, r *http.Request) { toolsetHandler(s, w, r) })
|
|
r.Get("/toolset/{toolsetName}", func(w http.ResponseWriter, r *http.Request) { toolsetHandler(s, w, r) })
|
|
|
|
r.Route("/tool/{toolName}", func(r chi.Router) {
|
|
r.Get("/", func(w http.ResponseWriter, r *http.Request) { toolGetHandler(s, w, r) })
|
|
r.Post("/invoke", func(w http.ResponseWriter, r *http.Request) { toolInvokeHandler(s, w, r) })
|
|
})
|
|
|
|
return r, nil
|
|
}
|
|
|
|
// toolInvokeHandler handles the request for information about a Toolset.
|
|
func toolsetHandler(s *Server, w http.ResponseWriter, r *http.Request) {
|
|
toolsetName := chi.URLParam(r, "toolsetName")
|
|
toolset, ok := s.toolsets[toolsetName]
|
|
if !ok {
|
|
err := fmt.Errorf("Toolset %q does not exist", toolsetName)
|
|
_ = render.Render(w, r, newErrResponse(err, http.StatusNotFound))
|
|
return
|
|
}
|
|
render.JSON(w, r, toolset.Manifest)
|
|
}
|
|
|
|
// toolGetHandler handles requests for a single Tool.
|
|
func toolGetHandler(s *Server, w http.ResponseWriter, r *http.Request) {
|
|
toolName := chi.URLParam(r, "toolName")
|
|
tool, ok := s.tools[toolName]
|
|
if !ok {
|
|
err := fmt.Errorf("invalid tool name: tool with name %q does not exist", toolName)
|
|
_ = render.Render(w, r, newErrResponse(err, http.StatusNotFound))
|
|
return
|
|
}
|
|
// TODO: this can be optimized later with some caching
|
|
m := tools.ToolsetManifest{
|
|
ServerVersion: s.conf.Version,
|
|
ToolsManifest: map[string]tools.Manifest{
|
|
toolName: tool.Manifest(),
|
|
},
|
|
}
|
|
|
|
render.JSON(w, r, m)
|
|
}
|
|
|
|
// toolInvokeHandler handles the API request to invoke a specific Tool.
|
|
func toolInvokeHandler(s *Server, w http.ResponseWriter, r *http.Request) {
|
|
toolName := chi.URLParam(r, "toolName")
|
|
tool, ok := s.tools[toolName]
|
|
if !ok {
|
|
err := fmt.Errorf("invalid tool name: tool with name %q does not exist", toolName)
|
|
_ = render.Render(w, r, newErrResponse(err, http.StatusNotFound))
|
|
return
|
|
}
|
|
|
|
var data map[string]interface{}
|
|
if err := render.DecodeJSON(r.Body, &data); err != nil {
|
|
render.Status(r, http.StatusBadRequest)
|
|
err := fmt.Errorf("request body was invalid JSON: %w", err)
|
|
_ = render.Render(w, r, newErrResponse(err, http.StatusBadRequest))
|
|
return
|
|
}
|
|
|
|
params, err := tool.ParseParams(data)
|
|
if err != nil {
|
|
err := fmt.Errorf("provided parameters were invalid: %w", err)
|
|
_ = render.Render(w, r, newErrResponse(err, http.StatusBadRequest))
|
|
return
|
|
}
|
|
|
|
res, err := tool.Invoke(params)
|
|
if err != nil {
|
|
err := fmt.Errorf("error while invoking tool: %w", err)
|
|
_ = render.Render(w, r, newErrResponse(err, http.StatusInternalServerError))
|
|
return
|
|
}
|
|
|
|
_ = render.Render(w, r, &resultResponse{Result: res})
|
|
}
|
|
|
|
var _ render.Renderer = &resultResponse{} // Renderer interface for managing response payloads.
|
|
|
|
// resultResponse is the response sent back when the tool was invocated successfully.
|
|
type resultResponse struct {
|
|
Result string `json:"result"` // result of tool invocation
|
|
}
|
|
|
|
// Render renders a single payload and respond to the client request.
|
|
func (rr resultResponse) Render(w http.ResponseWriter, r *http.Request) error {
|
|
render.Status(r, http.StatusOK)
|
|
return nil
|
|
}
|
|
|
|
var _ render.Renderer = &errResponse{} // Renderer interface for managing response payloads.
|
|
|
|
// newErrResponse is a helper function initalizing an ErrResponse
|
|
func newErrResponse(err error, code int) *errResponse {
|
|
return &errResponse{
|
|
Err: err,
|
|
HTTPStatusCode: code,
|
|
|
|
StatusText: http.StatusText(code),
|
|
ErrorText: err.Error(),
|
|
}
|
|
}
|
|
|
|
// errResponse is the response sent back when an error has been encountered.
|
|
type errResponse struct {
|
|
Err error `json:"-"` // low-level runtime error
|
|
HTTPStatusCode int `json:"-"` // http response status code
|
|
|
|
StatusText string `json:"status"` // user-level status message
|
|
ErrorText string `json:"error,omitempty"` // application-level error message, for debugging
|
|
}
|
|
|
|
func (e *errResponse) Render(w http.ResponseWriter, r *http.Request) error {
|
|
render.Status(r, e.HTTPStatusCode)
|
|
return nil
|
|
}
|