You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

claude.go 1.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2023 The casbin Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package model
  15. import (
  16. "fmt"
  17. "io"
  18. "net/http"
  19. "strings"
  20. "github.com/madebywelch/anthropic-go/pkg/anthropic"
  21. )
  22. type ClaudeModelProvider struct {
  23. subType string
  24. secretKey string
  25. }
  26. func NewClaudeModelProvider(subType string, secretKey string) (*ClaudeModelProvider, error) {
  27. return &ClaudeModelProvider{subType: subType, secretKey: secretKey}, nil
  28. }
  29. func (p *ClaudeModelProvider) QueryText(question string, writer io.Writer, builder *strings.Builder) error {
  30. client, err := anthropic.NewClient(p.secretKey)
  31. if err != nil {
  32. panic(err)
  33. }
  34. response, _ := client.Complete(&anthropic.CompletionRequest{
  35. Prompt: anthropic.GetPrompt(question),
  36. Model: anthropic.Model(p.subType),
  37. MaxTokensToSample: 100,
  38. StopSequences: []string{"\r", "Human:"},
  39. }, nil)
  40. flusher, ok := writer.(http.Flusher)
  41. if !ok {
  42. return fmt.Errorf("writer does not implement http.Flusher")
  43. }
  44. flushData := func(data string) error {
  45. if _, err := fmt.Fprintf(writer, "event: message\ndata: %s\n\n", data); err != nil {
  46. return err
  47. }
  48. flusher.Flush()
  49. builder.WriteString(data)
  50. return nil
  51. }
  52. err = flushData(response.Completion)
  53. if err != nil {
  54. return err
  55. }
  56. return nil
  57. }