Files
langchain-go/backend/utils/tool.go
T

26 lines
772 B
Go
Raw Normal View History

2026-03-27 20:30:49 +08:00
package utils
import (
"encoding/json"
"fmt"
"github.com/tmc/langchaingo/outputparser"
)
// Parse parses the output of an LLM call.
func (p outputparser.Defined[T)(T) Parse(text string) (T, error) {
var target T
// Removes '```json' and '```' from the start and end of the text.
const opening = "```json"
const closing = "```"
if text[:len(opening)] != opening || text[len(text)-len(closing):] != closing {
return target, nil
// return target, fmt.Errorf("input text should start with %s and end with %s", opening, closing)
}
parseableJSON := text[len(opening) : len(text)-len(closing)]
if err := json.Unmarshal([]byte(parseableJSON), &target); err != nil {
return target, fmt.Errorf("could not parse generated JSON: %w", err)
}
return target, nil
}