@revenium/openai 1.0.10 → 1.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +20 -0
- package/CHANGELOG.md +52 -0
- package/LICENSE +21 -21
- package/README.md +682 -1152
- package/dist/cjs/core/config/loader.js +1 -1
- package/dist/cjs/core/config/loader.js.map +1 -1
- package/dist/cjs/core/tracking/api-client.js +1 -1
- package/dist/cjs/core/tracking/api-client.js.map +1 -1
- package/dist/cjs/index.js +4 -4
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/types/openai-augmentation.js +1 -1
- package/dist/cjs/utils/url-builder.js +32 -7
- package/dist/cjs/utils/url-builder.js.map +1 -1
- package/dist/esm/core/config/loader.js +1 -1
- package/dist/esm/core/config/loader.js.map +1 -1
- package/dist/esm/core/tracking/api-client.js +1 -1
- package/dist/esm/core/tracking/api-client.js.map +1 -1
- package/dist/esm/index.js +4 -4
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/types/openai-augmentation.js +1 -1
- package/dist/esm/utils/url-builder.js +32 -7
- package/dist/esm/utils/url-builder.js.map +1 -1
- package/dist/types/index.d.ts +4 -4
- package/dist/types/types/index.d.ts +2 -2
- package/dist/types/types/index.d.ts.map +1 -1
- package/dist/types/types/openai-augmentation.d.ts +1 -1
- package/dist/types/utils/url-builder.d.ts +11 -3
- package/dist/types/utils/url-builder.d.ts.map +1 -1
- package/examples/README.md +357 -0
- package/examples/azure-basic.ts +206 -0
- package/examples/azure-responses-basic.ts +233 -0
- package/examples/azure-responses-streaming.ts +255 -0
- package/examples/azure-streaming.ts +209 -0
- package/examples/getting_started.ts +54 -0
- package/examples/openai-basic.ts +147 -0
- package/examples/openai-function-calling.ts +259 -0
- package/examples/openai-responses-basic.ts +212 -0
- package/examples/openai-responses-streaming.ts +232 -0
- package/examples/openai-streaming.ts +172 -0
- package/examples/openai-vision.ts +289 -0
- package/package.json +81 -84
- package/src/core/config/azure-config.ts +72 -0
- package/src/core/config/index.ts +23 -0
- package/src/core/config/loader.ts +66 -0
- package/src/core/config/manager.ts +94 -0
- package/src/core/config/validator.ts +89 -0
- package/src/core/providers/detector.ts +159 -0
- package/src/core/providers/index.ts +16 -0
- package/src/core/tracking/api-client.ts +78 -0
- package/src/core/tracking/index.ts +21 -0
- package/src/core/tracking/payload-builder.ts +132 -0
- package/src/core/tracking/usage-tracker.ts +189 -0
- package/src/core/wrapper/index.ts +9 -0
- package/src/core/wrapper/instance-patcher.ts +288 -0
- package/src/core/wrapper/request-handler.ts +423 -0
- package/src/core/wrapper/stream-wrapper.ts +100 -0
- package/src/index.ts +336 -0
- package/src/types/function-parameters.ts +251 -0
- package/src/types/index.ts +313 -0
- package/src/types/openai-augmentation.ts +233 -0
- package/src/types/responses-api.ts +308 -0
- package/src/utils/azure-model-resolver.ts +220 -0
- package/src/utils/constants.ts +21 -0
- package/src/utils/error-handler.ts +251 -0
- package/src/utils/metadata-builder.ts +219 -0
- package/src/utils/provider-detection.ts +257 -0
- package/src/utils/request-handler-factory.ts +285 -0
- package/src/utils/stop-reason-mapper.ts +74 -0
- package/src/utils/type-guards.ts +202 -0
- package/src/utils/url-builder.ts +68 -0
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
# Revenium OpenAI Middleware - Examples
|
|
2
|
+
|
|
3
|
+
**TypeScript-first** examples demonstrating automatic Revenium usage tracking with the OpenAI SDK.
|
|
4
|
+
|
|
5
|
+
## Getting Started - Step by Step
|
|
6
|
+
|
|
7
|
+
### 1. Create Your Project
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
# Create project directory
|
|
11
|
+
mkdir my-openai-project
|
|
12
|
+
cd my-openai-project
|
|
13
|
+
|
|
14
|
+
# Initialize Node.js project
|
|
15
|
+
npm init -y
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
### 2. Install Dependencies
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install @revenium/openai openai dotenv
|
|
22
|
+
npm install -D typescript tsx @types/node # For TypeScript
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### 3. Environment Setup
|
|
26
|
+
|
|
27
|
+
Create a `.env` file in your project root:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
# Required
|
|
31
|
+
REVENIUM_METERING_API_KEY=hak_your_revenium_api_key
|
|
32
|
+
OPENAI_API_KEY=sk_your_openai_api_key
|
|
33
|
+
|
|
34
|
+
# Optional
|
|
35
|
+
REVENIUM_METERING_BASE_URL=https://api.revenium.io
|
|
36
|
+
REVENIUM_DEBUG=false
|
|
37
|
+
|
|
38
|
+
# Optional - For Azure OpenAI examples
|
|
39
|
+
AZURE_OPENAI_ENDPOINT=https://your-resource-name.openai.azure.com/
|
|
40
|
+
AZURE_OPENAI_API_KEY=your-azure-api-key
|
|
41
|
+
AZURE_OPENAI_DEPLOYMENT=your-deployment-name
|
|
42
|
+
AZURE_OPENAI_API_VERSION=2024-12-01-preview
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### 4. Run Examples
|
|
46
|
+
|
|
47
|
+
**If you cloned from GitHub:**
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
# Run examples directly
|
|
51
|
+
npx tsx examples/getting_started.ts
|
|
52
|
+
npx tsx examples/openai-basic.ts
|
|
53
|
+
npx tsx examples/openai-streaming.ts
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
**If you installed via npm:**
|
|
57
|
+
|
|
58
|
+
Examples are included in your `node_modules/@revenium/openai/examples/` directory:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
npx tsx node_modules/@revenium/openai/examples/getting_started.ts
|
|
62
|
+
npx tsx node_modules/@revenium/openai/examples/openai-basic.ts
|
|
63
|
+
npx tsx node_modules/@revenium/openai/examples/openai-streaming.ts
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Available Examples
|
|
67
|
+
|
|
68
|
+
### `getting_started.ts` - Simple Entry Point
|
|
69
|
+
|
|
70
|
+
The simplest example to get you started with Revenium tracking:
|
|
71
|
+
|
|
72
|
+
- **Minimal setup** - Just import, configure, and start tracking
|
|
73
|
+
- **Complete metadata example** - Shows all 11 optional metadata fields in comments
|
|
74
|
+
- **Ready to customize** - Uncomment the metadata section to add tracking context
|
|
75
|
+
|
|
76
|
+
**Key Features:**
|
|
77
|
+
|
|
78
|
+
- Auto-initialization from environment variables
|
|
79
|
+
- Native `usageMetadata` support via module augmentation
|
|
80
|
+
- All metadata fields documented with examples
|
|
81
|
+
- Single API call demonstration
|
|
82
|
+
|
|
83
|
+
**Perfect for:** First-time users, quick validation, understanding metadata structure
|
|
84
|
+
|
|
85
|
+
**See the file for complete code examples.**
|
|
86
|
+
|
|
87
|
+
### `openai-basic.ts` - Chat Completions and Embeddings
|
|
88
|
+
|
|
89
|
+
Demonstrates standard OpenAI API usage with automatic tracking:
|
|
90
|
+
|
|
91
|
+
- **Chat completions** - Basic chat API with metadata tracking
|
|
92
|
+
- **Embeddings** - Text embedding generation with usage tracking
|
|
93
|
+
- **Multiple API calls** - Batch operations with consistent metadata
|
|
94
|
+
|
|
95
|
+
**Key Features:**
|
|
96
|
+
|
|
97
|
+
- TypeScript module augmentation for native `usageMetadata` support
|
|
98
|
+
- Full type safety with IntelliSense
|
|
99
|
+
- Comprehensive metadata examples
|
|
100
|
+
- Error handling patterns
|
|
101
|
+
|
|
102
|
+
**Perfect for:** Understanding basic OpenAI API patterns with tracking
|
|
103
|
+
|
|
104
|
+
**See the file for complete code examples.**
|
|
105
|
+
|
|
106
|
+
### `openai-streaming.ts` - Real-time Streaming
|
|
107
|
+
|
|
108
|
+
Demonstrates streaming responses with automatic token tracking:
|
|
109
|
+
|
|
110
|
+
- **Streaming chat completions** - Real-time token streaming with metadata
|
|
111
|
+
- **Batch embeddings** - Multiple embedding requests efficiently
|
|
112
|
+
- **Stream processing** - Type-safe event handling
|
|
113
|
+
|
|
114
|
+
**Key Features:**
|
|
115
|
+
|
|
116
|
+
- Automatic tracking when stream completes
|
|
117
|
+
- Real-time token counting
|
|
118
|
+
- Time-to-first-token metrics
|
|
119
|
+
- Stream error handling
|
|
120
|
+
|
|
121
|
+
**Perfect for:** Real-time applications, chatbots, interactive AI assistants
|
|
122
|
+
|
|
123
|
+
**See the file for complete code examples.**
|
|
124
|
+
|
|
125
|
+
### `openai-function-calling.ts` - Function Calling with Tools
|
|
126
|
+
|
|
127
|
+
Demonstrates OpenAI function calling (tools) with tracking:
|
|
128
|
+
|
|
129
|
+
- **Tool definitions** - Define functions for the AI to call
|
|
130
|
+
- **Function execution** - Handle tool calls and return results
|
|
131
|
+
- **Multi-turn conversations** - Manage conversation flow with function results
|
|
132
|
+
|
|
133
|
+
**Key Features:**
|
|
134
|
+
|
|
135
|
+
- Complete function calling workflow
|
|
136
|
+
- Type-safe tool definitions
|
|
137
|
+
- Automatic tracking of tool usage
|
|
138
|
+
- Multi-turn conversation handling
|
|
139
|
+
|
|
140
|
+
**Perfect for:** AI agents, function-calling applications, structured outputs
|
|
141
|
+
|
|
142
|
+
**See the file for complete code examples.**
|
|
143
|
+
|
|
144
|
+
### `openai-vision.ts` - Vision API with Images
|
|
145
|
+
|
|
146
|
+
Demonstrates OpenAI Vision API with image analysis:
|
|
147
|
+
|
|
148
|
+
- **Image URL analysis** - Analyze images from URLs
|
|
149
|
+
- **Base64 images** - Process local images as base64
|
|
150
|
+
- **Multi-image analysis** - Compare multiple images in one request
|
|
151
|
+
|
|
152
|
+
**Key Features:**
|
|
153
|
+
|
|
154
|
+
- Image analysis with GPT-4 Vision
|
|
155
|
+
- Multiple image input methods
|
|
156
|
+
- Detailed image descriptions
|
|
157
|
+
- Usage tracking for vision API calls
|
|
158
|
+
|
|
159
|
+
**Perfect for:** Image analysis applications, visual search, accessibility tools
|
|
160
|
+
|
|
161
|
+
**See the file for complete code examples.**
|
|
162
|
+
|
|
163
|
+
### `openai-responses-basic.ts` - New Responses API
|
|
164
|
+
|
|
165
|
+
Demonstrates OpenAI's new Responses API (SDK 5.8+):
|
|
166
|
+
|
|
167
|
+
- **Simplified interface** - Uses `input` instead of `messages` parameter
|
|
168
|
+
- **Stateful API** - Enhanced capabilities for agent-like applications
|
|
169
|
+
- **Unified experience** - Combines chat completions and assistants features
|
|
170
|
+
|
|
171
|
+
**Key Features:**
|
|
172
|
+
|
|
173
|
+
- New Responses API patterns
|
|
174
|
+
- Automatic tracking with new API
|
|
175
|
+
- Metadata support
|
|
176
|
+
- Backward compatibility notes
|
|
177
|
+
|
|
178
|
+
**Perfect for:** Applications using OpenAI's latest API features
|
|
179
|
+
|
|
180
|
+
**See the file for complete code examples.**
|
|
181
|
+
|
|
182
|
+
### `openai-responses-streaming.ts` - Responses API Streaming
|
|
183
|
+
|
|
184
|
+
Demonstrates streaming with the new Responses API:
|
|
185
|
+
|
|
186
|
+
- **Streaming responses** - Real-time responses with new API
|
|
187
|
+
- **Event handling** - Process response events as they arrive
|
|
188
|
+
- **Usage tracking** - Automatic tracking for streaming responses
|
|
189
|
+
|
|
190
|
+
**Key Features:**
|
|
191
|
+
|
|
192
|
+
- Responses API streaming patterns
|
|
193
|
+
- Type-safe event processing
|
|
194
|
+
- Automatic usage metrics
|
|
195
|
+
- Stream completion tracking
|
|
196
|
+
|
|
197
|
+
**Perfect for:** Real-time applications using the new Responses API
|
|
198
|
+
|
|
199
|
+
**See the file for complete code examples.**
|
|
200
|
+
|
|
201
|
+
### Azure OpenAI Examples
|
|
202
|
+
|
|
203
|
+
#### `azure-basic.ts` - Azure Chat Completions
|
|
204
|
+
|
|
205
|
+
Demonstrates Azure OpenAI integration with automatic detection:
|
|
206
|
+
|
|
207
|
+
- **Azure configuration** - Environment-based Azure setup
|
|
208
|
+
- **Chat completions** - Azure-hosted models with tracking
|
|
209
|
+
- **Automatic detection** - Middleware detects Azure vs OpenAI automatically
|
|
210
|
+
|
|
211
|
+
**Key Features:**
|
|
212
|
+
|
|
213
|
+
- Azure OpenAI deployment configuration
|
|
214
|
+
- Model name resolution for Azure
|
|
215
|
+
- Accurate Azure pricing
|
|
216
|
+
- Metadata tracking with Azure
|
|
217
|
+
|
|
218
|
+
**Perfect for:** Enterprise applications using Azure OpenAI
|
|
219
|
+
|
|
220
|
+
**See the file for complete code examples.**
|
|
221
|
+
|
|
222
|
+
#### `azure-streaming.ts` - Azure Streaming
|
|
223
|
+
|
|
224
|
+
Demonstrates streaming with Azure OpenAI:
|
|
225
|
+
|
|
226
|
+
- **Azure streaming** - Real-time responses from Azure-hosted models
|
|
227
|
+
- **Deployment resolution** - Automatic Azure deployment name handling
|
|
228
|
+
- **Usage tracking** - Azure-specific metrics and pricing
|
|
229
|
+
|
|
230
|
+
**Perfect for:** Real-time Azure OpenAI applications
|
|
231
|
+
|
|
232
|
+
**See the file for complete code examples.**
|
|
233
|
+
|
|
234
|
+
#### `azure-responses-basic.ts` - Azure Responses API
|
|
235
|
+
|
|
236
|
+
Demonstrates new Responses API with Azure OpenAI:
|
|
237
|
+
|
|
238
|
+
- **Azure + Responses API** - Combine Azure hosting with new API
|
|
239
|
+
- **Unified interface** - Same Responses API patterns on Azure
|
|
240
|
+
- **Automatic tracking** - Azure-aware usage tracking
|
|
241
|
+
|
|
242
|
+
**Perfect for:** Azure applications using latest OpenAI features
|
|
243
|
+
|
|
244
|
+
**See the file for complete code examples.**
|
|
245
|
+
|
|
246
|
+
#### `azure-responses-streaming.ts` - Azure Responses Streaming
|
|
247
|
+
|
|
248
|
+
Demonstrates Responses API streaming with Azure OpenAI:
|
|
249
|
+
|
|
250
|
+
- **Azure streaming** - Real-time Responses API on Azure
|
|
251
|
+
- **Event handling** - Process Azure response events
|
|
252
|
+
- **Complete tracking** - Azure metrics with new API
|
|
253
|
+
|
|
254
|
+
**Perfect for:** Real-time Azure applications with Responses API
|
|
255
|
+
|
|
256
|
+
**See the file for complete code examples.**
|
|
257
|
+
|
|
258
|
+
## TypeScript Configuration
|
|
259
|
+
|
|
260
|
+
Ensure your `tsconfig.json` includes:
|
|
261
|
+
|
|
262
|
+
```json
|
|
263
|
+
{
|
|
264
|
+
"compilerOptions": {
|
|
265
|
+
"target": "ES2020",
|
|
266
|
+
"module": "ESNext",
|
|
267
|
+
"moduleResolution": "node",
|
|
268
|
+
"esModuleInterop": true,
|
|
269
|
+
"allowSyntheticDefaultImports": true,
|
|
270
|
+
"strict": true,
|
|
271
|
+
"skipLibCheck": true
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
## Requirements
|
|
277
|
+
|
|
278
|
+
- **Node.js 16+** with TypeScript support
|
|
279
|
+
- **TypeScript 4.5+** for module augmentation features
|
|
280
|
+
- **Valid Revenium API key** (starts with `hak_`)
|
|
281
|
+
- **Valid OpenAI API key** (starts with `sk-`) or Azure OpenAI credentials
|
|
282
|
+
- **OpenAI SDK 5.0+** (5.8+ for Responses API)
|
|
283
|
+
|
|
284
|
+
## Troubleshooting
|
|
285
|
+
|
|
286
|
+
### Module Augmentation Not Working
|
|
287
|
+
|
|
288
|
+
**Problem:** TypeScript doesn't recognize `usageMetadata` in OpenAI SDK calls
|
|
289
|
+
|
|
290
|
+
**Solution:**
|
|
291
|
+
|
|
292
|
+
```typescript
|
|
293
|
+
// ❌ Wrong - missing module augmentation import
|
|
294
|
+
import { initializeReveniumFromEnv } from "@revenium/openai";
|
|
295
|
+
|
|
296
|
+
// ✅ Correct - import for module augmentation
|
|
297
|
+
import { initializeReveniumFromEnv, patchOpenAIInstance } from "@revenium/openai";
|
|
298
|
+
import OpenAI from "openai";
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
### Environment Variables Not Loading
|
|
302
|
+
|
|
303
|
+
**Problem:** `REVENIUM_METERING_API_KEY` or `OPENAI_API_KEY` not found
|
|
304
|
+
|
|
305
|
+
**Solutions:**
|
|
306
|
+
|
|
307
|
+
- Ensure `.env` file is in project root
|
|
308
|
+
- Check variable names match exactly
|
|
309
|
+
- Verify you're importing `dotenv/config` before the middleware
|
|
310
|
+
- Check API keys have correct prefixes (`hak_` for Revenium, `sk-` for OpenAI)
|
|
311
|
+
|
|
312
|
+
### TypeScript Compilation Errors
|
|
313
|
+
|
|
314
|
+
**Problem:** Module resolution or import errors
|
|
315
|
+
|
|
316
|
+
**Solution:** Verify your `tsconfig.json` settings:
|
|
317
|
+
|
|
318
|
+
```json
|
|
319
|
+
{
|
|
320
|
+
"compilerOptions": {
|
|
321
|
+
"moduleResolution": "node",
|
|
322
|
+
"esModuleInterop": true,
|
|
323
|
+
"allowSyntheticDefaultImports": true,
|
|
324
|
+
"strict": true
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
### Azure Configuration Issues
|
|
330
|
+
|
|
331
|
+
**Problem:** Azure OpenAI not working or incorrect pricing
|
|
332
|
+
|
|
333
|
+
**Solutions:**
|
|
334
|
+
|
|
335
|
+
- Verify all Azure environment variables are set (`AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_DEPLOYMENT`)
|
|
336
|
+
- Check deployment name matches your Azure resource
|
|
337
|
+
- Ensure API version is compatible (`2024-12-01-preview` or later recommended)
|
|
338
|
+
- Verify endpoint URL format: `https://your-resource-name.openai.azure.com/`
|
|
339
|
+
|
|
340
|
+
### Debug Mode
|
|
341
|
+
|
|
342
|
+
Enable detailed logging to troubleshoot issues:
|
|
343
|
+
|
|
344
|
+
```bash
|
|
345
|
+
# In .env file
|
|
346
|
+
REVENIUM_DEBUG=true
|
|
347
|
+
|
|
348
|
+
# Then run examples
|
|
349
|
+
npx tsx examples/getting_started.ts
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
## Additional Resources
|
|
353
|
+
|
|
354
|
+
- **Main Documentation**: See root [README.md](https://github.com/revenium/revenium-middleware-openai-node/blob/HEAD/README.md)
|
|
355
|
+
- **API Reference**: [Revenium Metadata Fields](https://revenium.readme.io/reference/meter_ai_completion)
|
|
356
|
+
- **OpenAI Documentation**: [OpenAI API Reference](https://platform.openai.com/docs)
|
|
357
|
+
- **Issues**: [Report bugs](https://github.com/revenium/revenium-middleware-openai-node/issues)
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Azure OpenAI Basic Example
|
|
3
|
+
*
|
|
4
|
+
* Shows how to use Revenium middleware with Azure OpenAI chat completions and embeddings.
|
|
5
|
+
* Demonstrates seamless metadata integration with Azure - all metadata fields are optional!
|
|
6
|
+
*
|
|
7
|
+
* Metadata Options:
|
|
8
|
+
* - Start with basic usage (no metadata) - tracking works automatically
|
|
9
|
+
* - Add subscriber info for user tracking
|
|
10
|
+
* - Include organization/product IDs for business analytics
|
|
11
|
+
* - Use task type and trace ID for detailed analysis
|
|
12
|
+
*
|
|
13
|
+
* For complete metadata field reference, see:
|
|
14
|
+
* https://revenium.readme.io/reference/meter_ai_completion
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import 'dotenv/config';
|
|
18
|
+
import { initializeReveniumFromEnv, patchOpenAIInstance } from '@revenium/openai';
|
|
19
|
+
import { AzureOpenAI } from 'openai';
|
|
20
|
+
|
|
21
|
+
async function azureBasicExample() {
|
|
22
|
+
console.log('️ Azure OpenAI Basic Usage with Seamless Metadata Integration\n');
|
|
23
|
+
|
|
24
|
+
// Initialize Revenium middleware
|
|
25
|
+
const initResult = initializeReveniumFromEnv();
|
|
26
|
+
if (!initResult.success) {
|
|
27
|
+
console.error(' Failed to initialize Revenium:', initResult.message);
|
|
28
|
+
process.exit(1);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Create Azure OpenAI instance and patch it
|
|
32
|
+
const azure = patchOpenAIInstance(
|
|
33
|
+
new AzureOpenAI({
|
|
34
|
+
endpoint: process.env.AZURE_OPENAI_ENDPOINT,
|
|
35
|
+
apiKey: process.env.AZURE_OPENAI_API_KEY,
|
|
36
|
+
apiVersion: process.env.AZURE_OPENAI_API_VERSION || '2024-12-01-preview',
|
|
37
|
+
})
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
console.log(' Azure OpenAI client configured and patched');
|
|
41
|
+
console.log(' Endpoint:', process.env.AZURE_OPENAI_ENDPOINT);
|
|
42
|
+
console.log(' API Version:', process.env.AZURE_OPENAI_API_VERSION || '2024-12-01-preview');
|
|
43
|
+
console.log();
|
|
44
|
+
|
|
45
|
+
// Check if we have a chat model configured
|
|
46
|
+
const deployment = process.env.AZURE_OPENAI_DEPLOYMENT;
|
|
47
|
+
const isChatModel = deployment && !deployment.includes('embedding');
|
|
48
|
+
|
|
49
|
+
if (!isChatModel) {
|
|
50
|
+
console.log('️ Note: Current Azure deployment appears to be for embeddings.');
|
|
51
|
+
console.log(' To test chat completions, update .env to use a chat model:');
|
|
52
|
+
console.log(' - Comment out the embeddings section');
|
|
53
|
+
console.log(' - Uncomment the chat testing section');
|
|
54
|
+
console.log(' - Set AZURE_OPENAI_DEPLOYMENT=gpt-4o');
|
|
55
|
+
console.log('\n Skipping chat examples and testing embeddings instead...\n');
|
|
56
|
+
} else {
|
|
57
|
+
// Example 1: Basic Azure chat completion (no metadata)
|
|
58
|
+
console.log(' Example 1: Basic Azure chat completion (automatic tracking)');
|
|
59
|
+
|
|
60
|
+
const basicResponse = await azure.chat.completions.create({
|
|
61
|
+
model: deployment,
|
|
62
|
+
messages: [{ role: 'user', content: 'What are the benefits of using Azure OpenAI?' }],
|
|
63
|
+
// No usageMetadata - still automatically tracked with Azure provider info!
|
|
64
|
+
// No max_tokens - let response complete naturally
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
console.log(' Response:', basicResponse.choices[0]?.message?.content);
|
|
68
|
+
console.log(' Usage:', basicResponse.usage);
|
|
69
|
+
console.log(' Automatically tracked to Revenium with Azure provider metadata\n');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (isChatModel) {
|
|
73
|
+
// Example 2: Azure chat completion with rich metadata (all optional!)
|
|
74
|
+
console.log(' Example 2: Azure chat completion with rich metadata');
|
|
75
|
+
|
|
76
|
+
const metadataResponse = await azure.chat.completions.create({
|
|
77
|
+
model: deployment,
|
|
78
|
+
messages: [
|
|
79
|
+
{
|
|
80
|
+
role: 'user',
|
|
81
|
+
content: 'Explain how Azure OpenAI differs from standard OpenAI in 3 points.',
|
|
82
|
+
},
|
|
83
|
+
],
|
|
84
|
+
|
|
85
|
+
// Optional metadata for advanced reporting, lineage tracking, and cost allocation
|
|
86
|
+
usageMetadata: {
|
|
87
|
+
// User identification
|
|
88
|
+
subscriber: {
|
|
89
|
+
id: 'azure-user-789',
|
|
90
|
+
email: 'azure-dev@company.com',
|
|
91
|
+
credential: {
|
|
92
|
+
name: 'api-key-prod',
|
|
93
|
+
value: 'key-jkl-012',
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
|
|
97
|
+
// Organization & billing
|
|
98
|
+
organizationId: 'enterprise-corp',
|
|
99
|
+
subscriptionId: 'plan-azure-enterprise-2024',
|
|
100
|
+
|
|
101
|
+
// Product & task tracking
|
|
102
|
+
productId: 'azure-ai-platform',
|
|
103
|
+
taskType: 'azure-comparison',
|
|
104
|
+
agent: 'azure-basic-chat-node',
|
|
105
|
+
|
|
106
|
+
// Session tracking
|
|
107
|
+
traceId: 'azure-' + Date.now(),
|
|
108
|
+
|
|
109
|
+
// Quality metrics
|
|
110
|
+
responseQualityScore: 0.92,
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
console.log(' Response:', metadataResponse.choices[0]?.message?.content);
|
|
115
|
+
console.log(' Usage:', metadataResponse.usage);
|
|
116
|
+
console.log(' Tracked with Azure provider + rich metadata for enterprise analytics\n');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Example 3: Azure embeddings (requires embeddings model)
|
|
120
|
+
console.log(' Example 3: Azure embeddings');
|
|
121
|
+
|
|
122
|
+
if (isChatModel) {
|
|
123
|
+
console.log('️ Note: Current deployment is a chat model (gpt-4o).');
|
|
124
|
+
console.log(' Embeddings require an embedding model like text-embedding-3-large.');
|
|
125
|
+
console.log(' To test embeddings, switch .env to embeddings configuration.');
|
|
126
|
+
console.log(' Skipping embeddings examples.\n');
|
|
127
|
+
} else {
|
|
128
|
+
console.log(' Example 3a: Basic Azure embeddings (automatic tracking)');
|
|
129
|
+
|
|
130
|
+
const basicEmbedding = await azure.embeddings.create({
|
|
131
|
+
model: deployment || 'text-embedding-3-large',
|
|
132
|
+
input:
|
|
133
|
+
'Azure OpenAI provides enterprise-grade AI capabilities with enhanced security and compliance',
|
|
134
|
+
// No usageMetadata - still automatically tracked with Azure provider info!
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
console.log(' Model:', basicEmbedding.model);
|
|
138
|
+
console.log(' Usage:', basicEmbedding.usage);
|
|
139
|
+
console.log(' Embedding dimensions:', basicEmbedding.data[0]?.embedding.length);
|
|
140
|
+
console.log(' Azure embeddings automatically tracked without metadata\n');
|
|
141
|
+
|
|
142
|
+
// Example 4: Azure embeddings with metadata (all optional!)
|
|
143
|
+
console.log(' Example 3b: Azure embeddings with rich metadata');
|
|
144
|
+
|
|
145
|
+
const metadataEmbedding = await azure.embeddings.create({
|
|
146
|
+
model: deployment || 'text-embedding-3-large',
|
|
147
|
+
input:
|
|
148
|
+
'Enterprise document processing with Azure OpenAI embeddings and comprehensive tracking',
|
|
149
|
+
|
|
150
|
+
// All metadata fields are optional - perfect for Azure enterprise use cases!
|
|
151
|
+
// Note: Nested subscriber structure matches Python middleware for consistency
|
|
152
|
+
usageMetadata: {
|
|
153
|
+
subscriber: {
|
|
154
|
+
id: 'azure-embed-user-456',
|
|
155
|
+
email: 'embeddings@enterprise-corp.com',
|
|
156
|
+
credential: {
|
|
157
|
+
name: 'azure-embed-key',
|
|
158
|
+
value: 'embed456',
|
|
159
|
+
},
|
|
160
|
+
},
|
|
161
|
+
organizationId: 'enterprise-corp',
|
|
162
|
+
productId: 'azure-search-platform',
|
|
163
|
+
subscriptionId: 'sub-azure-premium-999',
|
|
164
|
+
taskType: 'enterprise-document-embedding',
|
|
165
|
+
traceId: `azure-embed-${Date.now()}`,
|
|
166
|
+
agent: 'azure-basic-embeddings-node',
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
console.log(' Model:', metadataEmbedding.model);
|
|
171
|
+
console.log(' Usage:', metadataEmbedding.usage);
|
|
172
|
+
console.log(' Embedding dimensions:', metadataEmbedding.data[0]?.embedding.length);
|
|
173
|
+
console.log(' Azure embeddings tracked with metadata for enterprise analytics\n');
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Summary
|
|
177
|
+
console.log(' Azure OpenAI Summary:');
|
|
178
|
+
console.log(' Azure OpenAI automatically detected and tracked');
|
|
179
|
+
console.log(' Model name resolution for accurate pricing');
|
|
180
|
+
console.log(' Provider metadata includes "Azure" for analytics');
|
|
181
|
+
if (isChatModel) {
|
|
182
|
+
console.log(' Chat completions work with or without metadata');
|
|
183
|
+
} else {
|
|
184
|
+
console.log(' Embeddings work with or without metadata');
|
|
185
|
+
}
|
|
186
|
+
console.log(' All metadata fields are optional');
|
|
187
|
+
console.log(' No type casting required - native TypeScript support');
|
|
188
|
+
console.log(' Enterprise-grade tracking with Azure compliance');
|
|
189
|
+
|
|
190
|
+
if (!isChatModel) {
|
|
191
|
+
console.log('\n To test Azure chat completions:');
|
|
192
|
+
console.log(' 1. Edit .env file');
|
|
193
|
+
console.log(' 2. Comment out embeddings section');
|
|
194
|
+
console.log(' 3. Uncomment chat section');
|
|
195
|
+
console.log(' 4. Run this example again');
|
|
196
|
+
} else {
|
|
197
|
+
console.log('\n To test Azure embeddings:');
|
|
198
|
+
console.log(' 1. Edit .env file');
|
|
199
|
+
console.log(' 2. Comment out chat section');
|
|
200
|
+
console.log(' 3. Uncomment embeddings section');
|
|
201
|
+
console.log(' 4. Run this example again');
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Run the example
|
|
206
|
+
azureBasicExample().catch(console.error);
|