Skip to content

Commit 0230370

Browse files
committed
Refactoring
1 parent 77abf07 commit 0230370

14 files changed

Lines changed: 316 additions & 318 deletions
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
using namespace System.Collections
2+
3+
function Initialize-OpenAIAPIRequestParam {
4+
[CmdletBinding()]
5+
[OutputType([hashtable])]
6+
param (
7+
[Parameter()]
8+
[string]$Method = 'Post',
9+
10+
[Parameter(Mandatory)]
11+
[System.Uri]$Uri,
12+
13+
[Parameter()]
14+
[string]$ContentType = 'application/json',
15+
16+
[Parameter()]
17+
[IDictionary]$AdditionalQuery,
18+
19+
[Parameter()]
20+
[object]$Body,
21+
22+
[Parameter()]
23+
[object]$AdditionalBody,
24+
25+
[Parameter()]
26+
[IDictionary]$Headers,
27+
28+
[Parameter()]
29+
[IDictionary]$AdditionalHeaders,
30+
31+
[Parameter()]
32+
[string]$AuthType = 'openai',
33+
34+
[Parameter(ValueFromRemainingArguments)]$ArgList
35+
)
36+
37+
$InternalParams = @{
38+
ServiceName = ''
39+
Method = $Method
40+
ContentType = $ContentType
41+
Uri = $Uri
42+
Body = $null
43+
Headers = $null
44+
UserAgent = $null
45+
IsDebug = $false
46+
}
47+
48+
# Set service name based on AuthType
49+
$InternalParams.ServiceName = switch -Wildcard ($AuthType) {
50+
'openai*' { 'OpenAI' }
51+
'azure*' { 'Azure OpenAI' }
52+
}
53+
54+
# Assert selected model is discontinued
55+
if ($null -ne $Body -and $null -ne $Body.model) {
56+
Assert-DeprecationModel -Model $Body.model
57+
}
58+
59+
# Construct URI with Query Parameters
60+
if ($PSBoundParameters.ContainsKey('AdditionalQuery') -and $null -ne $AdditionalQuery) {
61+
$UriBuilder = [System.UriBuilder]::new($Uri)
62+
$QueryParam = [System.Web.HttpUtility]::ParseQueryString($UriBuilder.Query)
63+
foreach ($s in $AdditionalQuery.GetEnumerator()) {
64+
$QueryParam.Add($s.Key, $s.Value)
65+
}
66+
$UriBuilder.Query = $QueryParam.ToString()
67+
$Uri = $UriBuilder.Uri
68+
}
69+
$InternalParams.Uri = $Uri
70+
71+
# Construct Headers
72+
$RequestHeaders = @{}
73+
if ($PSBoundParameters.ContainsKey('Headers') -and $null -ne $Headers) {
74+
$RequestHeaders = Merge-Dictionary $Headers $RequestHeaders
75+
}
76+
if ($PSBoundParameters.ContainsKey('AdditionalHeaders') -and $null -ne $AdditionalHeaders) {
77+
$RequestHeaders = Merge-Dictionary $RequestHeaders $AdditionalHeaders
78+
}
79+
$InternalParams.Headers = $RequestHeaders
80+
81+
# Set UserAgent
82+
if (-not $script:UserAgent) {
83+
$script:UserAgent = Get-UserAgent
84+
}
85+
$InternalParams.UserAgent = $script:UserAgent
86+
87+
# Set debug flag
88+
$InternalParams.IsDebug = Test-Debug
89+
if ($InternalParams.IsDebug) {
90+
$InternalParams.Headers['OpenAI-Debug'] = 'true'
91+
}
92+
93+
94+
# Construct Body
95+
if ($null -ne $Body) {
96+
if ($ContentType -match 'multipart/form-data') {
97+
$Boundary = New-MultipartFormBoundary
98+
$Body = New-MultipartFormContent -FormData $Body -Boundary $Boundary
99+
$ContentType = ('multipart/form-data; boundary="{0}"' -f $Boundary)
100+
}
101+
elseif ($ContentType -match 'application/json') {
102+
if ($Body -is [pscustomobject]) {
103+
$Body = ObjectToHashTable $Body
104+
}
105+
if ($PSBoundParameters.ContainsKey('AdditionalBody') -and $null -ne $AdditionalBody) {
106+
if ($AdditionalBody -is [string]) {
107+
try {
108+
$AdditionalBody = ConvertFrom-Json $AdditionalBody -Depth 100
109+
}
110+
catch {
111+
Write-Error -Exception ([System.InvalidOperationException]::new('Failed to parse AdditionalBody as JSON.'))
112+
}
113+
}
114+
if ($AdditionalBody -is [pscustomobject]) {
115+
$AdditionalBody = ObjectToHashTable $AdditionalBody
116+
}
117+
$Body = Merge-Dictionary $Body $AdditionalBody
118+
}
119+
}
120+
}
121+
$InternalParams.Body = $Body
122+
123+
return $InternalParams
124+
}

