Enha: add openrouter parser
This commit is contained in:
@ -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
|
||||
}
|
||||
|
Reference in New Issue
Block a user