api_func_llm.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package route
  2. import (
  3. "context"
  4. "database/sql"
  5. "log"
  6. "opennamu/route/tool"
  7. "github.com/google/generative-ai-go/genai"
  8. jsoniter "github.com/json-iterator/go"
  9. "google.golang.org/api/option"
  10. )
  11. func Api_func_llm(call_arg []string) string {
  12. var json = jsoniter.ConfigCompatibleWithStandardLibrary
  13. other_set := map[string]string{}
  14. json.Unmarshal([]byte(call_arg[0]), &other_set)
  15. db := tool.DB_connect()
  16. defer db.Close()
  17. var api_key string
  18. stmt, err := db.Prepare(tool.DB_change("select data from user_set where name = 'llm_api_key' and id = ?"))
  19. if err != nil {
  20. log.Fatal(err)
  21. }
  22. defer stmt.Close()
  23. err = stmt.QueryRow(other_set["ip"]).Scan(api_key)
  24. if err != nil {
  25. if err == sql.ErrNoRows {
  26. api_key = ""
  27. } else {
  28. log.Fatal(err)
  29. }
  30. }
  31. ctx := context.Background()
  32. client, err := genai.NewClient(ctx, option.WithAPIKey(api_key))
  33. if err != nil {
  34. log.Fatal(err)
  35. }
  36. defer client.Close()
  37. model := client.GenerativeModel("gemini-pro")
  38. resp, err := model.GenerateContent(ctx, genai.Text(other_set["prompt"]))
  39. if err != nil {
  40. log.Fatal(err)
  41. }
  42. text := resp.Candidates[0].Content.Parts[0]
  43. json_data, _ := json.Marshal(map[string]genai.Part{"data": text})
  44. return string(json_data)
  45. }