Enha: add openrouter parser

This commit is contained in:
Grail Finder
2025-06-23 12:05:20 +03:00
parent c085e0dca1
commit 840b85887b
3 changed files with 125 additions and 55 deletions

View File

@ -88,3 +88,40 @@ func (p *lcpRespParser) ParseBytes(body []byte) (map[string]any, error) {
}
return respMap, nil
}
type openRouterParser struct {
log *slog.Logger
}
func NewOpenRouterParser(log *slog.Logger) *openRouterParser {
return &openRouterParser{log: log}
}
func (p *openRouterParser) ParseBytes(body []byte) (map[string]any, error) {
// parsing logic here
resp := OpenRouterResp{}
if err := json.Unmarshal(body, &resp); err != nil {
p.log.Error("failed to unmarshal", "error", err)
return nil, err
}
if len(resp.Choices) == 0 {
p.log.Error("empty choices", "resp", resp)
err := errors.New("empty choices in resp")
return nil, err
}
text := resp.Choices[0].Message.Content
li := strings.Index(text, "{")
ri := strings.LastIndex(text, "}")
if li < 0 || ri < 1 {
p.log.Error("not a json", "msg", text)
err := fmt.Errorf("fn: ParseBytes, not a json; data: %s", text)
return nil, err
}
sj := text[li : ri+1]
respMap := make(map[string]any)
if err := json.Unmarshal([]byte(sj), &respMap); err != nil {
p.log.Error("failed to unmarshal response", "error", err, "string-json", sj)
return nil, err
}
return respMap, nil
}