@axon-ai/openai-tracer 1.0.3
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/README.md +276 -0
- package/dist/index.d.mts +214 -0
- package/dist/index.d.ts +214 -0
- package/dist/index.js +425 -0
- package/dist/index.mjs +386 -0
- package/package.json +48 -0
package/README.md
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
# OpenAI Function Calling Tracer
|
|
2
|
+
|
|
3
|
+
A comprehensive tracing solution for OpenAI Function Calling agents, providing detailed monitoring, cost analysis, and performance insights.
|
|
4
|
+
|
|
5
|
+
## 🚀 Features
|
|
6
|
+
|
|
7
|
+
- **Function Call Tracking**: Monitor all function calls with detailed parameters and results
|
|
8
|
+
- **Tool Selection Analysis**: Track which tools are selected and why
|
|
9
|
+
- **Cost Calculation**: Automatic cost calculation based on token usage and model pricing
|
|
10
|
+
- **Performance Metrics**: Latency tracking and performance analysis
|
|
11
|
+
- **Error Monitoring**: Comprehensive error tracking and debugging
|
|
12
|
+
- **Real-time Dashboard**: Live visualization of agent execution
|
|
13
|
+
- **Conversation Flow**: Track multi-turn conversations and context
|
|
14
|
+
|
|
15
|
+
## 📦 Installation
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install @axon-ai/openai-tracer openai
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## 🎯 Quick Start
|
|
22
|
+
|
|
23
|
+
### Basic Usage
|
|
24
|
+
|
|
25
|
+
```javascript
|
|
26
|
+
import OpenAI from 'openai';
|
|
27
|
+
import { createOpenAITracer, TracedOpenAI } from '@axon-ai/openai-tracer';
|
|
28
|
+
|
|
29
|
+
// Initialize OpenAI client
|
|
30
|
+
const openai = new OpenAI({
|
|
31
|
+
apiKey: process.env.OPENAI_API_KEY,
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
// Create tracer
|
|
35
|
+
const tracer = createOpenAITracer({
|
|
36
|
+
projectName: 'my-agent',
|
|
37
|
+
metadata: {
|
|
38
|
+
version: '1.0.0',
|
|
39
|
+
environment: 'production',
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// Create traced OpenAI client
|
|
44
|
+
const tracedOpenAI = new TracedOpenAI(openai, tracer);
|
|
45
|
+
|
|
46
|
+
// Use the traced client
|
|
47
|
+
const response = await tracedOpenAI.createChatCompletion({
|
|
48
|
+
model: 'gpt-4',
|
|
49
|
+
messages: [
|
|
50
|
+
{ role: 'user', content: 'What\'s the weather in NYC?' }
|
|
51
|
+
],
|
|
52
|
+
tools: [/* your tools */],
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### Advanced Configuration
|
|
57
|
+
|
|
58
|
+
```javascript
|
|
59
|
+
const tracer = createOpenAITracer({
|
|
60
|
+
projectName: 'weather-agent',
|
|
61
|
+
endpoint: 'http://localhost:3000', // Custom trace server
|
|
62
|
+
metadata: {
|
|
63
|
+
agentType: 'weather',
|
|
64
|
+
version: '2.1.0',
|
|
65
|
+
environment: 'staging',
|
|
66
|
+
team: 'ai-platform',
|
|
67
|
+
},
|
|
68
|
+
autoConnect: true, // Auto-connect to trace server
|
|
69
|
+
});
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## 🔧 API Reference
|
|
73
|
+
|
|
74
|
+
### OpenAITracer
|
|
75
|
+
|
|
76
|
+
#### Constructor Options
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
interface OpenAITraceConfig {
|
|
80
|
+
projectName?: string; // Project identifier
|
|
81
|
+
endpoint?: string; // Trace server endpoint
|
|
82
|
+
metadata?: Record<string, any>; // Custom metadata
|
|
83
|
+
autoConnect?: boolean; // Auto-connect to server
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
#### Methods
|
|
88
|
+
|
|
89
|
+
##### `traceFunctionCallStart(functionName, arguments, model, messages, tools?)`
|
|
90
|
+
Track the start of a function call.
|
|
91
|
+
|
|
92
|
+
##### `traceFunctionCallEnd(eventId, result, cost, latency, tokens?)`
|
|
93
|
+
Track the completion of a function call.
|
|
94
|
+
|
|
95
|
+
##### `traceToolSelection(availableTools, selectedTool, reasoning?, confidence?)`
|
|
96
|
+
Track tool selection decisions.
|
|
97
|
+
|
|
98
|
+
##### `traceConversationTurn(userMessage, assistantResponse, model, tokens?, cost?)`
|
|
99
|
+
Track conversation turns.
|
|
100
|
+
|
|
101
|
+
##### `traceError(error, context, functionName?, arguments?)`
|
|
102
|
+
Track errors and exceptions.
|
|
103
|
+
|
|
104
|
+
### TracedOpenAI
|
|
105
|
+
|
|
106
|
+
A wrapper around the OpenAI client that automatically traces all interactions.
|
|
107
|
+
|
|
108
|
+
#### Methods
|
|
109
|
+
|
|
110
|
+
##### `createChatCompletion(params)`
|
|
111
|
+
Enhanced chat completion with automatic tracing.
|
|
112
|
+
|
|
113
|
+
## 📊 Dashboard Integration
|
|
114
|
+
|
|
115
|
+
The tracer automatically sends data to the Agent Trace dashboard for visualization:
|
|
116
|
+
|
|
117
|
+
- **Function Call Flow**: Visual representation of function calls
|
|
118
|
+
- **Cost Analysis**: Detailed cost breakdown by function and model
|
|
119
|
+
- **Performance Metrics**: Latency and throughput analysis
|
|
120
|
+
- **Tool Usage**: Which tools are used most frequently
|
|
121
|
+
- **Error Tracking**: Error rates and debugging information
|
|
122
|
+
|
|
123
|
+
## 🎨 Example Agents
|
|
124
|
+
|
|
125
|
+
### Weather Agent
|
|
126
|
+
|
|
127
|
+
```javascript
|
|
128
|
+
import { createOpenAITracer, TracedOpenAI } from '@axon-ai/openai-tracer';
|
|
129
|
+
|
|
130
|
+
const tracer = createOpenAITracer({ projectName: 'weather-agent' });
|
|
131
|
+
const tracedOpenAI = new TracedOpenAI(openai, tracer);
|
|
132
|
+
|
|
133
|
+
const tools = [
|
|
134
|
+
{
|
|
135
|
+
type: 'function',
|
|
136
|
+
function: {
|
|
137
|
+
name: 'getCurrentWeather',
|
|
138
|
+
description: 'Get current weather',
|
|
139
|
+
parameters: {
|
|
140
|
+
type: 'object',
|
|
141
|
+
properties: {
|
|
142
|
+
location: { type: 'string' }
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
];
|
|
148
|
+
|
|
149
|
+
const response = await tracedOpenAI.createChatCompletion({
|
|
150
|
+
model: 'gpt-4',
|
|
151
|
+
messages: [{ role: 'user', content: 'Weather in NYC?' }],
|
|
152
|
+
tools,
|
|
153
|
+
});
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Stock Analysis Agent
|
|
157
|
+
|
|
158
|
+
```javascript
|
|
159
|
+
const tracer = createOpenAITracer({ projectName: 'stock-agent' });
|
|
160
|
+
const tracedOpenAI = new TracedOpenAI(openai, tracer);
|
|
161
|
+
|
|
162
|
+
const tools = [
|
|
163
|
+
{
|
|
164
|
+
type: 'function',
|
|
165
|
+
function: {
|
|
166
|
+
name: 'getStockPrice',
|
|
167
|
+
description: 'Get stock price',
|
|
168
|
+
parameters: {
|
|
169
|
+
type: 'object',
|
|
170
|
+
properties: {
|
|
171
|
+
symbol: { type: 'string' }
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
];
|
|
177
|
+
|
|
178
|
+
const response = await tracedOpenAI.createChatCompletion({
|
|
179
|
+
model: 'gpt-4',
|
|
180
|
+
messages: [{ role: 'user', content: 'AAPL stock price?' }],
|
|
181
|
+
tools,
|
|
182
|
+
});
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## 🔍 Event Types
|
|
186
|
+
|
|
187
|
+
The tracer tracks several types of events:
|
|
188
|
+
|
|
189
|
+
### Function Call Events
|
|
190
|
+
- `function_call_start`: When a function call begins
|
|
191
|
+
- `function_call_end`: When a function call completes
|
|
192
|
+
|
|
193
|
+
### Tool Selection Events
|
|
194
|
+
- `tool_selection`: When the model selects a tool
|
|
195
|
+
|
|
196
|
+
### Conversation Events
|
|
197
|
+
- `conversation_turn`: Each user-assistant interaction
|
|
198
|
+
|
|
199
|
+
### Error Events
|
|
200
|
+
- `error`: When errors occur during execution
|
|
201
|
+
|
|
202
|
+
## 💰 Cost Calculation
|
|
203
|
+
|
|
204
|
+
Automatic cost calculation based on:
|
|
205
|
+
|
|
206
|
+
- **Model Pricing**: Current OpenAI pricing for different models
|
|
207
|
+
- **Token Usage**: Prompt and completion tokens
|
|
208
|
+
- **Function Calls**: Additional costs for function calling
|
|
209
|
+
|
|
210
|
+
Supported models:
|
|
211
|
+
- GPT-4: $0.03/1K prompt, $0.06/1K completion
|
|
212
|
+
- GPT-4 Turbo: $0.01/1K prompt, $0.03/1K completion
|
|
213
|
+
- GPT-3.5 Turbo: $0.001/1K prompt, $0.002/1K completion
|
|
214
|
+
|
|
215
|
+
## 🚨 Error Handling
|
|
216
|
+
|
|
217
|
+
The tracer provides comprehensive error tracking:
|
|
218
|
+
|
|
219
|
+
```javascript
|
|
220
|
+
try {
|
|
221
|
+
const response = await tracedOpenAI.createChatCompletion(params);
|
|
222
|
+
} catch (error) {
|
|
223
|
+
// Error is automatically traced
|
|
224
|
+
console.error('API call failed:', error);
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## 🔧 Development
|
|
229
|
+
|
|
230
|
+
### Building
|
|
231
|
+
|
|
232
|
+
```bash
|
|
233
|
+
npm run build
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
### Development Mode
|
|
237
|
+
|
|
238
|
+
```bash
|
|
239
|
+
npm run dev
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
### Testing
|
|
243
|
+
|
|
244
|
+
```bash
|
|
245
|
+
npm test
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
## 📈 Performance
|
|
249
|
+
|
|
250
|
+
The tracer is designed for minimal overhead:
|
|
251
|
+
|
|
252
|
+
- **Async Operations**: Non-blocking event queuing
|
|
253
|
+
- **Batch Processing**: Efficient event batching
|
|
254
|
+
- **Memory Management**: Automatic cleanup of old events
|
|
255
|
+
- **Network Optimization**: Compressed data transmission
|
|
256
|
+
|
|
257
|
+
## 🤝 Contributing
|
|
258
|
+
|
|
259
|
+
1. Fork the repository
|
|
260
|
+
2. Create a feature branch
|
|
261
|
+
3. Make your changes
|
|
262
|
+
4. Add tests
|
|
263
|
+
5. Submit a pull request
|
|
264
|
+
|
|
265
|
+
## 📄 License
|
|
266
|
+
|
|
267
|
+
MIT License - see LICENSE file for details.
|
|
268
|
+
|
|
269
|
+
## 🔄 Changelog
|
|
270
|
+
|
|
271
|
+
### v1.0.0
|
|
272
|
+
- Initial release
|
|
273
|
+
- OpenAI Function Calling support
|
|
274
|
+
- Cost calculation
|
|
275
|
+
- Performance metrics
|
|
276
|
+
- Dashboard integration
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { EventEmitter } from 'events';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* OpenAI Function Calling Tracer
|
|
5
|
+
* Tracks OpenAI function calling agents with detailed event logging
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
interface OpenAIFunctionCall {
|
|
9
|
+
id: string;
|
|
10
|
+
type: 'function';
|
|
11
|
+
function: {
|
|
12
|
+
name: string;
|
|
13
|
+
arguments: string;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
interface OpenAIToolCall {
|
|
17
|
+
id: string;
|
|
18
|
+
type: 'function';
|
|
19
|
+
function: {
|
|
20
|
+
name: string;
|
|
21
|
+
arguments: string;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
interface OpenAIMessage {
|
|
25
|
+
role: 'system' | 'user' | 'assistant' | 'tool';
|
|
26
|
+
content: string | null;
|
|
27
|
+
tool_calls?: OpenAIToolCall[];
|
|
28
|
+
tool_call_id?: string;
|
|
29
|
+
name?: string;
|
|
30
|
+
}
|
|
31
|
+
interface OpenAITool {
|
|
32
|
+
type: 'function';
|
|
33
|
+
function: {
|
|
34
|
+
name: string;
|
|
35
|
+
description: string;
|
|
36
|
+
parameters: any;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
interface OpenAITraceEvent {
|
|
40
|
+
eventId: string;
|
|
41
|
+
traceId: string;
|
|
42
|
+
timestamp: number;
|
|
43
|
+
type: 'function_call_start' | 'function_call_end' | 'tool_selection' | 'conversation_turn' | 'error';
|
|
44
|
+
data: any;
|
|
45
|
+
metadata?: Record<string, any>;
|
|
46
|
+
}
|
|
47
|
+
interface OpenAITraceConfig {
|
|
48
|
+
projectName?: string;
|
|
49
|
+
endpoint?: string;
|
|
50
|
+
metadata?: Record<string, any>;
|
|
51
|
+
autoConnect?: boolean;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* OpenAI Function Calling Tracer
|
|
55
|
+
*
|
|
56
|
+
* This class provides comprehensive tracing capabilities for OpenAI function calling agents.
|
|
57
|
+
* It tracks function calls, tool selections, conversation turns, and errors, sending
|
|
58
|
+
* real-time events to the Agent Trace Visualizer backend via WebSocket.
|
|
59
|
+
*
|
|
60
|
+
* Features:
|
|
61
|
+
* - Real-time event queuing and flushing
|
|
62
|
+
* - WebSocket connection management
|
|
63
|
+
* - Cost calculation for different OpenAI models
|
|
64
|
+
* - Error tracking and reporting
|
|
65
|
+
* - Automatic reconnection handling
|
|
66
|
+
*/
|
|
67
|
+
declare class OpenAITracer extends EventEmitter {
|
|
68
|
+
private traceId;
|
|
69
|
+
private projectName;
|
|
70
|
+
private endpoint;
|
|
71
|
+
private metadata;
|
|
72
|
+
private eventQueue;
|
|
73
|
+
private isConnected;
|
|
74
|
+
private client;
|
|
75
|
+
private flushInterval;
|
|
76
|
+
/**
|
|
77
|
+
* Creates a new OpenAI tracer instance
|
|
78
|
+
*
|
|
79
|
+
* @param config - Configuration object for the tracer
|
|
80
|
+
* @param config.projectName - Project name for organizing traces (default: 'openai-agent')
|
|
81
|
+
* @param config.endpoint - Backend server endpoint (default: 'http://localhost:3000')
|
|
82
|
+
* @param config.metadata - Additional metadata to include with all events
|
|
83
|
+
* @param config.autoConnect - Whether to automatically connect to the server (default: true)
|
|
84
|
+
*/
|
|
85
|
+
constructor(config?: OpenAITraceConfig);
|
|
86
|
+
/**
|
|
87
|
+
* Establishes WebSocket connection to the trace server
|
|
88
|
+
*
|
|
89
|
+
* This method creates a Socket.IO client connection to the backend server,
|
|
90
|
+
* sets up event listeners for connection status, and starts the periodic
|
|
91
|
+
* event flushing mechanism.
|
|
92
|
+
*
|
|
93
|
+
* @throws Error if connection fails
|
|
94
|
+
*/
|
|
95
|
+
connect(): Promise<void>;
|
|
96
|
+
/**
|
|
97
|
+
* Disconnect from the trace server
|
|
98
|
+
*/
|
|
99
|
+
disconnect(): void;
|
|
100
|
+
/**
|
|
101
|
+
* Records the start of a function call execution
|
|
102
|
+
*
|
|
103
|
+
* This method creates and queues a function call start event, capturing
|
|
104
|
+
* the function name, arguments, model, messages, and available tools.
|
|
105
|
+
* It returns an event ID that can be used to correlate with the end event.
|
|
106
|
+
*
|
|
107
|
+
* @param functionName - Name of the function being called
|
|
108
|
+
* @param functionArguments - Arguments passed to the function
|
|
109
|
+
* @param model - OpenAI model being used (e.g., 'gpt-4', 'gpt-3.5-turbo')
|
|
110
|
+
* @param messages - Array of conversation messages
|
|
111
|
+
* @param tools - Optional array of available tools
|
|
112
|
+
* @returns Event ID for correlating with the corresponding end event
|
|
113
|
+
*/
|
|
114
|
+
traceFunctionCallStart(functionName: string, functionArguments: any, model: string, messages: OpenAIMessage[], tools?: OpenAITool[]): string;
|
|
115
|
+
/**
|
|
116
|
+
* Track function call end
|
|
117
|
+
*/
|
|
118
|
+
traceFunctionCallEnd(eventId: string, result: any, cost: number, latency: number, tokens?: {
|
|
119
|
+
prompt: number;
|
|
120
|
+
completion: number;
|
|
121
|
+
total: number;
|
|
122
|
+
}): void;
|
|
123
|
+
/**
|
|
124
|
+
* Track tool selection
|
|
125
|
+
*/
|
|
126
|
+
traceToolSelection(availableTools: OpenAITool[], selectedTool: OpenAITool, reasoning?: string, confidence?: number): void;
|
|
127
|
+
/**
|
|
128
|
+
* Track conversation turn
|
|
129
|
+
*/
|
|
130
|
+
traceConversationTurn(userMessage: string, assistantResponse: string, model: string, tokens?: {
|
|
131
|
+
prompt: number;
|
|
132
|
+
completion: number;
|
|
133
|
+
total: number;
|
|
134
|
+
}, cost?: number): void;
|
|
135
|
+
/**
|
|
136
|
+
* Track error
|
|
137
|
+
*/
|
|
138
|
+
traceError(error: Error, context: string, functionName?: string, functionArguments?: any): void;
|
|
139
|
+
/**
|
|
140
|
+
* Add event to queue
|
|
141
|
+
*/
|
|
142
|
+
private addEvent;
|
|
143
|
+
/**
|
|
144
|
+
* Flush events to server
|
|
145
|
+
*/
|
|
146
|
+
flushQueue(): Promise<void>;
|
|
147
|
+
/**
|
|
148
|
+
* Extract conversation context from messages
|
|
149
|
+
*/
|
|
150
|
+
private extractConversationContext;
|
|
151
|
+
/**
|
|
152
|
+
* Get current turn number
|
|
153
|
+
*/
|
|
154
|
+
private getTurnNumber;
|
|
155
|
+
/**
|
|
156
|
+
* Calculate cost based on tokens and model
|
|
157
|
+
*/
|
|
158
|
+
calculateCost(tokens: {
|
|
159
|
+
prompt: number;
|
|
160
|
+
completion: number;
|
|
161
|
+
total: number;
|
|
162
|
+
}, model: string): number;
|
|
163
|
+
/**
|
|
164
|
+
* Get trace ID
|
|
165
|
+
*/
|
|
166
|
+
getTraceId(): string;
|
|
167
|
+
/**
|
|
168
|
+
* Check if connected
|
|
169
|
+
*/
|
|
170
|
+
isConnectedToServer(): boolean;
|
|
171
|
+
/**
|
|
172
|
+
* Get current event queue size
|
|
173
|
+
*/
|
|
174
|
+
getQueueSize(): number;
|
|
175
|
+
/**
|
|
176
|
+
* Clear event queue
|
|
177
|
+
*/
|
|
178
|
+
clearQueue(): void;
|
|
179
|
+
/**
|
|
180
|
+
* Shutdown tracer
|
|
181
|
+
*/
|
|
182
|
+
shutdown(): Promise<void>;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Create a new OpenAI tracer instance
|
|
186
|
+
*/
|
|
187
|
+
declare function createOpenAITracer(config?: OpenAITraceConfig): OpenAITracer;
|
|
188
|
+
/**
|
|
189
|
+
* OpenAI Function Calling Wrapper
|
|
190
|
+
* Wraps OpenAI API calls with automatic tracing
|
|
191
|
+
*/
|
|
192
|
+
declare class TracedOpenAI {
|
|
193
|
+
private openai;
|
|
194
|
+
private tracer;
|
|
195
|
+
constructor(openaiClient: any, tracer: OpenAITracer);
|
|
196
|
+
/**
|
|
197
|
+
* Traced chat completion with function calling
|
|
198
|
+
*/
|
|
199
|
+
createChatCompletion(params: {
|
|
200
|
+
model: string;
|
|
201
|
+
messages: OpenAIMessage[];
|
|
202
|
+
tools?: OpenAITool[];
|
|
203
|
+
tool_choice?: 'auto' | 'none' | {
|
|
204
|
+
type: 'function';
|
|
205
|
+
function: {
|
|
206
|
+
name: string;
|
|
207
|
+
};
|
|
208
|
+
};
|
|
209
|
+
temperature?: number;
|
|
210
|
+
max_tokens?: number;
|
|
211
|
+
}): Promise<any>;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export { type OpenAIFunctionCall, type OpenAIMessage, type OpenAITool, type OpenAIToolCall, type OpenAITraceConfig, type OpenAITraceEvent, OpenAITracer, TracedOpenAI, createOpenAITracer, OpenAITracer as default };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { EventEmitter } from 'events';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* OpenAI Function Calling Tracer
|
|
5
|
+
* Tracks OpenAI function calling agents with detailed event logging
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
interface OpenAIFunctionCall {
|
|
9
|
+
id: string;
|
|
10
|
+
type: 'function';
|
|
11
|
+
function: {
|
|
12
|
+
name: string;
|
|
13
|
+
arguments: string;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
interface OpenAIToolCall {
|
|
17
|
+
id: string;
|
|
18
|
+
type: 'function';
|
|
19
|
+
function: {
|
|
20
|
+
name: string;
|
|
21
|
+
arguments: string;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
interface OpenAIMessage {
|
|
25
|
+
role: 'system' | 'user' | 'assistant' | 'tool';
|
|
26
|
+
content: string | null;
|
|
27
|
+
tool_calls?: OpenAIToolCall[];
|
|
28
|
+
tool_call_id?: string;
|
|
29
|
+
name?: string;
|
|
30
|
+
}
|
|
31
|
+
interface OpenAITool {
|
|
32
|
+
type: 'function';
|
|
33
|
+
function: {
|
|
34
|
+
name: string;
|
|
35
|
+
description: string;
|
|
36
|
+
parameters: any;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
interface OpenAITraceEvent {
|
|
40
|
+
eventId: string;
|
|
41
|
+
traceId: string;
|
|
42
|
+
timestamp: number;
|
|
43
|
+
type: 'function_call_start' | 'function_call_end' | 'tool_selection' | 'conversation_turn' | 'error';
|
|
44
|
+
data: any;
|
|
45
|
+
metadata?: Record<string, any>;
|
|
46
|
+
}
|
|
47
|
+
interface OpenAITraceConfig {
|
|
48
|
+
projectName?: string;
|
|
49
|
+
endpoint?: string;
|
|
50
|
+
metadata?: Record<string, any>;
|
|
51
|
+
autoConnect?: boolean;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* OpenAI Function Calling Tracer
|
|
55
|
+
*
|
|
56
|
+
* This class provides comprehensive tracing capabilities for OpenAI function calling agents.
|
|
57
|
+
* It tracks function calls, tool selections, conversation turns, and errors, sending
|
|
58
|
+
* real-time events to the Agent Trace Visualizer backend via WebSocket.
|
|
59
|
+
*
|
|
60
|
+
* Features:
|
|
61
|
+
* - Real-time event queuing and flushing
|
|
62
|
+
* - WebSocket connection management
|
|
63
|
+
* - Cost calculation for different OpenAI models
|
|
64
|
+
* - Error tracking and reporting
|
|
65
|
+
* - Automatic reconnection handling
|
|
66
|
+
*/
|
|
67
|
+
declare class OpenAITracer extends EventEmitter {
|
|
68
|
+
private traceId;
|
|
69
|
+
private projectName;
|
|
70
|
+
private endpoint;
|
|
71
|
+
private metadata;
|
|
72
|
+
private eventQueue;
|
|
73
|
+
private isConnected;
|
|
74
|
+
private client;
|
|
75
|
+
private flushInterval;
|
|
76
|
+
/**
|
|
77
|
+
* Creates a new OpenAI tracer instance
|
|
78
|
+
*
|
|
79
|
+
* @param config - Configuration object for the tracer
|
|
80
|
+
* @param config.projectName - Project name for organizing traces (default: 'openai-agent')
|
|
81
|
+
* @param config.endpoint - Backend server endpoint (default: 'http://localhost:3000')
|
|
82
|
+
* @param config.metadata - Additional metadata to include with all events
|
|
83
|
+
* @param config.autoConnect - Whether to automatically connect to the server (default: true)
|
|
84
|
+
*/
|
|
85
|
+
constructor(config?: OpenAITraceConfig);
|
|
86
|
+
/**
|
|
87
|
+
* Establishes WebSocket connection to the trace server
|
|
88
|
+
*
|
|
89
|
+
* This method creates a Socket.IO client connection to the backend server,
|
|
90
|
+
* sets up event listeners for connection status, and starts the periodic
|
|
91
|
+
* event flushing mechanism.
|
|
92
|
+
*
|
|
93
|
+
* @throws Error if connection fails
|
|
94
|
+
*/
|
|
95
|
+
connect(): Promise<void>;
|
|
96
|
+
/**
|
|
97
|
+
* Disconnect from the trace server
|
|
98
|
+
*/
|
|
99
|
+
disconnect(): void;
|
|
100
|
+
/**
|
|
101
|
+
* Records the start of a function call execution
|
|
102
|
+
*
|
|
103
|
+
* This method creates and queues a function call start event, capturing
|
|
104
|
+
* the function name, arguments, model, messages, and available tools.
|
|
105
|
+
* It returns an event ID that can be used to correlate with the end event.
|
|
106
|
+
*
|
|
107
|
+
* @param functionName - Name of the function being called
|
|
108
|
+
* @param functionArguments - Arguments passed to the function
|
|
109
|
+
* @param model - OpenAI model being used (e.g., 'gpt-4', 'gpt-3.5-turbo')
|
|
110
|
+
* @param messages - Array of conversation messages
|
|
111
|
+
* @param tools - Optional array of available tools
|
|
112
|
+
* @returns Event ID for correlating with the corresponding end event
|
|
113
|
+
*/
|
|
114
|
+
traceFunctionCallStart(functionName: string, functionArguments: any, model: string, messages: OpenAIMessage[], tools?: OpenAITool[]): string;
|
|
115
|
+
/**
|
|
116
|
+
* Track function call end
|
|
117
|
+
*/
|
|
118
|
+
traceFunctionCallEnd(eventId: string, result: any, cost: number, latency: number, tokens?: {
|
|
119
|
+
prompt: number;
|
|
120
|
+
completion: number;
|
|
121
|
+
total: number;
|
|
122
|
+
}): void;
|
|
123
|
+
/**
|
|
124
|
+
* Track tool selection
|
|
125
|
+
*/
|
|
126
|
+
traceToolSelection(availableTools: OpenAITool[], selectedTool: OpenAITool, reasoning?: string, confidence?: number): void;
|
|
127
|
+
/**
|
|
128
|
+
* Track conversation turn
|
|
129
|
+
*/
|
|
130
|
+
traceConversationTurn(userMessage: string, assistantResponse: string, model: string, tokens?: {
|
|
131
|
+
prompt: number;
|
|
132
|
+
completion: number;
|
|
133
|
+
total: number;
|
|
134
|
+
}, cost?: number): void;
|
|
135
|
+
/**
|
|
136
|
+
* Track error
|
|
137
|
+
*/
|
|
138
|
+
traceError(error: Error, context: string, functionName?: string, functionArguments?: any): void;
|
|
139
|
+
/**
|
|
140
|
+
* Add event to queue
|
|
141
|
+
*/
|
|
142
|
+
private addEvent;
|
|
143
|
+
/**
|
|
144
|
+
* Flush events to server
|
|
145
|
+
*/
|
|
146
|
+
flushQueue(): Promise<void>;
|
|
147
|
+
/**
|
|
148
|
+
* Extract conversation context from messages
|
|
149
|
+
*/
|
|
150
|
+
private extractConversationContext;
|
|
151
|
+
/**
|
|
152
|
+
* Get current turn number
|
|
153
|
+
*/
|
|
154
|
+
private getTurnNumber;
|
|
155
|
+
/**
|
|
156
|
+
* Calculate cost based on tokens and model
|
|
157
|
+
*/
|
|
158
|
+
calculateCost(tokens: {
|
|
159
|
+
prompt: number;
|
|
160
|
+
completion: number;
|
|
161
|
+
total: number;
|
|
162
|
+
}, model: string): number;
|
|
163
|
+
/**
|
|
164
|
+
* Get trace ID
|
|
165
|
+
*/
|
|
166
|
+
getTraceId(): string;
|
|
167
|
+
/**
|
|
168
|
+
* Check if connected
|
|
169
|
+
*/
|
|
170
|
+
isConnectedToServer(): boolean;
|
|
171
|
+
/**
|
|
172
|
+
* Get current event queue size
|
|
173
|
+
*/
|
|
174
|
+
getQueueSize(): number;
|
|
175
|
+
/**
|
|
176
|
+
* Clear event queue
|
|
177
|
+
*/
|
|
178
|
+
clearQueue(): void;
|
|
179
|
+
/**
|
|
180
|
+
* Shutdown tracer
|
|
181
|
+
*/
|
|
182
|
+
shutdown(): Promise<void>;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Create a new OpenAI tracer instance
|
|
186
|
+
*/
|
|
187
|
+
declare function createOpenAITracer(config?: OpenAITraceConfig): OpenAITracer;
|
|
188
|
+
/**
|
|
189
|
+
* OpenAI Function Calling Wrapper
|
|
190
|
+
* Wraps OpenAI API calls with automatic tracing
|
|
191
|
+
*/
|
|
192
|
+
declare class TracedOpenAI {
|
|
193
|
+
private openai;
|
|
194
|
+
private tracer;
|
|
195
|
+
constructor(openaiClient: any, tracer: OpenAITracer);
|
|
196
|
+
/**
|
|
197
|
+
* Traced chat completion with function calling
|
|
198
|
+
*/
|
|
199
|
+
createChatCompletion(params: {
|
|
200
|
+
model: string;
|
|
201
|
+
messages: OpenAIMessage[];
|
|
202
|
+
tools?: OpenAITool[];
|
|
203
|
+
tool_choice?: 'auto' | 'none' | {
|
|
204
|
+
type: 'function';
|
|
205
|
+
function: {
|
|
206
|
+
name: string;
|
|
207
|
+
};
|
|
208
|
+
};
|
|
209
|
+
temperature?: number;
|
|
210
|
+
max_tokens?: number;
|
|
211
|
+
}): Promise<any>;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export { type OpenAIFunctionCall, type OpenAIMessage, type OpenAITool, type OpenAIToolCall, type OpenAITraceConfig, type OpenAITraceEvent, OpenAITracer, TracedOpenAI, createOpenAITracer, OpenAITracer as default };
|