import os
from openai import AzureOpenAI
client = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2024-03-01-preview"
)
response = client.chat.completions.create(
model="YOUR-MODEL_DEPLOYMENT_NAME", # Model = should match the deployment name you chose for your model deployment
response_format={ "type": "json_object" },
messages=[
{"role": "system", "content": "You are a helpful assistant designed to output JSON."},
{"role": "user", "content": "Who won the world series in 2020?"}
]
)
print(response.choices[0].message.content)
$openai = @{
api_key = $Env:AZURE_OPENAI_API_KEY
api_base = $Env:AZURE_OPENAI_ENDPOINT # like the following https://YOUR_RESOURCE_NAME.openai.azure.com/
api_version = '2024-03-01-preview' # may change in the future
name = 'YOUR-DEPLOYMENT-NAME-HERE' # name you chose for your deployment
}
$headers = @{
'api-key' = $openai.api_key
}
$messages = @()
$messages += @{
role = 'system'
content = 'You are a helpful assistant designed to output JSON.'
}
$messages += @{
role = 'user'
content = 'Who threw the final pitch during the world series each year from 1979 to 1989?'
}
$messages += @{
role = 'user'
content = 'Respond using schema. response:{year, team, player, player_height}.'
}
$body = @{
response_format = @{type = 'json_object'}
messages = $messages
} | ConvertTo-Json
$url = "$($openai.api_base)/openai/deployments/$($openai.name)/chat/completions?api-version=$($openai.api_version)"
$response = Invoke-RestMethod -Uri $url -Headers $headers -Body $body -Method Post -ContentType 'application/json'
$response.choices[0].message.content
if ($response.choices[0].finish_reason -eq 'stop') {
$response.choices[0].message.content | ConvertFrom-Json | ForEach-Object response | Sort player_height -Descending
} else { write-warning 'the JSON response was incomplete'}
year team player player_height
---- ---- ------ -------------
1979 Pittsburgh Pirates Kent Tekulve 6' 4"
1984 Detroit Tigers Willie Hernandez 6' 3"
1988 Los Angeles Dodgers Orel Hershiser 6' 3"
1982 St. Louis Cardinals Bruce Sutter 6' 2"
1985 Kansas City Royals Dan Quisenberry 6' 2"
1986 New York Mets Jesse Orosco 6' 2"
1989 Oakland Athletics Dennis Eckersley 6' 2"
1981 Los Angeles Dodgers Steve Howe 6' 1"
1980 Philadelphia Phillies Tug McGraw 6' 0"
1987 Minnesota Twins Jeff Reardon 6' 0"
1983 Baltimore Orioles Tippy Martinez 5' 10"
BadRequestError: Error code: 400 - {'error': {'message': "'messages' must contain the word 'json' in some form, to use 'response_format' of type 'json_object'.", 'type': 'invalid_request_error', 'param': 'messages', 'code': None}}