Skip to content

Commit c6f3a10

Browse files
authored
Merge branch 'sashabaranov:master' into master
2 parents fddc507 + 2a0ff5a commit c6f3a10

28 files changed

+991
-181
lines changed

.gitignore

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,7 @@
1616

1717
# Auth token for tests
1818
.openai-token
19-
.idea
19+
.idea
20+
21+
# Generated by tests
22+
test.mp3

.golangci.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ linters-settings:
5757
# Default: true
5858
skipRecvDeref: false
5959

60-
gomnd:
60+
mnd:
6161
# List of function patterns to exclude from analysis.
6262
# Values always ignored: `time.Date`
6363
# Default: []
@@ -167,7 +167,7 @@ linters:
167167
- durationcheck # check for two durations multiplied together
168168
- errname # Checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error.
169169
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
170-
- execinquery # execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds
170+
# Removed execinquery (deprecated). execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds
171171
- exhaustive # check exhaustiveness of enum switch statements
172172
- exportloopref # checks for pointers to enclosing loop variables
173173
- forbidigo # Forbids identifiers
@@ -180,14 +180,14 @@ linters:
180180
- gocyclo # Computes and checks the cyclomatic complexity of functions
181181
- godot # Check if comments end in a period
182182
- goimports # In addition to fixing imports, goimports also formats your code in the same style as gofmt.
183-
- gomnd # An analyzer to detect magic numbers.
184183
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
185184
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
186185
- goprintffuncname # Checks that printf-like functions are named with f at the end
187186
- gosec # Inspects source code for security problems
188187
- lll # Reports long lines
189188
- makezero # Finds slice declarations with non-zero initial length
190189
# - nakedret # Finds naked returns in functions greater than a specified function length
190+
- mnd # An analyzer to detect magic numbers.
191191
- nestif # Reports deeply nested if statements
192192
- nilerr # Finds the code that returns nil even if it checks that the error is not nil.
193193
- nilnil # Checks that there is no simultaneous return of nil error and an invalid value.

Makefile

