|
| 1 | +package anthropic |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + |
| 6 | + "github.com/fasthttp/router" |
| 7 | + bifrost "github.com/maximhq/bifrost/core" |
| 8 | + "github.com/maximhq/bifrost/transports/bifrost-http/lib" |
| 9 | + "github.com/valyala/fasthttp" |
| 10 | +) |
| 11 | + |
| 12 | +// AnthropicRouter holds route registrations for Anthropic endpoints. |
| 13 | +type AnthropicRouter struct { |
| 14 | + client *bifrost.Bifrost |
| 15 | +} |
| 16 | + |
| 17 | +// NewAnthropicRouter creates a new AnthropicRouter with the given bifrost client. |
| 18 | +func NewAnthropicRouter(client *bifrost.Bifrost) *AnthropicRouter { |
| 19 | + return &AnthropicRouter{client: client} |
| 20 | +} |
| 21 | + |
| 22 | +// RegisterRoutes registers all Anthropic routes on the given router. |
| 23 | +func (a *AnthropicRouter) RegisterRoutes(r *router.Router) { |
| 24 | + r.POST("/anthropic/v1/messages", a.handleMessages) |
| 25 | +} |
| 26 | + |
| 27 | +// handleMessages handles POST /v1/messages |
| 28 | +func (a *AnthropicRouter) handleMessages(ctx *fasthttp.RequestCtx) { |
| 29 | + var req AnthropicMessageRequest |
| 30 | + if err := json.Unmarshal(ctx.PostBody(), &req); err != nil { |
| 31 | + ctx.SetStatusCode(fasthttp.StatusBadRequest) |
| 32 | + ctx.SetContentType("application/json") |
| 33 | + errResponse := map[string]string{"error": err.Error()} |
| 34 | + jsonBytes, _ := json.Marshal(errResponse) |
| 35 | + ctx.SetBody(jsonBytes) |
| 36 | + return |
| 37 | + } |
| 38 | + |
| 39 | + if req.Model == "" { |
| 40 | + ctx.SetStatusCode(fasthttp.StatusBadRequest) |
| 41 | + ctx.SetBodyString("Model parameter is required") |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + bifrostReq := req.ConvertToBifrostRequest() |
| 46 | + |
| 47 | + bifrostCtx := lib.ConvertToBifrostContext(ctx) |
| 48 | + |
| 49 | + result, err := a.client.ChatCompletionRequest(*bifrostCtx, bifrostReq) |
| 50 | + if err != nil { |
| 51 | + ctx.SetStatusCode(fasthttp.StatusInternalServerError) |
| 52 | + ctx.SetContentType("application/json") |
| 53 | + jsonBytes, _ := json.Marshal(err) |
| 54 | + ctx.SetBody(jsonBytes) |
| 55 | + return |
| 56 | + } |
| 57 | + |
| 58 | + anthropicResponse := DeriveAnthropicFromBifrostResponse(result) |
| 59 | + ctx.SetStatusCode(fasthttp.StatusOK) |
| 60 | + ctx.SetContentType("application/json") |
| 61 | + jsonBytes, _ := json.Marshal(anthropicResponse) |
| 62 | + ctx.SetBody(jsonBytes) |
| 63 | +} |
0 commit comments