@@ -154,6 +154,8 @@ ai: {
154154
155155#### Azure OpenAI
156156
157+ When your setup using Azure API key
158+
157159Prerequisite:
158160
159161* Install ` @azure/ openai` package
@@ -175,7 +177,88 @@ ai: {
175177}
176178` ` `
177179
180+ When your setup using ` bearer token`
181+
182+ Prerequisite:
183+
184+ * Install ` @azure/ openai` , ` @azure/ identity` packages
185+ * obtain ` AZURE_TENANT_ID ` , ` AZURE_CLIENT_ID ` , and ` AZURE_CLIENT_SECRET `
186+
187+ ` ` ` js
188+ ai: {
189+ request: async (messages ) => {
190+ try {
191+ const { OpenAIClient } = require (" @azure/openai" );
192+ const { DefaultAzureCredential } = require (" @azure/identity" );
193+
194+ const endpoint = process .env .API_ENDPOINT ;
195+ const deploymentId = process .env .DEPLOYMENT_ID ;
196+
197+ const client = new OpenAIClient (endpoint, new DefaultAzureCredential ());
198+ const result = await client .getCompletions (deploymentId, {
199+ prompt: messages,
200+ model: ' gpt-3.5-turbo' // your preferred model
201+ });
202+
203+ return result .choices [0 ]? .text ;
204+ } catch (error) {
205+ console .error (" Error calling API:" , error);
206+ throw error;
207+ }
208+ }
209+ }
210+ ` ` `
211+
212+ Or you could try with direct API request
213+
214+ ` ` ` js
215+ ai: {
216+ request: async (messages ) => {
217+ try {
218+ const endpoint = process .env .API_ENDPOINT ;
219+ const deploymentId = process .env .DEPLOYMENT_ID ;
178220
221+ const result = await makeApiRequest (endpoint, deploymentId, messages)
222+
223+ return result .choices [0 ]? .message .content
224+ } catch (error) {
225+ console .error (" Error calling API:" , error);
226+ throw error;
227+ }
228+ }
229+ }
230+ ...
231+
232+ async function getAccessToken () {
233+ const credential = new DefaultAzureCredential ();
234+ const scope = " https://cognitiveservices.azure.com/.default" ;
235+
236+ try {
237+ const accessToken = await credential .getToken (scope);
238+ return ` Bearer ${ accessToken .token } ` ;
239+ } catch (err) {
240+ console .error (" Failed to get access token:" , err);
241+ }
242+ }
243+
244+ async function makeApiRequest (endpoint , deploymentId , messages ) {
245+ const token = await getAccessToken ();
246+ const url = ` ${ endpoint} /openai/deployments/${ deploymentId} /chat/completions?api-version=2024-06-01` ;
247+
248+ const data = { messages };
249+
250+ try {
251+ const response = await axios .post (url, data, {
252+ headers: {
253+ ' Authorization' : ` ${ token} `
254+ }
255+ });
256+ return response .data
257+ } catch (err) {
258+ console .error (" API request failed:" , err .response );
259+ }
260+ }
261+ ` ` `
179262
180263### Writing Tests with AI Copilot
181264
@@ -490,4 +573,4 @@ or if you run it in shell mode:
490573
491574` ` `
492575DEBUG = " codeceptjs:ai" npx codeceptjs shell -- ai
493- ` ` `
576+ ` ` `
0 commit comments