Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

merge main branch #1

Open
wants to merge 217 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
Show all changes
217 commits
Select commit Hold shift + click to select a range
be253c2
change azure engine config to modelMapper (#306)
GargantuaX May 10, 2023
83d03fc
Adjust the azure model deployment name call corresponding to README (…
zjy282 May 15, 2023
21eef5b
Move form_builder into internal pkg. (#311)
JiayueShi May 16, 2023
b62a325
Azure OpenAI API version 2023-05-15 (#316)
iktakahiro May 19, 2023
faae8b4
Update README.md (#319)
TomHennessy May 22, 2023
a18c18d
Update README.md with Azure OpenAI Embeddings example (#318)
coggsfl May 22, 2023
980504b
docs(readme): update format (#317)
appleboy May 27, 2023
62eb4be
move marshaller and unmarshaler into internal pkg (#304) (#325)
vvatanabe May 28, 2023
61ba5f3
move request_builder into internal pkg (#304) (#329)
vvatanabe May 31, 2023
fa694c6
Implement optional io.Reader in AudioRequest (#303) (#265) (#331)
mdarc Jun 5, 2023
1394329
move error_accumulator into internal pkg (#304) (#335)
vvatanabe Jun 5, 2023
6830e00
Support Retrieve model API (#340) (#341)
vvatanabe Jun 5, 2023
b8c13e4
Refactor streamReader: Replace goto Statement with Loop in Recv Metho…
YukiBobier Jun 8, 2023
06b16a7
fix json marshaling error response of azure openai (#343) (#345)
vvatanabe Jun 8, 2023
a243e73
Support Retrieve file content API (#347) (#348)
vvatanabe Jun 11, 2023
b616090
refactoring tests with mock servers (#30) (#356)
vvatanabe Jun 12, 2023
3f4e3bb
models: add *-0613 models (#361)
simonklee Jun 13, 2023
646989c
Improve (#356) to support registration of wildcard URLs (#359)
coggsfl Jun 14, 2023
7e76a68
Add 16k 0613 model (#365)
beichideyuwan Jun 14, 2023
2bd65aa
feat(chat): support function call api (#369)
Ccheers Jun 15, 2023
43de771
Create FUNDING.yml (#371)
sashabaranov Jun 15, 2023
0bd14f9
refactor: ChatCompletionStreamChoice.FinishReason from string to Fini…
liushuangls Jun 15, 2023
ac25f31
add items, which is required for array type (#373)
nftechie Jun 16, 2023
f0770cf
audio: add items to AudioResponseFormat enum (#382)
romazu Jun 16, 2023
e49d771
support for parsing error response message fields even if they are ar…
vvatanabe Jun 17, 2023
b095938
extract and split integration tests (#389)
vvatanabe Jun 18, 2023
68f9ef9
split integration test using go build tag (#392)
vvatanabe Jun 19, 2023
7203770
feat: added function call info to chat completions (#390)
cem-unuvar Jun 20, 2023
e948150
fix: chat stream returns an error response with a 'data: ' prefix (#396)
liushuangls Jun 20, 2023
f22da8a
feat: allow more input types to functions, fix tests (#377)
stillmatic Jun 21, 2023
e19b074
docs: add requires go version in README.md (#397)
vvatanabe Jun 21, 2023
ffa7abc
Update README.md (#399)
sashabaranov Jun 21, 2023
157de06
add vvatanabe to FUNDING.yml (#402)
vvatanabe Jun 22, 2023
f1b6696
refactor: refactoring http request creation and sending (#395)
vvatanabe Jun 22, 2023
5f4ef29
Update README.md (#406)
sashabaranov Jun 23, 2023
0ca4ea4
move json schema to directory/package (#407)
jmacwhyte Jun 24, 2023
a3c0b36
chore: add an issue template for feature request (#410)
vvatanabe Jun 26, 2023
581f70b
chore: add an issue template for bug report (#408)
vvatanabe Jun 26, 2023
86d0f48
chore: add a pull request template (#412)
vvatanabe Jun 28, 2023
9c99f36
replace deprecated FunctionDefine in chat_test.go (#416)
ryomak Jun 29, 2023
1efcf2d
fix: move pull request template (#420)
vvatanabe Jun 30, 2023
177c143
Fix OpenAI error when properties is empty in function call : object s…
royalrick Jun 30, 2023
2042608
docs: remove medatada in PULL_REQUEST_TEMPLATE.md (#423)
vvatanabe Jul 3, 2023
5c7d882
Allow embeddings requests to be tokens or strings (#417)
jacksors Jul 5, 2023
619ad71
docs: added instructions for obtaining OpenAI API key to README (#421)
vvatanabe Jul 5, 2023
7b22898
Implement OpenAI July 2023 Updates (#427)
liushuangls Jul 9, 2023
181fc2a
docs: explanation about LogitBias. (129) (#426)
vvatanabe Jul 9, 2023
f028c28
fix: function call error due to nil properties (429) (#431)
vvatanabe Jul 9, 2023
c3b2451
fix: invalid schema for function 'func_name': None is not of type 'ob…
vvatanabe Jul 11, 2023
39b2acb
ci: set up closing-inactive-issues in GitHub Action (129) (#428)
vvatanabe Jul 12, 2023
e22a29d
Check if the model param is valid for moderations endpoint (#437)
MunarYesen Jul 13, 2023
0234c1e
add example: fine tune (#438)
mehulgohil Jul 14, 2023
1876e0c
update to json.RawMessage (#441)
Jul 15, 2023
1153eb2
Add support for azure openai new version API (2023-07-01-preview) (#451)
ZeroDeng01 Jul 20, 2023
62dc817
feat: make finish reason nullable in json marshal (#449)
yuikns Jul 28, 2023
71a2493
docs: add Frequently Asked Questions to README.md (#462)
vvatanabe Jul 30, 2023
3456989
Compatible with the 2023-07-01-preview API interface of Azure Openai,…
ZeroDeng01 Aug 9, 2023
a14bc10
docs: Add Contributing Guidelines (#463)
vvatanabe Aug 9, 2023
a2ca01b
feat: implement new fine tuning job API (#479)
henomis Aug 29, 2023
25da859
Chore Deprecate legacy fine tunes API (#484)
henomis Aug 31, 2023
3589837
Update OpenAPI file return struct (#486)
NullpointerW Sep 7, 2023
8e4b796
Chore Support base64 embedding format (#485)
henomis Sep 11, 2023
0d5256f
added delete fine tune model endpoint (#497)
BrendanMartin Sep 25, 2023
84f77a0
Add DotProduct Method and README Example for Embedding Similarity Sea…
ealvar3z Oct 2, 2023
533935e
fix: use any for n_epochs (#499)
henomis Oct 6, 2023
8e165dc
Feat Add headers to openai responses (#506)
henomis Oct 9, 2023
b77d01e
Support get http header and x-ratelimit-* headers (#507)
liushuangls Oct 10, 2023
c47ddfc
Update README.md (#511)
sashabaranov Oct 10, 2023
6c52952
feat(completion): add constants for new GPT models (#520)
simonklee Nov 6, 2023
9e0232f
Fix typo in README: AdaEmbeddingV2 (#516)
eliben Nov 6, 2023
0664105
lint: fix linter warnings reported by golangci-lint (#522)
simonklee Nov 7, 2023
d07833e
Doc ways to improve reproducability besides Temp (#532)
carsonkahn-external Nov 7, 2023
6d9c3a6
Feat Support chat completion response format and seed new fields (#525)
henomis Nov 7, 2023
3063e67
Feat Implement assistants API (#535)
henomis Nov 7, 2023
1ad6b6f
Feat Support tools and tools choice new fileds (#526)
henomis Nov 7, 2023
a20eb08
fix: use pointer for ChatCompletionResponseFormat (#544)
henomis Nov 7, 2023
a0159ad
Support new fields for /v1/images/generation API (#530)
mikecutalo Nov 8, 2023
a2d2bf6
Fix Refactor assistant api (#545)
henomis Nov 8, 2023
08c167f
test: fix compile error in api integration test (#548)
vvatanabe Nov 8, 2023
bc89139
Feat Implement threads API (#536)
henomis Nov 9, 2023
e3e065d
Add SystemFingerprint and chatMsg.ToolCallID field (#543)
gburt Nov 9, 2023
8127072
fix test server setup: (#549)
urjitbhatia Nov 9, 2023
78862a2
fix: add missing fields in tool_calls (#558)
henomis Nov 9, 2023
d6f3bdc
Feat implement Run APIs (#560)
henomis Nov 9, 2023
35495cc
Add `json:"metadata,omitempty"` to RunRequest struct (#561)
kb Nov 12, 2023
9fefd50
Fix typo in chat_test.go (#564)
eltociear Nov 12, 2023
b7cac70
Feat/messages api (#546)
urjitbhatia Nov 13, 2023
515de02
feat: initial TTS support (#528)
stillmatic Nov 13, 2023
fe67abb
fix: add beta assistant header to CreateMessage call (#566)
floodfx Nov 15, 2023
71848cc
feat: support direct bytes for file upload (#568)
floodfx Nov 15, 2023
464b85b
Pagination fields are missing from assistants list beta API (#571)
liron-l Nov 15, 2023
3220f19
feat(runapi): add RunStepList response args https://platform.openai.…
Ccheers Nov 15, 2023
1846572
Add missing struct properties. (#579)
revett Nov 15, 2023
4fd904c
Add File purposes as constants (#577)
revett Nov 18, 2023
9efad28
Updates the tool call struct (#595)
albertpurnama Nov 18, 2023
a130cfe
Add missing response fields for pagination (#584)
albertpurnama Nov 18, 2023
f879095
Add canary-tts to speech models (#603)
pjuhasz Nov 24, 2023
7260991
Update PULL_REQUEST_TEMPLATE.md (#606)
sashabaranov Nov 24, 2023
03caea8
Add support for multi part chat messages (and gpt-4-vision-preview mo…
rkintzi Nov 24, 2023
a09cb0c
Add completion-with-tool example (#598)
mikeb26 Nov 26, 2023
c9615e0
Added support for createImage Azure models (#608)
zjy282 Jan 3, 2024
f10955c
Log probabilities for chat completion output tokens (#625)
danai-antoniou Jan 9, 2024
682b7ad
Update README.md (#631)
Kledal Jan 11, 2024
e01a2d7
convert EmbeddingModel to string type (#629)
jaffee Jan 15, 2024
09f6920
fixed #594 (#609)
HongminHan Jan 15, 2024
4ce03a9
Fix Azure embeddings model detection by passing string to `fullURL` (…
greysteil Jan 16, 2024
eff8dc1
fix(audio): fix audioTextResponse decode (#638)
WqyJh Jan 17, 2024
4c41f24
Support January 25, 2024, models update. (#644)
bazuker Jan 26, 2024
06ff541
Add new struct filed dimensions for embedding API (#645)
chenhhA Jan 29, 2024
bc8cdd3
add GPT3Dot5Turbo0125 model (#648)
liushuangls Feb 2, 2024
bb6ed54
Fix: Add RunStatusCancelled (#650)
shadowpigy Feb 2, 2024
69e3fcb
Fix typo assitantInstructions (#655)
chrbsg Feb 6, 2024
6c2e316
Added support for CreateSpeech Azure models (#657)
zjy282 Feb 8, 2024
a7954c8
Feat: Add assistant usage (#649)
shadowpigy Feb 8, 2024
11ad4b6
make linter happy (#661)
sashabaranov Feb 15, 2024
66bae3e
Content-type fix (#659)
grulex Feb 15, 2024
ff61bbb
Add RunRequest field AdditionalInstructions (#656)
chrbsg Feb 15, 2024
69e3bbb
Update client.go - allow to skip Authorization header (#658)
7flash Feb 16, 2024
e8b3478
fix:fix open ai original validation. modify Tool's Function to pointe…
CaoPengflying Feb 19, 2024
7381d18
Fix for broken Azure Assistants url (#665)
coggsflod Feb 21, 2024
c5401e9
Fix for broken Azure Threads url (#668)
coggsflod Feb 26, 2024
f220443
Added fields for moderation (#662)
raphoester Feb 26, 2024
4103778
fix: when no Assistant Tools are specified, an empty list should be s…
guillaume-dussault Feb 26, 2024
bb6149f
fix: repair json decoding of moderation response (#670)
mheck136 Feb 28, 2024
38b16a3
Added 'wav' and 'pcm' Audio Formats (#671)
GopherGhaznix Mar 7, 2024
699f397
Update streamReader Close() method to return error (#681)
sunshineplan Mar 11, 2024
0925563
Fix broken implementation AssistantModify implementation (#685)
qhenkart Mar 15, 2024
2646bce
feat: get header from sendRequestRaw (#694)
WqyJh Apr 5, 2024
774fc9d
make linter happy (#701)
sashabaranov Apr 5, 2024
187f416
[BREAKING_CHANGES] Fix update message payload (#699)
qhenkart Apr 9, 2024
e0d0801
feat: add GPT4Turbo and GPT4Turbo20240409 (#703)
liushuangls Apr 11, 2024
ea551f4
Fixing typos (#706)
deining Apr 13, 2024
2446f08
Bump GitHub workflow actions to latest versions (#707)
deining Apr 13, 2024
a42f519
[New_Features] Adds recently added Assistant cost saving parameters (…
qhenkart Apr 16, 2024
c6a63ed
Add PromptFilterResult (#702)
jchaykow Apr 16, 2024
8d15a37
Remove hardcoded assistants version (#719)
danai-antoniou Apr 24, 2024
2d58f8f
chore: add SystemFingerprint for chat completion stream response (#716)
winrey Apr 24, 2024
c84ab5f
feat: support cloudflare AI Gateway flavored azure openai (#715)
woorui Apr 24, 2024
c9953a7
Fixup minor copy-pasta comment typo (#728)
agcom Apr 27, 2024
3334a9c
Add support for word-level audio transcription timestamp granularity …
agcom May 7, 2024
6af3220
feat: support stream_options (#736)
liushuangls May 7, 2024
3b25e09
enhancement: Add new GPT4-o and alias to completion enums (#744)
kmesiab May 13, 2024
9f19d1c
Add gpt4o (#742)
May 13, 2024
4f4a856
Added DALL.E 3 to readme.md (#741)
Kshirodram May 13, 2024
211cb49
Update client.go to get response header whether there is an error or …
ando-masaki May 24, 2024
30cf7b8
feat: add params to RunRequest (#754)
TheAdamSmith Jun 3, 2024
8618492
feat: add incomplete run status (#763)
shosato0306 Jun 5, 2024
fd41f7a
Fix integration test (#762)
TheAdamSmith Jun 13, 2024
7e96c71
run integration tests (#769)
sashabaranov Jun 13, 2024
c69c3bb
integration tests: pass openai secret (#770)
sashabaranov Jun 13, 2024
99cc170
feat: support batches api (#746)
eiixy Jun 13, 2024
68acf22
Support Tool Resources properties for Threads (#760)
pkosiec Jun 13, 2024
0a42130
feat: provide vector store (#772)
Pengguancheng Jun 19, 2024
e311859
remove errors.Join (#778)
sashabaranov Jun 26, 2024
03851d2
allow custom voice and speech models (#691)
adrianliechti Jun 30, 2024
727944c
feat: ParallelToolCalls to ChatCompletionRequest with helper function…
structwafel Jul 12, 2024
3e47e6f
fix: #790 (#798)
eiixy Jul 19, 2024
27c1c56
feat: Add GPT-4o Mini model support (#796)
danielchalef Jul 19, 2024
92f4830
fix: #794 (#797)
eiixy Jul 19, 2024
ae903d7
fix: Updated ThreadMessage struct with latest fields based on OpenAI …
ecoralic Jul 19, 2024
a7e9f0e
add hyperparams (#793)
janukobytsch Jul 19, 2024
966ee68
Add New Optional Parameters to `AssistantRequest` Struct (#795)
Vanessamae23 Jul 19, 2024
581da2f
fix: #804 (#807)
eiixy Jul 28, 2024
dbe726c
Add support for `gpt-4o-2024-08-06` (#812)
danielchalef Aug 7, 2024
623074c
feat: Support Structured Outputs (#813)
eiixy Aug 7, 2024
6439e1f
Make reponse format JSONSchema optional (#820)
tylergannon Aug 7, 2024
1880333
Run integration tests for PRs (#823)
HaraldNordgren Aug 9, 2024
2c6889e
fix: #788 (#800)
eiixy Aug 10, 2024
dd7f582
fix: fullURL endpoint generation (#817)
eiixy Aug 16, 2024
d86425a
Allow structured outputs via function calling (#828)
greysteil Aug 16, 2024
6d02119
feat: Support Delete Message API (#799)
kappa-lab Aug 22, 2024
5162adb
Support http client middlewareing (#830)
michurin Aug 23, 2024
a3bd256
Improve handling of JSON Schema in OpenAI API Response Context (#819)
eiixy Aug 24, 2024
030b7cb
fix integration tests (#834)
sashabaranov Aug 24, 2024
c37cf9a
Dynamic model (#838)
mathisen99 Sep 1, 2024
643da8d
depricated model GPT3Ada changed to GPT3Babbage002 (#843)
Arundas666 Sep 4, 2024
194a03e
Add refusal (#844)
qhenkart Sep 11, 2024
a5fb553
Support OpenAI reasoning models (#850)
abatilo Sep 17, 2024
1ec8c24
fix: jsonschema integer validation (#852)
WeiAnAn Sep 20, 2024
9add1c3
add max_completions_tokens for o1 series models (#857)
chococola Sep 20, 2024
9a4f3a7
feat: add ParallelToolCalls to RunRequest (#847)
kenshin54 Sep 20, 2024
e095df5
run_id string Optional (#855)
floodwm Sep 20, 2024
38bdc81
Optimize Client Error Return (#856)
eiixy Sep 26, 2024
7f80303
Fix max_completion_tokens (#860)
alexsacr Sep 26, 2024
e9d8485
fix: ParallelToolCalls should be added to RunRequest (#861)
kenshin54 Sep 26, 2024
fdd59d9
feat: usage struct add CompletionTokensDetails (#863)
liushuangls Sep 26, 2024
bac7d59
fix MaxCompletionTokens typo (#862)
l-winston Oct 3, 2024
7c145eb
add jailbreak filter result, add ContentFilterResults on output (#864)
juliomartinsdev Oct 3, 2024
9913264
Completion API: add new params (#870)
isaacseymour Oct 9, 2024
cfe15ff
return response body as byte slice for RequestError type (#873)
AyushSawant18588 Oct 14, 2024
21f7134
Adding new moderation model constants (#875)
Mhjacobs Oct 14, 2024
b162541
Cleanup (#879)
sashabaranov Oct 15, 2024
9fe2c6c
Completion API: add Store and Metadata parameters (#878)
smackcrane Oct 15, 2024
fb15ff9
Handling for non-json response (#881)
AyushSawant18588 Oct 21, 2024
3672c0d
fix: Updated Assistent struct with latest fields based on OpenAI docs…
ecoralic Oct 21, 2024
6e08732
Updated checkPromptType function to handle prompt list in completions…
AyushSawant18588 Oct 25, 2024
d10f1b8
add chatcompletion stream delta refusal and logprobs (#882)
Yu0u Oct 29, 2024
f5e6e0e
Added Vector Store File List properties that allow for pagination (#891)
MattDavisRV Nov 8, 2024
6d066bb
Support Attachments in MessageRequest (#890)
kodernubie Nov 8, 2024
b3ece4d
Updated client_test to solve lint error (#900)
AyushSawant18588 Nov 19, 2024
1687616
o1 model support stream (#904)
ldnvnbl Nov 20, 2024
74ed75f
Make user field optional in embedding request (#899)
nagar-ajay Nov 20, 2024
21fa42c
feat: add gpt-4o-2024-11-20 model (#905)
liushuangls Nov 30, 2024
c203ca0
feat: add RecvRaw (#896)
WqyJh Nov 30, 2024
af5355f
Fix ID field to be optional (#911)
TimMisiak Dec 8, 2024
56a9acf
Ignore test.mp3 (#913)
sashabaranov Dec 8, 2024
2a0ff5a
Added additional_messages (#914)
sabuhigr Dec 27, 2024
7a2915a
Simplify tests with T.TempDir (#929)
alexandear Jan 31, 2025
9823a8b
Chat Completion API: add ReasoningEffort and new o1 models (#928)
trevorcreech Jan 31, 2025
45aa996
Make "Content" field in "ChatCompletionMessage" omitempty (#926)
saileshd1402 Jan 31, 2025
2054db0
Add support for O3-mini (#930)
rorymalcolm Feb 6, 2025
a62919e
ref: add image url support to messages (#933)
mazyaryousefinia Feb 9, 2025
c0a9a75
feat: add developer role (#936)
liushuangls Feb 12, 2025
85f578b
fix: remove validateO1Specific (#939)
liushuangls Feb 17, 2025
be2e238
feat: add Anthropic API support with custom version header (#934)
danackerson Feb 25, 2025
261721b
Fix linter (#943)
sashabaranov Feb 25, 2025
74d6449
feat: add gpt-4.5-preview models (#947)
liushuangls Mar 4, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
change azure engine config to modelMapper (sashabaranov#306)
* change azure engine config to azure modelMapper config

* Update go.mod

* Revert "Update go.mod"

This reverts commit 78d14c5.

* lint fix

* add test

* lint fix

* lint fix

* lint fix

* opt

* opt

* opt

* opt
GargantuaX authored May 10, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
commit be253c2d63b3df346d3521991241e5cb77e6a4cd
17 changes: 10 additions & 7 deletions api_internal_test.go
Original file line number Diff line number Diff line change
@@ -94,7 +94,7 @@ func TestRequestAuthHeader(t *testing.T) {
az.OrgID = c.OrgID

cli := NewClientWithConfig(az)
req, err := cli.newStreamRequest(context.Background(), "POST", "/chat/completions", nil)
req, err := cli.newStreamRequest(context.Background(), "POST", "/chat/completions", nil, "")
if err != nil {
t.Errorf("Failed to create request: %v", err)
}
@@ -109,14 +109,16 @@ func TestRequestAuthHeader(t *testing.T) {

func TestAzureFullURL(t *testing.T) {
cases := []struct {
Name string
BaseURL string
Engine string
Expect string
Name string
BaseURL string
AzureModelMapper map[string]string
Model string
Expect string
}{
{
"AzureBaseURLWithSlashAutoStrip",
"https://httpbin.org/",
nil,
"chatgpt-demo",
"https://httpbin.org/" +
"openai/deployments/chatgpt-demo" +
@@ -125,6 +127,7 @@ func TestAzureFullURL(t *testing.T) {
{
"AzureBaseURLWithoutSlashOK",
"https://httpbin.org",
nil,
"chatgpt-demo",
"https://httpbin.org/" +
"openai/deployments/chatgpt-demo" +
@@ -134,10 +137,10 @@ func TestAzureFullURL(t *testing.T) {

for _, c := range cases {
t.Run(c.Name, func(t *testing.T) {
az := DefaultAzureConfig("dummy", c.BaseURL, c.Engine)
az := DefaultAzureConfig("dummy", c.BaseURL)
cli := NewClientWithConfig(az)
// /openai/deployments/{engine}/chat/completions?api-version={api_version}
actual := cli.fullURL("/chat/completions")
actual := cli.fullURL("/chat/completions", c.Model)
if actual != c.Expect {
t.Errorf("Expected %s, got %s", c.Expect, actual)
}
2 changes: 1 addition & 1 deletion audio.go
Original file line number Diff line number Diff line change
@@ -68,7 +68,7 @@ func (c *Client) callAudioAPI(
}

urlSuffix := fmt.Sprintf("/audio/%s", endpointSuffix)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.fullURL(urlSuffix), &formBody)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.fullURL(urlSuffix, request.Model), &formBody)
if err != nil {
return AudioResponse{}, err
}
2 changes: 1 addition & 1 deletion chat.go
Original file line number Diff line number Diff line change
@@ -77,7 +77,7 @@ func (c *Client) CreateChatCompletion(
return
}

req, err := c.requestBuilder.build(ctx, http.MethodPost, c.fullURL(urlSuffix), request)
req, err := c.requestBuilder.build(ctx, http.MethodPost, c.fullURL(urlSuffix, request.Model), request)
if err != nil {
return
}
2 changes: 1 addition & 1 deletion chat_stream.go
Original file line number Diff line number Diff line change
@@ -46,7 +46,7 @@ func (c *Client) CreateChatCompletionStream(
}

request.Stream = true
req, err := c.newStreamRequest(ctx, "POST", urlSuffix, request)
req, err := c.newStreamRequest(ctx, "POST", urlSuffix, request, request.Model)
if err != nil {
return
}
22 changes: 17 additions & 5 deletions client.go
Original file line number Diff line number Diff line change
@@ -98,8 +98,10 @@ func decodeString(body io.Reader, output *string) error {
return nil
}

func (c *Client) fullURL(suffix string) string {
// /openai/deployments/{engine}/chat/completions?api-version={api_version}
// fullURL returns full URL for request.
// args[0] is model name, if API type is Azure, model name is required to get deployment name.
func (c *Client) fullURL(suffix string, args ...any) string {
// /openai/deployments/{model}/chat/completions?api-version={api_version}
if c.config.APIType == APITypeAzure || c.config.APIType == APITypeAzureAD {
baseURL := c.config.BaseURL
baseURL = strings.TrimRight(baseURL, "/")
@@ -108,8 +110,17 @@ func (c *Client) fullURL(suffix string) string {
if strings.Contains(suffix, "/models") {
return fmt.Sprintf("%s/%s%s?api-version=%s", baseURL, azureAPIPrefix, suffix, c.config.APIVersion)
}
azureDeploymentName := "UNKNOWN"
if len(args) > 0 {
model, ok := args[0].(string)
if ok {
azureDeploymentName = c.config.GetAzureDeploymentByModel(model)
}
}
return fmt.Sprintf("%s/%s/%s/%s%s?api-version=%s",
baseURL, azureAPIPrefix, azureDeploymentsPrefix, c.config.Engine, suffix, c.config.APIVersion)
baseURL, azureAPIPrefix, azureDeploymentsPrefix,
azureDeploymentName, suffix, c.config.APIVersion,
)
}

// c.config.APIType == APITypeOpenAI || c.config.APIType == ""
@@ -120,8 +131,9 @@ func (c *Client) newStreamRequest(
ctx context.Context,
method string,
urlSuffix string,
body any) (*http.Request, error) {
req, err := c.requestBuilder.build(ctx, method, c.fullURL(urlSuffix), body)
body any,
model string) (*http.Request, error) {
req, err := c.requestBuilder.build(ctx, method, c.fullURL(urlSuffix, model), body)
if err != nil {
return nil, err
}
2 changes: 1 addition & 1 deletion completion.go
Original file line number Diff line number Diff line change
@@ -155,7 +155,7 @@ func (c *Client) CreateCompletion(
return
}

req, err := c.requestBuilder.build(ctx, http.MethodPost, c.fullURL(urlSuffix), request)
req, err := c.requestBuilder.build(ctx, http.MethodPost, c.fullURL(urlSuffix, request.Model), request)
if err != nil {
return
}
28 changes: 19 additions & 9 deletions config.go
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@ package openai

import (
"net/http"
"regexp"
)

const (
@@ -26,13 +27,12 @@ const AzureAPIKeyHeader = "api-key"
type ClientConfig struct {
authToken string

BaseURL string
OrgID string
APIType APIType
APIVersion string // required when APIType is APITypeAzure or APITypeAzureAD
Engine string // required when APIType is APITypeAzure or APITypeAzureAD

HTTPClient *http.Client
BaseURL string
OrgID string
APIType APIType
APIVersion string // required when APIType is APITypeAzure or APITypeAzureAD
AzureModelMapperFunc func(model string) string // replace model to azure deployment name func
HTTPClient *http.Client

EmptyMessagesLimit uint
}
@@ -50,14 +50,16 @@ func DefaultConfig(authToken string) ClientConfig {
}
}

func DefaultAzureConfig(apiKey, baseURL, engine string) ClientConfig {
func DefaultAzureConfig(apiKey, baseURL string) ClientConfig {
return ClientConfig{
authToken: apiKey,
BaseURL: baseURL,
OrgID: "",
APIType: APITypeAzure,
APIVersion: "2023-03-15-preview",
Engine: engine,
AzureModelMapperFunc: func(model string) string {
return regexp.MustCompile(`[.:]`).ReplaceAllString(model, "")
},

HTTPClient: &http.Client{},

@@ -68,3 +70,11 @@ func DefaultAzureConfig(apiKey, baseURL, engine string) ClientConfig {
func (ClientConfig) String() string {
return "<OpenAI API ClientConfig>"
}

func (c ClientConfig) GetAzureDeploymentByModel(model string) string {
if c.AzureModelMapperFunc != nil {
return c.AzureModelMapperFunc(model)
}

return model
}
62 changes: 62 additions & 0 deletions config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package openai_test

import (
"testing"

. "github.com/sashabaranov/go-openai"
)

func TestGetAzureDeploymentByModel(t *testing.T) {
cases := []struct {
Model string
AzureModelMapperFunc func(model string) string
Expect string
}{
{
Model: "gpt-3.5-turbo",
Expect: "gpt-35-turbo",
},
{
Model: "gpt-3.5-turbo-0301",
Expect: "gpt-35-turbo-0301",
},
{
Model: "text-embedding-ada-002",
Expect: "text-embedding-ada-002",
},
{
Model: "",
Expect: "",
},
{
Model: "models",
Expect: "models",
},
{
Model: "gpt-3.5-turbo",
Expect: "my-gpt35",
AzureModelMapperFunc: func(model string) string {
modelmapper := map[string]string{
"gpt-3.5-turbo": "my-gpt35",
}
if val, ok := modelmapper[model]; ok {
return val
}
return model
},
},
}

for _, c := range cases {
t.Run(c.Model, func(t *testing.T) {
conf := DefaultAzureConfig("", "https://test.openai.azure.com/")
if c.AzureModelMapperFunc != nil {
conf.AzureModelMapperFunc = c.AzureModelMapperFunc
}
actual := conf.GetAzureDeploymentByModel(c.Model)
if actual != c.Expect {
t.Errorf("Expected %s, got %s", c.Expect, actual)
}
})
}
}
3 changes: 2 additions & 1 deletion edits.go
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@ package openai

import (
"context"
"fmt"
"net/http"
)

@@ -31,7 +32,7 @@ type EditsResponse struct {

// Perform an API call to the Edits endpoint.
func (c *Client) Edits(ctx context.Context, request EditsRequest) (response EditsResponse, err error) {
req, err := c.requestBuilder.build(ctx, http.MethodPost, c.fullURL("/edits"), request)
req, err := c.requestBuilder.build(ctx, http.MethodPost, c.fullURL("/edits", fmt.Sprint(request.Model)), request)
if err != nil {
return
}
2 changes: 1 addition & 1 deletion embeddings.go
Original file line number Diff line number Diff line change
@@ -132,7 +132,7 @@ type EmbeddingRequest struct {
// CreateEmbeddings returns an EmbeddingResponse which will contain an Embedding for every item in |request.Input|.
// https://beta.openai.com/docs/api-reference/embeddings/create
func (c *Client) CreateEmbeddings(ctx context.Context, request EmbeddingRequest) (resp EmbeddingResponse, err error) {
req, err := c.requestBuilder.build(ctx, http.MethodPost, c.fullURL("/embeddings"), request)
req, err := c.requestBuilder.build(ctx, http.MethodPost, c.fullURL("/embeddings", request.Model.String()), request)
if err != nil {
return
}
3 changes: 1 addition & 2 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -305,8 +305,7 @@ func Example_chatbot() {
func ExampleDefaultAzureConfig() {
azureKey := os.Getenv("AZURE_OPENAI_API_KEY") // Your azure API key
azureEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT") // Your azure OpenAI endpoint
azureModel := os.Getenv("AZURE_OPENAI_MODEL") // Your model deployment name
config := openai.DefaultAzureConfig(azureKey, azureEndpoint, azureModel)
config := openai.DefaultAzureConfig(azureKey, azureEndpoint)
client := openai.NewClientWithConfig(config)
resp, err := client.CreateChatCompletion(
context.Background(),
2 changes: 1 addition & 1 deletion models_test.go
Original file line number Diff line number Diff line change
@@ -40,7 +40,7 @@ func TestAzureListModels(t *testing.T) {
ts.Start()
defer ts.Close()

config := DefaultAzureConfig(test.GetTestToken(), "https://dummylab.openai.azure.com/", "dummyengine")
config := DefaultAzureConfig(test.GetTestToken(), "https://dummylab.openai.azure.com/")
config.BaseURL = ts.URL
client := NewClientWithConfig(config)
ctx := context.Background()
2 changes: 1 addition & 1 deletion moderation.go
Original file line number Diff line number Diff line change
@@ -63,7 +63,7 @@ type ModerationResponse struct {
// Moderations — perform a moderation api call over a string.
// Input can be an array or slice but a string will reduce the complexity.
func (c *Client) Moderations(ctx context.Context, request ModerationRequest) (response ModerationResponse, err error) {
req, err := c.requestBuilder.build(ctx, http.MethodPost, c.fullURL("/moderations"), request)
req, err := c.requestBuilder.build(ctx, http.MethodPost, c.fullURL("/moderations", request.Model), request)
if err != nil {
return
}
2 changes: 1 addition & 1 deletion stream.go
Original file line number Diff line number Diff line change
@@ -35,7 +35,7 @@ func (c *Client) CreateCompletionStream(
}

request.Stream = true
req, err := c.newStreamRequest(ctx, "POST", urlSuffix, request)
req, err := c.newStreamRequest(ctx, "POST", urlSuffix, request, request.Model)
if err != nil {
return
}