Lines changed: 0 additions & 35 deletions
This file was deleted.

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
This library provides unofficial Go clients for [OpenAI API](https://platform.openai.com/). We support:
77

8-
* ChatGPT
8+
* ChatGPT 4o, o1
99
* GPT-3, GPT-4
1010
* DALL·E 2, DALL·E 3
1111
* Whisper

assistant.go

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,20 @@ const (
1414
)
1515

1616
type Assistant struct {
17-
ID string `json:"id"`
18-
Object string `json:"object"`
19-
CreatedAt int64 `json:"created_at"`
20-
Name *string `json:"name,omitempty"`
21-
Description *string `json:"description,omitempty"`
22-
Model string `json:"model"`
23-
Instructions *string `json:"instructions,omitempty"`
24-
Tools []AssistantTool `json:"tools"`
25-
FileIDs []string `json:"file_ids,omitempty"`
26-
Metadata map[string]any `json:"metadata,omitempty"`
27-
ToolResources *AssistantToolResource `json:"tool_resources,omitempty"`
17+
ID string `json:"id"`
18+
Object string `json:"object"`
19+
CreatedAt int64 `json:"created_at"`
20+
Name *string `json:"name,omitempty"`
21+
Description *string `json:"description,omitempty"`
22+
Model string `json:"model"`
23+
Instructions *string `json:"instructions,omitempty"`
24+
Tools []AssistantTool `json:"tools"`
25+
ToolResources *AssistantToolResource `json:"tool_resources,omitempty"`
26+
FileIDs []string `json:"file_ids,omitempty"` // Deprecated in v2
27+
Metadata map[string]any `json:"metadata,omitempty"`
28+
Temperature *float32 `json:"temperature,omitempty"`
29+
TopP *float32 `json:"top_p,omitempty"`
30+
ResponseFormat any `json:"response_format,omitempty"`
2831

2932
httpHeader
3033
}

batch_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ func TestUploadBatchFileRequest_AddEmbedding(t *testing.T) {
211211
Input: []string{"Hello", "World"},
212212
},
213213
},
214-
}, []byte("{\"custom_id\":\"req-1\",\"body\":{\"input\":[\"Hello\",\"World\"],\"model\":\"gpt-3.5-turbo\",\"user\":\"\"},\"method\":\"POST\",\"url\":\"/v1/embeddings\"}\n{\"custom_id\":\"req-2\",\"body\":{\"input\":[\"Hello\",\"World\"],\"model\":\"text-embedding-ada-002\",\"user\":\"\"},\"method\":\"POST\",\"url\":\"/v1/embeddings\"}")}, //nolint:lll
214+
}, []byte("{\"custom_id\":\"req-1\",\"body\":{\"input\":[\"Hello\",\"World\"],\"model\":\"gpt-3.5-turbo\"},\"method\":\"POST\",\"url\":\"/v1/embeddings\"}\n{\"custom_id\":\"req-2\",\"body\":{\"input\":[\"Hello\",\"World\"],\"model\":\"text-embedding-ada-002\"},\"method\":\"POST\",\"url\":\"/v1/embeddings\"}")}, //nolint:lll
215215
}
216216
for _, tt := range tests {
217217
t.Run(tt.name, func(t *testing.T) {

chat.go

Lines changed: 63 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,23 @@ type Violence struct {
4141
Severity string `json:"severity,omitempty"`
4242
}
4343

44+
type JailBreak struct {
45+
Filtered bool `json:"filtered"`
46+
Detected bool `json:"detected"`
47+
}
48+
49+
type Profanity struct {
50+
Filtered bool `json:"filtered"`
51+
Detected bool `json:"detected"`
52+
}
53+
4454
type ContentFilterResults struct {
45-
Hate Hate `json:"hate,omitempty"`
46-
SelfHarm SelfHarm `json:"self_harm,omitempty"`
47-
Sexual Sexual `json:"sexual,omitempty"`
48-
Violence Violence `json:"violence,omitempty"`
55+
Hate Hate `json:"hate,omitempty"`
56+
SelfHarm SelfHarm `json:"self_harm,omitempty"`
57+
Sexual Sexual `json:"sexual,omitempty"`
58+
Violence Violence `json:"violence,omitempty"`
59+
JailBreak JailBreak `json:"jailbreak,omitempty"`
60+
Profanity Profanity `json:"profanity,omitempty"`
4961
}
5062

5163
type PromptAnnotation struct {
@@ -82,6 +94,7 @@ type ChatMessagePart struct {
8294
type ChatCompletionMessage struct {
8395
Role string `json:"role"`
8496
Content string `json:"content"`
97+
Refusal string `json:"refusal,omitempty"`
8598
MultiContent []ChatMessagePart
8699

87100
// This property isn't in the official documentation, but it's in
@@ -107,6 +120,7 @@ func (m ChatCompletionMessage) MarshalJSON() ([]byte, error) {
107120
msg := struct {
108121
Role string `json:"role"`
109122
Content string `json:"-"`
123+
Refusal string `json:"refusal,omitempty"`
110124
MultiContent []ChatMessagePart `json:"content,omitempty"`
111125
Name string `json:"name,omitempty"`
112126
FunctionCall *FunctionCall `json:"function_call,omitempty"`
@@ -115,9 +129,11 @@ func (m ChatCompletionMessage) MarshalJSON() ([]byte, error) {
115129
}(m)
116130
return json.Marshal(msg)
117131
}
132+
118133
msg := struct {
119134
Role string `json:"role"`
120135
Content string `json:"content"`
136+
Refusal string `json:"refusal,omitempty"`
121137
MultiContent []ChatMessagePart `json:"-"`
122138
Name string `json:"name,omitempty"`
123139
FunctionCall *FunctionCall `json:"function_call,omitempty"`
@@ -131,19 +147,22 @@ func (m *ChatCompletionMessage) UnmarshalJSON(bs []byte) error {
131147
msg := struct {
132148
Role string `json:"role"`
133149
Content string `json:"content"`
150+
Refusal string `json:"refusal,omitempty"`
134151
MultiContent []ChatMessagePart
135152
Name string `json:"name,omitempty"`
136153
FunctionCall *FunctionCall `json:"function_call,omitempty"`
137154
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
138155
ToolCallID string `json:"tool_call_id,omitempty"`
139156
}{}
157+
140158
if err := json.Unmarshal(bs, &msg); err == nil {
141159
*m = ChatCompletionMessage(msg)
142160
return nil
143161
}
144162
multiMsg := struct {
145163
Role string `json:"role"`
146164
Content string
165+
Refusal string `json:"refusal,omitempty"`
147166
MultiContent []ChatMessagePart `json:"content"`
148167
Name string `json:"name,omitempty"`
149168
FunctionCall *FunctionCall `json:"function_call,omitempty"`
@@ -160,7 +179,7 @@ func (m *ChatCompletionMessage) UnmarshalJSON(bs []byte) error {
160179
type ToolCall struct {
161180
// Index is not nil only in chat completion chunk object
162181
Index *int `json:"index,omitempty"`
163-
ID string `json:"id"`
182+
ID string `json:"id,omitempty"`
164183
Type ToolType `json:"type"`
165184
Function FunctionCall `json:"function"`
166185
}
@@ -193,18 +212,25 @@ type ChatCompletionResponseFormatJSONSchema struct {
193212

194213
// ChatCompletionRequest represents a request structure for chat completion API.
195214
type ChatCompletionRequest struct {
196-
Model string `json:"model"`
197-
Messages []ChatCompletionMessage `json:"messages"`
198-
MaxTokens int `json:"max_tokens,omitempty"`
199-
Temperature float32 `json:"temperature,omitempty"`
200-
TopP float32 `json:"top_p,omitempty"`
201-
N int `json:"n,omitempty"`
202-
Stream bool `json:"stream,omitempty"`
203-
Stop []string `json:"stop,omitempty"`
204-
PresencePenalty float32 `json:"presence_penalty,omitempty"`
205-
ResponseFormat *ChatCompletionResponseFormat `json:"response_format,omitempty"`
206-
Seed *int `json:"seed,omitempty"`
207-
FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
215+
Model string `json:"model"`
216+
Messages []ChatCompletionMessage `json:"messages"`
217+
// MaxTokens The maximum number of tokens that can be generated in the chat completion.
218+
// This value can be used to control costs for text generated via API.
219+
// This value is now deprecated in favor of max_completion_tokens, and is not compatible with o1 series models.
220+
// refs: https://platform.openai.com/docs/api-reference/chat/create#chat-create-max_tokens
221+
MaxTokens int `json:"max_tokens,omitempty"`
222+
// MaxCompletionTokens An upper bound for the number of tokens that can be generated for a completion,
223+
// including visible output tokens and reasoning tokens https://platform.openai.com/docs/guides/reasoning
224+
MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
225+
Temperature float32 `json:"temperature,omitempty"`
226+
TopP float32 `json:"top_p,omitempty"`
227+
N int `json:"n,omitempty"`
228+
Stream bool `json:"stream,omitempty"`
229+
Stop []string `json:"stop,omitempty"`
230+
PresencePenalty float32 `json:"presence_penalty,omitempty"`
231+
ResponseFormat *ChatCompletionResponseFormat `json:"response_format,omitempty"`
232+
Seed *int `json:"seed,omitempty"`
233+
FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
208234
// LogitBias is must be a token id string (specified by their token ID in the tokenizer), not a word string.
209235
// incorrect: `"logit_bias":{"You": 6}`, correct: `"logit_bias":{"1639": 6}`
210236
// refs: https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias
@@ -229,6 +255,11 @@ type ChatCompletionRequest struct {
229255
StreamOptions *StreamOptions `json:"stream_options,omitempty"`
230256
// Disable the default behavior of parallel tool calls by setting it: false.
231257
ParallelToolCalls any `json:"parallel_tool_calls,omitempty"`
258+
// Store can be set to true to store the output of this completion request for use in distillations and evals.
259+
// https://platform.openai.com/docs/api-reference/chat/create#chat-create-store
260+
Store bool `json:"store,omitempty"`
261+
// Metadata to store with the completion.
262+
Metadata map[string]string `json:"metadata,omitempty"`
232263
}
233264

234265
type StreamOptions struct {
@@ -324,19 +355,21 @@ type ChatCompletionChoice struct {
324355
// function_call: The model decided to call a function
325356
// content_filter: Omitted content due to a flag from our content filters
326357
// null: API response still in progress or incomplete
327-
FinishReason FinishReason `json:"finish_reason"`
328-
LogProbs *LogProbs `json:"logprobs,omitempty"`
358+
FinishReason FinishReason `json:"finish_reason"`
359+
LogProbs *LogProbs `json:"logprobs,omitempty"`
360+
ContentFilterResults ContentFilterResults `json:"content_filter_results,omitempty"`
329361
}
330362

331363
// ChatCompletionResponse represents a response structure for chat completion API.
332364
type ChatCompletionResponse struct {
333-
ID string `json:"id"`
334-
Object string `json:"object"`
335-
Created int64 `json:"created"`
336-
Model string `json:"model"`
337-
Choices []ChatCompletionChoice `json:"choices"`
338-
Usage Usage `json:"usage"`
339-
SystemFingerprint string `json:"system_fingerprint"`
365+
ID string `json:"id"`
366+
Object string `json:"object"`
367+
Created int64 `json:"created"`
368+
Model string `json:"model"`
369+
Choices []ChatCompletionChoice `json:"choices"`
370+
Usage Usage `json:"usage"`
371+
SystemFingerprint string `json:"system_fingerprint"`
372+
PromptFilterResults []PromptFilterResult `json:"prompt_filter_results,omitempty"`
340373

341374
httpHeader
342375
}
@@ -357,6 +390,10 @@ func (c *Client) CreateChatCompletion(
357390
return
358391
}
359392

393+
if err = validateRequestForO1Models(request); err != nil {
394+
return
395+
}
396+
360397
req, err := c.newRequest(
361398
ctx,
362399
http.MethodPost,

chat_stream.go

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,33 @@ type ChatCompletionStreamChoiceDelta struct {
1010
Role string `json:"role,omitempty"`
1111
FunctionCall *FunctionCall `json:"function_call,omitempty"`
1212
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
13+
Refusal string `json:"refusal,omitempty"`
14+
}
15+
16+
type ChatCompletionStreamChoiceLogprobs struct {
17+
Content []ChatCompletionTokenLogprob `json:"content,omitempty"`
18+
Refusal []ChatCompletionTokenLogprob `json:"refusal,omitempty"`
19+
}
20+
21+
type ChatCompletionTokenLogprob struct {
22+
Token string `json:"token"`
23+
Bytes []int64 `json:"bytes,omitempty"`
24+
Logprob float64 `json:"logprob,omitempty"`
25+
TopLogprobs []ChatCompletionTokenLogprobTopLogprob `json:"top_logprobs"`
26+
}
27+
28+
type ChatCompletionTokenLogprobTopLogprob struct {
29+
Token string `json:"token"`
30+
Bytes []int64 `json:"bytes"`
31+
Logprob float64 `json:"logprob"`
1332
}
1433

1534
type ChatCompletionStreamChoice struct {
16-
Index int `json:"index"`
17-
Delta ChatCompletionStreamChoiceDelta `json:"delta"`
18-
FinishReason FinishReason `json:"finish_reason"`
19-
ContentFilterResults ContentFilterResults `json:"content_filter_results,omitempty"`
35+
Index int `json:"index"`
36+
Delta ChatCompletionStreamChoiceDelta `json:"delta"`
37+
Logprobs *ChatCompletionStreamChoiceLogprobs `json:"logprobs,omitempty"`
38+
FinishReason FinishReason `json:"finish_reason"`
39+
ContentFilterResults ContentFilterResults `json:"content_filter_results,omitempty"`
2040
}
2141

2242
type PromptFilterResult struct {
@@ -60,6 +80,10 @@ func (c *Client) CreateChatCompletionStream(
6080
}
6181

6282
request.Stream = true
83+
if err = validateRequestForO1Models(request); err != nil {
84+
return
85+
}
86+
6387
req, err := c.newRequest(
6488
ctx,
6589
http.MethodPost,

0 commit comments

Comments
 (0)