Private/Invoke-OpenAIAPIRequest.ps1

Lines changed: 20 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,6 @@ function Invoke-OpenAIAPIRequest {
5555
[Parameter()]
5656
[int]$RetryCount = 0,
5757

58-
[Parameter()]
59-
[bool]$Stream = $false,
60-
6158
[Parameter()]
6259
# [ValidateSet('openai', 'azure', 'azure_ad')]
6360
[string]$AuthType = 'openai',
@@ -66,99 +63,21 @@ function Invoke-OpenAIAPIRequest {
6663
[bool]$ReturnRawResponse = $false
6764
)
6865

69-
#region Set variables
70-
$IsDebug = Test-Debug
71-
$ServiceName = switch -Wildcard ($AuthType) {
72-
'openai*' { 'OpenAI' }
73-
'azure*' { 'Azure OpenAI' }
74-
}
75-
#endregion
76-
77-
#region Assert selected model is discontinued
78-
if ($null -ne $Body -and $null -ne $Body.model) {
79-
Assert-DeprecationModel -Model $Body.model
80-
}
81-
#endregion
82-
83-
# Query string
84-
if ($PSBoundParameters.ContainsKey('AdditionalQuery') -and $null -ne $AdditionalQuery) {
85-
$UriBuilder = [System.UriBuilder]::new($Uri)
86-
$QueryParam = [System.Web.HttpUtility]::ParseQueryString($UriBuilder.Query)
87-
foreach ($s in $AdditionalQuery.GetEnumerator()) {
88-
$QueryParam.Add($s.Key, $s.Value)
89-
}
90-
$UriBuilder.Query = $QueryParam.ToString()
91-
$Uri = $UriBuilder.Uri
92-
}
93-
94-
# Headers dictionary
95-
$RequestHeaders = @{}
96-
if ($PSBoundParameters.ContainsKey('Headers') -and $null -ne $Headers) {
97-
$RequestHeaders = Merge-Dictionary $Headers $RequestHeaders
98-
}
99-
if ($PSBoundParameters.ContainsKey('AdditionalHeaders') -and $null -ne $AdditionalHeaders) {
100-
$RequestHeaders = Merge-Dictionary $RequestHeaders $AdditionalHeaders
101-
}
102-
103-
# Set debug header
104-
if ($IsDebug) {
105-
$RequestHeaders['OpenAI-Debug'] = 'true'
106-
}
66+
$InternalParams = Initialize-OpenAIAPIRequestParam @PSBoundParameters
10767

108-
# Body object
109-
if ($null -ne $Body) {
110-
if ($ContentType -match 'multipart/form-data') {
111-
$Boundary = New-MultipartFormBoundary
112-
$Body = New-MultipartFormContent -FormData $Body -Boundary $Boundary
113-
$ContentType = ('multipart/form-data; boundary="{0}"' -f $Boundary)
114-
}
115-
elseif ($ContentType -match 'application/json') {
116-
if ($Body -is [pscustomobject]) {
117-
$Body = ObjectToHashTable $Body
118-
}
119-
if ($PSBoundParameters.ContainsKey('AdditionalBody') -and $null -ne $AdditionalBody) {
120-
if ($AdditionalBody -is [string]) {
121-
try {
122-
$AdditionalBody = ConvertFrom-Json $AdditionalBody -Depth 100
123-
}
124-
catch {
125-
Write-Error -Exception ([System.InvalidOperationException]::new('Failed to parse AdditionalBody as JSON.'))
126-
}
127-
}
128-
if ($AdditionalBody -is [pscustomobject]) {
129-
$AdditionalBody = ObjectToHashTable $AdditionalBody
130-
}
131-
$Body = Merge-Dictionary $Body $AdditionalBody
132-
}
133-
}
134-
}
135-
136-
#region Server-Sent-Events
137-
if ($Stream) {
138-
$params = @{
139-
Method = $Method
140-
Uri = $Uri
141-
ContentType = $ContentType
142-
ApiKey = $ApiKey
143-
Organization = $Organization
144-
AuthType = $AuthType
145-
Body = $Body
146-
Headers = $RequestHeaders
147-
TimeoutSec = $TimeoutSec
148-
MaxRetryCount = $MaxRetryCount
149-
}
150-
Invoke-OpenAIAPIRequestSSE @params
151-
return
152-
}
68+
#region Set variables
69+
$IsDebug = $InternalParams.IsDebug
70+
$ServiceName = $InternalParams.ServiceName
15371
#endregion
15472

15573
#region API request
15674
# Construct parameter for Invoke-WebRequest
15775
$PlainToken = DecryptSecureString $ApiKey
15876
$IwrParam = @{
159-
Method = $Method
160-
Uri = $Uri
161-
ContentType = $ContentType
77+
Method = $InternalParams.Method
78+
Uri = $InternalParams.Uri
79+
ContentType = $InternalParams.ContentType
80+
UserAgent = $InternalParams.UserAgent
16281
TimeoutSec = $TimeoutSec
16382
UseBasicParsing = $true
16483
}
@@ -188,12 +107,12 @@ function Invoke-OpenAIAPIRequest {
188107
$UseBearer = $true
189108
# Set Organization-ID
190109
if (-not [string]::IsNullOrWhiteSpace($Organization)) {
191-
$RequestHeaders['OpenAI-Organization'] = $Organization.Trim()
110+
$InternalParams.Headers['OpenAI-Organization'] = $Organization.Trim()
192111
}
193112
}
194113
'azure' {
195114
$UseBearer = $false
196-
$RequestHeaders['api-key'] = $PlainToken
115+
$InternalParams.Headers['api-key'] = $PlainToken
197116
}
198117
'azure_ad' {
199118
$UseBearer = $true
@@ -217,28 +136,28 @@ function Invoke-OpenAIAPIRequest {
217136
else {
218137
# Use Bearer Token Auth
219138
if ($UseBearer) {
220-
$RequestHeaders['Authorization'] = "Bearer $PlainToken"
139+
$InternalParams.Headers['Authorization'] = "Bearer $PlainToken"
221140
}
222141
}
223142

224-
if ($null -ne $Body) {
225-
if ($ContentType -match 'application/json') {
226-
try { $Body = ($Body | ConvertTo-Json -Compress -Depth 100) }catch { Write-Error -Exception $_.Exception }
227-
$IwrParam.Body = ([System.Text.Encoding]::UTF8.GetBytes($Body))
143+
if ($null -ne $InternalParams.Body) {
144+
if ($InternalParams.ContentType -match 'application/json') {
145+
try { $InternalParams.Body = ($InternalParams.Body | ConvertTo-Json -Compress -Depth 100) }catch { Write-Error -Exception $_.Exception }
146+
$IwrParam.Body = ([System.Text.Encoding]::UTF8.GetBytes($InternalParams.Body))
228147
}
229148
else {
230-
$IwrParam.Body = $Body
149+
$IwrParam.Body = $InternalParams.Body
231150
}
232151
}
233152

234153
# Set http request headers
235-
if ($null -ne $RequestHeaders -and $RequestHeaders.Count -ne 0) {
236-
$IwrParam.Headers = $RequestHeaders
154+
if ($InternalParams.Headers.Keys.Count -ne 0) {
155+
$IwrParam.Headers = $InternalParams.Headers
237156
}
238157

239158
# Verbose / Debug output
240159
Write-Verbose -Message "Request to $ServiceName API"
241-
Write-Verbose -Message "Method = $Method, Path = $Uri"
160+
Write-Verbose -Message "Method = $Method, Path = $($InternalParams.Uri)"
242161
if ($IsDebug) {
243162
$startIdx = $lastIdx = 2
244163
if ($AuthType -eq 'openai') { $startIdx += 4 } # 'org-'
@@ -253,7 +172,7 @@ function Invoke-OpenAIAPIRequest {
253172
Write-Debug -Message $maskedString1
254173

255174
$params2 = @{
256-
Source = 'Post body: ' + $Body
175+
Source = 'Post body: ' + $InternalParams.Body
257176
Target = ($ApiKey, $Organization)
258177
First = $startIdx
259178
Last = $lastIdx

0 commit comments

Comments
 (0)