text_completion.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package openai
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. )
  10. type TextCompletionChoice struct {
  11. Text string `json:"text"`
  12. }
  13. type TextCompletionResponse struct {
  14. Error any `json:"error"`
  15. Model string `json:"model"`
  16. Choices []TextCompletionChoice `json:"choices"`
  17. }
  18. func PostTextCompletion(prompt string, apiKey string, apiHost string) (string, error) {
  19. if apiHost == "" {
  20. apiHost = "https://api.openai.com"
  21. }
  22. url, err := url.JoinPath(apiHost, "/v1/chat/completions")
  23. if err != nil {
  24. return "", err
  25. }
  26. values := map[string]any{
  27. "model": "gpt-3.5-turbo",
  28. "prompt": prompt,
  29. "temperature": 0.5,
  30. "max_tokens": 100,
  31. "n": 1,
  32. "stop": ".",
  33. }
  34. jsonValue, err := json.Marshal(values)
  35. if err != nil {
  36. return "", err
  37. }
  38. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonValue))
  39. if err != nil {
  40. return "", err
  41. }
  42. // Set the API key in the request header
  43. req.Header.Set("Content-Type", "application/json")
  44. req.Header.Set("Authorization", "Bearer "+apiKey)
  45. // Send the request to OpenAI's API
  46. client := http.Client{}
  47. resp, err := client.Do(req)
  48. if err != nil {
  49. return "", err
  50. }
  51. defer resp.Body.Close()
  52. // Read the response body
  53. responseBody, err := io.ReadAll(resp.Body)
  54. if err != nil {
  55. return "", err
  56. }
  57. textCompletionResponse := TextCompletionResponse{}
  58. err = json.Unmarshal(responseBody, &textCompletionResponse)
  59. if err != nil {
  60. return "", err
  61. }
  62. if textCompletionResponse.Error != nil {
  63. errorBytes, err := json.Marshal(textCompletionResponse.Error)
  64. if err != nil {
  65. return "", err
  66. }
  67. return "", errors.New(string(errorBytes))
  68. }
  69. if len(textCompletionResponse.Choices) == 0 {
  70. return "", nil
  71. }
  72. return textCompletionResponse.Choices[0].Text, nil
  73. }