Skip to content

Commit

Permalink
parser
Browse files Browse the repository at this point in the history
  • Loading branch information
Gekko0114 committed Jul 8, 2024
1 parent d615b90 commit 3cc6f3b
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 2 deletions.
5 changes: 3 additions & 2 deletions pkg/main.go → examples/normal/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"golangchain/pkg/lib"
"golangchain/pkg/openai"
"golangchain/pkg/parser"
"golangchain/pkg/prompt"
)

Expand All @@ -13,9 +14,10 @@ func main() {
fmt.Println(err)
}
prompt, err := prompt.NewPromptTemplate("{{.Word}}の意味を教えて。")
parser := parser.NewStrOutputParser()

pipeline := lib.NewPipeline()
pipeline.Pipe(prompt).Pipe(llm)
pipeline.Pipe(prompt).Pipe(llm).Pipe(parser)
m := map[string]string{
"Word": "因果応報",
}
Expand All @@ -25,5 +27,4 @@ func main() {
fmt.Println(err)
}
fmt.Printf("Response: %+v\n", response)

}
23 changes: 23 additions & 0 deletions pkg/parser/stroutputparser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package parser

import (
"golangchain/pkg/openai"
)

type StrOutputParser struct {
}

func NewStrOutputParser() *StrOutputParser {
return &StrOutputParser{}
}

func (p *StrOutputParser) Invoke(input any) (any, error) {
var output string
res, ok := input.(*openai.Response)
if ok {
output = res.Choices[0].Message.Content
} else {
return nil, nil
}
return output, nil
}
36 changes: 36 additions & 0 deletions pkg/parser/stroutputparser_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package parser

import (
"golangchain/pkg/openai"
"testing"
)

func TestInvoke(t *testing.T) {
tests := []struct {
name string
input any
expected string
}{
{
name: "template is string",
input: &openai.Response{
Choices: []openai.Choice{
{Message: openai.Message{Role: "assistant", Content: "This is the test response"}},
},
},
expected: "This is the test response",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
parser := NewStrOutputParser()
have, err := parser.Invoke(tc.input)
if err != nil {
t.Fatalf("Error happens: %v", err)
}
if have != tc.expected {
t.Fatalf("unexpected string: %v != %v", have, tc.expected)
}
})
}
}

0 comments on commit 3cc6f3b

Please sign in to comment.