forked from anhao/go-ernie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ernie_bot.go
73 lines (61 loc) · 1.94 KB
/
ernie_bot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package go_ernie
import (
"context"
"errors"
"net/http"
)
const (
MessageRoleUser = "user"
MessageRoleAssistant = "assistant"
)
var (
ErrChatCompletionStreamNotSupported = errors.New("streaming is not supported with this method, please use CreateChatCompletionStream") //nolint:lll
)
const ernieBotURL = "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions"
type ChatCompletionMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type ErnieBotRequest struct {
Messages []ChatCompletionMessage `json:"messages"`
Temperature float32 `json:"temperature,omitempty"`
TopP float32 `json:"top_p,omitempty"`
PresencePenalty float32 `json:"presence_penalty,omitempty"`
Stream bool `json:"stream"`
UserId string `json:"user_id,omitempty"`
}
type ErnieUsage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
}
type ErnieBotResponse struct {
Id string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
SentenceId int `json:"sentence_id"`
IsEnd bool `json:"is_end"`
IsTruncated bool `json:"is_truncated"`
Result string `json:"result"`
NeedClearHistory bool `json:"need_clear_history"`
Usage ErnieUsage `json:"usage"`
APIError
}
func (c *Client) CreateErnieBotChatCompletion(
ctx context.Context,
request ErnieBotRequest,
) (response ErnieBotResponse, err error) {
if request.Stream {
err = ErrChatCompletionStreamNotSupported
return
}
req, err := c.newRequest(ctx, http.MethodPost, c.fullURL(ernieBotURL), withBody(request))
if err != nil {
return
}
err = c.sendRequest(req, &response)
if response.ErrorCode != 0 {
err = &response.APIError
}
return
}