MCPcopy Index your code
hub / github.com/APIParkLab/APIPark / parseAIResponse

Function parseAIResponse

module/service/parse.go:45–95  ·  view source on GitHub ↗

ParseAIResponse parses both streaming and non-streaming AI responses and returns the concatenated content

(input string)

Source from the content-addressed store, hash-verified

43
44// ParseAIResponse parses both streaming and non-streaming AI responses and returns the concatenated content
45func parseAIResponse(input string) (string, error) {
46 // First, try to parse as a non-streaming response
47 var nonStreaming ChatCompletion
48 if err := json.Unmarshal([]byte(input), &nonStreaming); err == nil && nonStreaming.Object == "chat.completion" {
49 var result strings.Builder
50 for _, choice := range nonStreaming.Choices {
51 result.WriteString(choice.Message.Content)
52 }
53 return result.String(), nil
54 }
55
56 // If not non-streaming, parse as streaming response
57 var result strings.Builder
58 scanner := bufio.NewScanner(strings.NewReader(input))
59
60 for scanner.Scan() {
61 line := scanner.Text()
62 // Skip empty lines or [DONE]
63 if line == "" || line == "data: [DONE]" {
64 continue
65 }
66
67 // Check if line starts with "data: "
68 if !strings.HasPrefix(line, "data: ") {
69 continue
70 }
71
72 // Extract JSON data
73 jsonData := strings.TrimPrefix(line, "data: ")
74 var chunk ChatCompletionChunk
75 if err := json.Unmarshal([]byte(jsonData), &chunk); err != nil {
76 return "", err
77 }
78
79 // Process each choice
80 for _, choice := range chunk.Choices {
81 // Append content from delta
82 result.WriteString(choice.Delta.Content)
83 // Check if this is the final chunk
84 if choice.FinishReason != nil && *choice.FinishReason == "stop" {
85 return result.String(), nil
86 }
87 }
88 }
89
90 if err := scanner.Err(); err != nil {
91 return "", err
92 }
93
94 return result.String(), nil
95}
96
97func parseAIRequest(ori string) string {
98 type aiRequest struct {

Callers 1

AILogInfoMethod · 0.85

Calls 2

StringMethod · 0.45
ScanMethod · 0.45

Tested by

no test coverage detected