Skip to content

Commit

Permalink
(refactor): clean up the code for calling the api
Browse files Browse the repository at this point in the history
  • Loading branch information
tearingItUp786 committed Mar 13, 2024
1 parent 0c7391f commit ced3991
Showing 1 changed file with 57 additions and 61 deletions.
118 changes: 57 additions & 61 deletions sessions/message-stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,81 +83,77 @@ func (m Model) constructJsonBody() ([]byte, error) {
return body, nil
}

func (m *Model) CallChatGpt(resultChan chan ProcessResult) tea.Cmd {
apiKey := os.Getenv("OPENAI_API_KEY")
processResultID := 0 // Initialize a counter for ProcessResult IDs
func (m *Model) callChatGptAPI(apiKey string, body []byte) (*http.Response, error) {
req, err := http.NewRequest("POST", m.config.ChatGPTApiUrl, bytes.NewBuffer(body))
if err != nil {
return nil, err
}

return func() tea.Msg {
body, err := m.constructJsonBody()
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))

// API endpoint to call -- should be an env variable
req, err := http.NewRequest(
"POST",
// get this url from the config
m.config.ChatGPTApiUrl,
bytes.NewBuffer(body),
)
if err != nil {
util.Log("Error creating request:", err)
resultChan <- ProcessResult{ID: processResultID, Err: err}
}
client := &http.Client{}
return client.Do(req)
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
func (m *Model) processAPIResponse(
resp *http.Response,
resultChan chan ProcessResult,
processResultID *int,
) {
defer resp.Body.Close()

client := &http.Client{}
resp, err := client.Do(req)
if resp.StatusCode >= 400 {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
resultChan <- ProcessResult{ID: processResultID, Err: err}
resultChan <- ProcessResult{ID: *processResultID, Err: err}
return
}
defer resp.Body.Close()

// any kind of error, just break out man
if resp.StatusCode >= 400 {
// Read the response body
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return util.ErrorEvent{
Message: err.Error(),
}
}
bodyString := string(bodyBytes)
resultChan <- ProcessResult{ID: *processResultID, Err: fmt.Errorf(string(bodyBytes))}
return
}

return util.ErrorEvent{
Message: bodyString,
scanner := bufio.NewReader(resp.Body)
for {
line, err := scanner.ReadString('\n')
if err != nil {
if err == io.EOF {
break // End of the stream
}
resultChan <- ProcessResult{ID: *processResultID, Err: err}
return
}

scanner := bufio.NewReader(resp.Body)

for {
line, err := scanner.ReadString('\n')
if err != nil {
if err == io.EOF {
// log.Println("end of file")
break // End of the stream
}
// TODO: proper error handler when the stream breaks
log.Fatal(err) // Handle other errors
}
if line == "data: [DONE]\n" {
resultChan <- ProcessResult{ID: *processResultID, Err: nil, Final: true}
return
}

// This should be a constant (checking to see if the stream is done)
if line == "data: [DONE]\n" {
util.Log("Stream ended with [DONE] message.")
return ProcessResult{ID: processResultID, Err: nil, Final: true}
}
if strings.HasPrefix(line, "data:") {
jsonStr := strings.TrimPrefix(line, "data:")
resultChan <- processChunk(jsonStr, *processResultID)
*processResultID++ // Increment the ID for each processed chunk
}
}
}

if strings.HasPrefix(line, "data:") {
// log.Printf("Process Array: %v", line)
jsonStr := strings.TrimPrefix(line, "data:")
// Create a channel to receive the results
// Start the goroutine, passing the channel for communication
resultChan <- processChunk(jsonStr, processResultID)
processResultID++ // Increment the ID for each processed chunk
}
func (m *Model) CallChatGpt(resultChan chan ProcessResult) tea.Cmd {
apiKey := os.Getenv("OPENAI_API_KEY")
processResultID := 0 // Initialize a counter for ProcessResult IDs

return func() tea.Msg {
body, err := m.constructJsonBody()
if err != nil {
return util.ErrorEvent{Message: err.Error()}
}

resp, err := m.callChatGptAPI(apiKey, body)
if err != nil {
return util.ErrorEvent{Message: err.Error()}
}

return ProcessResult{ID: 200, Err: nil}
m.processAPIResponse(resp, resultChan, &processResultID)
return nil // Or return a specific message indicating completion or next steps
}
}

Expand Down

0 comments on commit ced3991

Please sign in to comment.