@evalguard/openai 1.1.1
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/LICENSE +201 -0
- package/README.md +123 -0
- package/dist/cost.d.ts +2 -0
- package/dist/cost.d.ts.map +1 -0
- package/dist/cost.js +6 -0
- package/dist/cost.js.map +1 -0
- package/dist/guardrail-client.d.ts +8 -0
- package/dist/guardrail-client.d.ts.map +1 -0
- package/dist/guardrail-client.js +21 -0
- package/dist/guardrail-client.js.map +1 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +533 -0
- package/dist/index.js.map +1 -0
- package/package.json +70 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for describing the origin of the Work and
|
|
141
|
+
reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Support. While redistributing the Work or
|
|
166
|
+
Derivative Works thereof, You may choose to offer, and charge a
|
|
167
|
+
fee for, acceptance of support, warranty, indemnity, or other
|
|
168
|
+
liability obligations and/or rights consistent with this License.
|
|
169
|
+
However, in accepting such obligations, You may act only on Your
|
|
170
|
+
own behalf and on Your sole responsibility, not on behalf of any
|
|
171
|
+
other Contributor, and only if You agree to indemnify, defend,
|
|
172
|
+
and hold each Contributor harmless for any liability incurred by,
|
|
173
|
+
or claims asserted against, such Contributor by reason of your
|
|
174
|
+
accepting any such warranty or support.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2024-2026 EvalGuard, Inc.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# @evalguard/openai
|
|
2
|
+
|
|
3
|
+
Drop-in OpenAI SDK wrapper that adds real-time guardrails, trace logging, and cost tracking via [EvalGuard](https://evalguard.ai).
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @evalguard/openai openai
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import OpenAI from "openai";
|
|
15
|
+
import { wrapOpenAI } from "@evalguard/openai";
|
|
16
|
+
|
|
17
|
+
const openai = wrapOpenAI(new OpenAI(), {
|
|
18
|
+
apiKey: "eg_...",
|
|
19
|
+
projectId: "proj_...",
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
// Use exactly like the normal OpenAI SDK — guardrails are automatic
|
|
23
|
+
const response = await openai.chat.completions.create({
|
|
24
|
+
model: "gpt-4o",
|
|
25
|
+
messages: [{ role: "user", content: "Hello, how are you?" }],
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
console.log(response.choices[0].message.content);
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Streaming
|
|
32
|
+
|
|
33
|
+
Streaming works transparently. The wrapper intercepts chunks to log the assembled response without affecting stream behavior.
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
const stream = await openai.chat.completions.create({
|
|
37
|
+
model: "gpt-4o",
|
|
38
|
+
messages: [{ role: "user", content: "Write a poem about AI safety" }],
|
|
39
|
+
stream: true,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
for await (const chunk of stream) {
|
|
43
|
+
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Configuration
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
50
|
+
const openai = wrapOpenAI(new OpenAI(), {
|
|
51
|
+
// Required: your EvalGuard API key
|
|
52
|
+
apiKey: "eg_...",
|
|
53
|
+
|
|
54
|
+
// Optional: EvalGuard API base URL (default: https://evalguard.ai/api/v1)
|
|
55
|
+
baseUrl: "https://your-evalguard-instance.com/api/v1",
|
|
56
|
+
|
|
57
|
+
// Optional: block requests that fail guardrails (default: true)
|
|
58
|
+
blockOnViolation: true,
|
|
59
|
+
|
|
60
|
+
// Optional: log all requests to EvalGuard (default: true)
|
|
61
|
+
enableLogging: true,
|
|
62
|
+
|
|
63
|
+
// Optional: project ID for organizing traces
|
|
64
|
+
projectId: "proj_...",
|
|
65
|
+
|
|
66
|
+
// Optional: custom metadata attached to every trace
|
|
67
|
+
metadata: { environment: "production", service: "chatbot" },
|
|
68
|
+
|
|
69
|
+
// Optional: callback when a guardrail violation is detected
|
|
70
|
+
onViolation: (result) => {
|
|
71
|
+
console.warn("Guardrail violation:", result.violations);
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## What It Does
|
|
77
|
+
|
|
78
|
+
| Phase | Action |
|
|
79
|
+
|-------|--------|
|
|
80
|
+
| **Pre-request** | Sends the prompt to EvalGuard's firewall for prompt injection detection, PII scanning, and toxicity checks |
|
|
81
|
+
| **LLM call** | Passes through to the real OpenAI API unchanged |
|
|
82
|
+
| **Post-response** | Logs model, tokens, latency, cost, and guardrail results as a trace to EvalGuard |
|
|
83
|
+
|
|
84
|
+
## Fail-Open Design
|
|
85
|
+
|
|
86
|
+
If EvalGuard is unreachable (network error, timeout, 5xx), the wrapper passes requests through to OpenAI directly. Your application never breaks because of EvalGuard downtime.
|
|
87
|
+
|
|
88
|
+
## Error Handling
|
|
89
|
+
|
|
90
|
+
When `blockOnViolation` is `true` (default) and a guardrail check fails:
|
|
91
|
+
|
|
92
|
+
```typescript
|
|
93
|
+
import { EvalGuardViolationError } from "@evalguard/openai";
|
|
94
|
+
|
|
95
|
+
try {
|
|
96
|
+
const response = await openai.chat.completions.create({
|
|
97
|
+
model: "gpt-4o",
|
|
98
|
+
messages: [{ role: "user", content: "malicious prompt..." }],
|
|
99
|
+
});
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (error instanceof EvalGuardViolationError) {
|
|
102
|
+
console.log("Blocked:", error.violations);
|
|
103
|
+
// [{ type: "prompt_injection", severity: "critical", message: "..." }]
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Set `blockOnViolation: false` to log violations without blocking:
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
const openai = wrapOpenAI(new OpenAI(), {
|
|
112
|
+
apiKey: "eg_...",
|
|
113
|
+
blockOnViolation: false,
|
|
114
|
+
onViolation: (result) => {
|
|
115
|
+
// Log but don't block
|
|
116
|
+
analytics.track("guardrail_violation", result);
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT
|
package/dist/cost.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cost.d.ts","sourceRoot":"","sources":["../src/cost.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC"}
|
package/dist/cost.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Cost estimation is shared across all EvalGuard wrappers — re-exported
|
|
2
|
+
// from @evalguard/wrapper-core so the model pricing table has a single
|
|
3
|
+
// source of truth (and Gemini / future-provider pricing rolls in
|
|
4
|
+
// without touching this package).
|
|
5
|
+
export { estimateCost } from "@evalguard/wrapper-core";
|
|
6
|
+
//# sourceMappingURL=cost.js.map
|
package/dist/cost.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cost.js","sourceRoot":"","sources":["../src/cost.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,uEAAuE;AACvE,iEAAiE;AACjE,kCAAkC;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { GuardrailClient as CoreGuardrailClient } from "@evalguard/wrapper-core";
|
|
2
|
+
import type { EvalGuardConfig } from "@evalguard/wrapper-core";
|
|
3
|
+
export declare class GuardrailClient extends CoreGuardrailClient {
|
|
4
|
+
constructor(apiKey: string, baseUrl?: string);
|
|
5
|
+
constructor(config: EvalGuardConfig);
|
|
6
|
+
}
|
|
7
|
+
export type { GuardrailCheckResult, GuardrailViolation, TraceLogData, } from "@evalguard/wrapper-core";
|
|
8
|
+
//# sourceMappingURL=guardrail-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guardrail-client.d.ts","sourceRoot":"","sources":["../src/guardrail-client.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,eAAe,IAAI,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AACjF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE/D,qBAAa,eAAgB,SAAQ,mBAAmB;gBAC1C,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM;gBAChC,MAAM,EAAE,eAAe;CAQpC;AAGD,YAAY,EACV,oBAAoB,EACpB,kBAAkB,EAClB,YAAY,GACb,MAAM,yBAAyB,CAAC"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Thin back-compat subclass over @evalguard/wrapper-core's GuardrailClient.
|
|
2
|
+
//
|
|
3
|
+
// Preserves the v1.0.x public constructor signature:
|
|
4
|
+
// new GuardrailClient(apiKey: string, baseUrl?: string)
|
|
5
|
+
//
|
|
6
|
+
// so callers + the existing test suite that instantiate via this form
|
|
7
|
+
// keep working. New callers should prefer the wrapper-core form:
|
|
8
|
+
// new GuardrailClient({ apiKey, baseUrl, retry, idempotency, ... })
|
|
9
|
+
// which exposes BYOK, retry+circuit-breaker, idempotency, etc.
|
|
10
|
+
import { GuardrailClient as CoreGuardrailClient } from "@evalguard/wrapper-core";
|
|
11
|
+
export class GuardrailClient extends CoreGuardrailClient {
|
|
12
|
+
constructor(apiKeyOrConfig, baseUrl) {
|
|
13
|
+
if (typeof apiKeyOrConfig === "string") {
|
|
14
|
+
super({ apiKey: apiKeyOrConfig, baseUrl });
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
super(apiKeyOrConfig);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=guardrail-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guardrail-client.js","sourceRoot":"","sources":["../src/guardrail-client.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,EAAE;AACF,qDAAqD;AACrD,0DAA0D;AAC1D,EAAE;AACF,sEAAsE;AACtE,iEAAiE;AACjE,sEAAsE;AACtE,+DAA+D;AAE/D,OAAO,EAAE,eAAe,IAAI,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAGjF,MAAM,OAAO,eAAgB,SAAQ,mBAAmB;IAGtD,YAAY,cAAwC,EAAE,OAAgB;QACpE,IAAI,OAAO,cAAc,KAAK,QAAQ,EAAE,CAAC;YACvC,KAAK,CAAC,EAAE,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,CAAC,CAAC;QAC7C,CAAC;aAAM,CAAC;YACN,KAAK,CAAC,cAAc,CAAC,CAAC;QACxB,CAAC;IACH,CAAC;CACF"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type OpenAI from "openai";
|
|
2
|
+
import { type EvalGuardConfig } from "@evalguard/wrapper-core";
|
|
3
|
+
export { GuardrailClient } from "./guardrail-client.js";
|
|
4
|
+
export { EvalGuardViolationError, EvalGuardOutputViolationError, estimateCost, } from "@evalguard/wrapper-core";
|
|
5
|
+
export type { EvalGuardConfig, GuardrailCheckResult, GuardrailViolation, TraceLogData, OutputScoreResult, ByokKeyResolver, RetryConfig, CircuitConfig, EvalOnResponseConfig, } from "@evalguard/wrapper-core";
|
|
6
|
+
/**
|
|
7
|
+
* Wrap an existing OpenAI client to add EvalGuard guardrails, logging, and
|
|
8
|
+
* cost tracking. Returns a proxied client that is fully type-compatible with
|
|
9
|
+
* the original.
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* import OpenAI from "openai";
|
|
13
|
+
* import { wrapOpenAI } from "evalguardai-openai";
|
|
14
|
+
*
|
|
15
|
+
* const openai = wrapOpenAI(new OpenAI(), {
|
|
16
|
+
* apiKey: "eg_...",
|
|
17
|
+
* projectId: "proj_...",
|
|
18
|
+
* });
|
|
19
|
+
*
|
|
20
|
+
* // Use exactly like the normal OpenAI SDK
|
|
21
|
+
* const res = await openai.chat.completions.create({
|
|
22
|
+
* model: "gpt-4o",
|
|
23
|
+
* messages: [{ role: "user", content: "Hello" }],
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare function wrapOpenAI(client: OpenAI, config: EvalGuardConfig): OpenAI;
|
|
28
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AAEjC,OAAO,EAML,KAAK,eAAe,EAGrB,MAAM,yBAAyB,CAAC;AAWjC,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EACL,uBAAuB,EACvB,6BAA6B,EAC7B,YAAY,GACb,MAAM,yBAAyB,CAAC;AACjC,YAAY,EACV,eAAe,EACf,oBAAoB,EACpB,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,EACjB,eAAe,EACf,WAAW,EACX,aAAa,EACb,oBAAoB,GACrB,MAAM,yBAAyB,CAAC;AA4BjC;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,GAAG,MAAM,CA2B1E"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
// ── evalguardai-openai ───────────────────────────────────────────────────────
|
|
2
|
+
// Drop-in OpenAI SDK wrapper that auto-intercepts chat.completions.create()
|
|
3
|
+
// to enforce guardrails, log traces, and track costs via EvalGuard.
|
|
4
|
+
import { GuardrailClient } from "./guardrail-client.js";
|
|
5
|
+
import { estimateCost, newTraceId, injectTraceHeader, resolveIdempotencyKey, runPostResponseEval, } from "@evalguard/wrapper-core";
|
|
6
|
+
// ── Re-exports ──────────────────────────────────────────────────────────────
|
|
7
|
+
// Public surface of v1.1.0:
|
|
8
|
+
// - EvalGuardConfig now widens `apiKey` to `ByokKeyResolver` (was `string`)
|
|
9
|
+
// and adds opt-in fields: retry, circuit, idempotency, evalOnResponse,
|
|
10
|
+
// onOutputViolation. Existing string-apiKey callers are unaffected.
|
|
11
|
+
// - EvalGuardOutputViolationError is new (thrown by eval-on-response when
|
|
12
|
+
// output score falls below failOnScore).
|
|
13
|
+
// - estimateCost / GuardrailClient / newTraceId etc. are unchanged shape.
|
|
14
|
+
export { GuardrailClient } from "./guardrail-client.js";
|
|
15
|
+
export { EvalGuardViolationError, EvalGuardOutputViolationError, estimateCost, } from "@evalguard/wrapper-core";
|
|
16
|
+
import { EvalGuardViolationError } from "@evalguard/wrapper-core";
|
|
17
|
+
// ── Helper: extract text from messages ──────────────────────────────────────
|
|
18
|
+
function extractPromptText(messages) {
|
|
19
|
+
return messages
|
|
20
|
+
.map((m) => {
|
|
21
|
+
if (typeof m.content === "string")
|
|
22
|
+
return m.content;
|
|
23
|
+
if (Array.isArray(m.content)) {
|
|
24
|
+
return m.content
|
|
25
|
+
.map((part) => {
|
|
26
|
+
if (part.type === "text" && typeof part.text === "string")
|
|
27
|
+
return part.text;
|
|
28
|
+
return "";
|
|
29
|
+
})
|
|
30
|
+
.join(" ");
|
|
31
|
+
}
|
|
32
|
+
return "";
|
|
33
|
+
})
|
|
34
|
+
.join("\n");
|
|
35
|
+
}
|
|
36
|
+
// ── Main wrapper ────────────────────────────────────────────────────────────
|
|
37
|
+
/**
|
|
38
|
+
* Wrap an existing OpenAI client to add EvalGuard guardrails, logging, and
|
|
39
|
+
* cost tracking. Returns a proxied client that is fully type-compatible with
|
|
40
|
+
* the original.
|
|
41
|
+
*
|
|
42
|
+
* ```ts
|
|
43
|
+
* import OpenAI from "openai";
|
|
44
|
+
* import { wrapOpenAI } from "evalguardai-openai";
|
|
45
|
+
*
|
|
46
|
+
* const openai = wrapOpenAI(new OpenAI(), {
|
|
47
|
+
* apiKey: "eg_...",
|
|
48
|
+
* projectId: "proj_...",
|
|
49
|
+
* });
|
|
50
|
+
*
|
|
51
|
+
* // Use exactly like the normal OpenAI SDK
|
|
52
|
+
* const res = await openai.chat.completions.create({
|
|
53
|
+
* model: "gpt-4o",
|
|
54
|
+
* messages: [{ role: "user", content: "Hello" }],
|
|
55
|
+
* });
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
export function wrapOpenAI(client, config) {
|
|
59
|
+
// Pass the full config to the GuardrailClient — this picks up BYOK
|
|
60
|
+
// (apiKey as function), retry+circuit-breaker, idempotency, and
|
|
61
|
+
// eval-on-response wiring for free via wrapper-core.
|
|
62
|
+
const guardrail = new GuardrailClient(config);
|
|
63
|
+
const blockOnViolation = config.blockOnViolation ?? true;
|
|
64
|
+
const enableLogging = config.enableLogging ?? true;
|
|
65
|
+
// We need to intercept client.chat.completions.create(). The OpenAI SDK
|
|
66
|
+
// exposes this as a deeply nested property chain. We use a Proxy on the
|
|
67
|
+
// top-level client that intercepts property access to build a chain of
|
|
68
|
+
// proxies down to the `create` method.
|
|
69
|
+
return new Proxy(client, {
|
|
70
|
+
get(target, prop, receiver) {
|
|
71
|
+
if (prop === "chat") {
|
|
72
|
+
return createChatProxy(target.chat, guardrail, blockOnViolation, enableLogging, config);
|
|
73
|
+
}
|
|
74
|
+
return Reflect.get(target, prop, receiver);
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
function createChatProxy(chat, guardrail, blockOnViolation, enableLogging, config) {
|
|
79
|
+
return new Proxy(chat, {
|
|
80
|
+
get(target, prop, receiver) {
|
|
81
|
+
if (prop === "completions") {
|
|
82
|
+
return createCompletionsProxy(target.completions, guardrail, blockOnViolation, enableLogging, config);
|
|
83
|
+
}
|
|
84
|
+
return Reflect.get(target, prop, receiver);
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
function createCompletionsProxy(completions, guardrail, blockOnViolation, enableLogging, config) {
|
|
89
|
+
return new Proxy(completions, {
|
|
90
|
+
get(target, prop, receiver) {
|
|
91
|
+
if (prop === "create") {
|
|
92
|
+
return createInterceptedCreate(target.create.bind(target), guardrail, blockOnViolation, enableLogging, config);
|
|
93
|
+
}
|
|
94
|
+
// check.txt #17: the SDK also exposes chat.completions.stream() — a
|
|
95
|
+
// convenience helper distinct from create({stream:true}). Left
|
|
96
|
+
// un-intercepted, every .stream() caller skipped the input guardrail,
|
|
97
|
+
// output eval, and cost tracking. Intercept it the same way Anthropic
|
|
98
|
+
// does (and then some — see wrapChatCompletionStream).
|
|
99
|
+
if (prop === "stream") {
|
|
100
|
+
return createInterceptedStream(target, guardrail, blockOnViolation, enableLogging, config);
|
|
101
|
+
}
|
|
102
|
+
return Reflect.get(target, prop, receiver);
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
// ── Intercepted create() ────────────────────────────────────────────────────
|
|
107
|
+
function createInterceptedCreate(originalCreate, guardrail, blockOnViolation, enableLogging, config) {
|
|
108
|
+
// The OpenAI SDK's create() has multiple overloads. We return a function
|
|
109
|
+
// that handles both streaming and non-streaming transparently.
|
|
110
|
+
return async function interceptedCreate(...args) {
|
|
111
|
+
const body = args[0];
|
|
112
|
+
const messages = (body.messages ?? []);
|
|
113
|
+
const model = body.model ?? "unknown";
|
|
114
|
+
const isStreaming = Boolean(body.stream);
|
|
115
|
+
// D8 (2026-05-19): one trace id per intercepted call. Flows three
|
|
116
|
+
// places: (1) header on the EvalGuard firewall-check, (2) header
|
|
117
|
+
// + body on the EvalGuard trace-log, (3) `x-evalguard-trace-id`
|
|
118
|
+
// on the upstream OpenAI request via the SDK's RequestOptions
|
|
119
|
+
// second arg.
|
|
120
|
+
const traceId = newTraceId();
|
|
121
|
+
const upstreamArgs = injectTraceHeader(args, traceId);
|
|
122
|
+
// ── Pre-request guardrail check ─────────────────────────────────────
|
|
123
|
+
const promptText = extractPromptText(messages);
|
|
124
|
+
let guardrailResult;
|
|
125
|
+
try {
|
|
126
|
+
guardrailResult = await guardrail.checkInput(promptText, {
|
|
127
|
+
model,
|
|
128
|
+
provider: "openai",
|
|
129
|
+
projectId: config.projectId,
|
|
130
|
+
...config.metadata,
|
|
131
|
+
}, traceId);
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
// 2026-05-28: previously this catch silently set
|
|
135
|
+
// `{ allowed: true, violations: [] }` — meaning any guardrail
|
|
136
|
+
// outage (network blip, EvalGuard 5xx, DNS hiccup) became a
|
|
137
|
+
// free pass for the prompt. Per check.txt audit P1 finding.
|
|
138
|
+
//
|
|
139
|
+
// New contract: an unreachable guardrail is itself a
|
|
140
|
+
// "guardrail_unavailable" violation. Honor blockOnViolation —
|
|
141
|
+
// true (default) → throw; false → onViolation callback + allow.
|
|
142
|
+
const unavailable = {
|
|
143
|
+
allowed: false,
|
|
144
|
+
violations: [
|
|
145
|
+
{
|
|
146
|
+
type: "guardrail_unavailable",
|
|
147
|
+
severity: "high",
|
|
148
|
+
message: err instanceof Error ? err.message : "guardrail check failed",
|
|
149
|
+
},
|
|
150
|
+
],
|
|
151
|
+
};
|
|
152
|
+
config.onViolation?.(unavailable);
|
|
153
|
+
if (blockOnViolation) {
|
|
154
|
+
throw new EvalGuardViolationError(unavailable);
|
|
155
|
+
}
|
|
156
|
+
guardrailResult = { allowed: true, violations: [] };
|
|
157
|
+
}
|
|
158
|
+
if (!guardrailResult.allowed) {
|
|
159
|
+
config.onViolation?.(guardrailResult);
|
|
160
|
+
if (blockOnViolation) {
|
|
161
|
+
throw new EvalGuardViolationError(guardrailResult);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
// ── Execute LLM call ────────────────────────────────────────────────
|
|
165
|
+
const startTime = performance.now();
|
|
166
|
+
if (isStreaming) {
|
|
167
|
+
return handleStreamingResponse(originalCreate, upstreamArgs, model, messages, startTime, guardrail, enableLogging, config, guardrailResult, traceId);
|
|
168
|
+
}
|
|
169
|
+
return handleNonStreamingResponse(originalCreate, upstreamArgs, model, messages, startTime, guardrail, enableLogging, config, guardrailResult, traceId);
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
// ── Non-streaming handler ───────────────────────────────────────────────────
|
|
173
|
+
async function handleNonStreamingResponse(originalCreate, args, model, messages, startTime, guardrail, enableLogging, config, guardrailResult, traceId) {
|
|
174
|
+
const response = await originalCreate(...args);
|
|
175
|
+
const latencyMs = Math.round(performance.now() - startTime);
|
|
176
|
+
const usage = response.usage;
|
|
177
|
+
const inputTokens = usage?.prompt_tokens ?? 0;
|
|
178
|
+
const outputTokens = usage?.completion_tokens ?? 0;
|
|
179
|
+
const cost = estimateCost(model, inputTokens, outputTokens);
|
|
180
|
+
const outputContent = response.choices?.[0]
|
|
181
|
+
?.message ?? null;
|
|
182
|
+
const idempotencyKey = resolveIdempotencyKey(config);
|
|
183
|
+
// ── Eval-on-response (no-op unless config.evalOnResponse is set) ───────
|
|
184
|
+
// May throw EvalGuardOutputViolationError when failOnScore is breached
|
|
185
|
+
// and fireAndForget is NOT set.
|
|
186
|
+
const outputText = typeof outputContent === "object" && outputContent !== null
|
|
187
|
+
? String(outputContent.content ?? "")
|
|
188
|
+
: String(outputContent ?? "");
|
|
189
|
+
let outputScore = null;
|
|
190
|
+
try {
|
|
191
|
+
outputScore = await runPostResponseEval(guardrail, config, outputText, { model, provider: "openai", projectId: config.projectId, ...config.metadata }, traceId, idempotencyKey);
|
|
192
|
+
}
|
|
193
|
+
catch (err) {
|
|
194
|
+
// Re-throw EvalGuardOutputViolationError after logging the trace
|
|
195
|
+
// (caller still wants the trace row for the blocked output).
|
|
196
|
+
if (enableLogging) {
|
|
197
|
+
guardrail
|
|
198
|
+
.logTrace({
|
|
199
|
+
model,
|
|
200
|
+
provider: "openai",
|
|
201
|
+
input: messages,
|
|
202
|
+
output: outputContent,
|
|
203
|
+
latencyMs,
|
|
204
|
+
tokenUsage: { input: inputTokens, output: outputTokens },
|
|
205
|
+
cost,
|
|
206
|
+
projectId: config.projectId,
|
|
207
|
+
metadata: config.metadata,
|
|
208
|
+
guardrailResult,
|
|
209
|
+
outputScore: outputScore ?? undefined,
|
|
210
|
+
traceId,
|
|
211
|
+
idempotencyKey,
|
|
212
|
+
})
|
|
213
|
+
.catch(() => {
|
|
214
|
+
/* logging never throws */
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
throw err;
|
|
218
|
+
}
|
|
219
|
+
// Log trace in background (non-blocking) — happy path.
|
|
220
|
+
if (enableLogging) {
|
|
221
|
+
guardrail
|
|
222
|
+
.logTrace({
|
|
223
|
+
model,
|
|
224
|
+
provider: "openai",
|
|
225
|
+
input: messages,
|
|
226
|
+
output: outputContent,
|
|
227
|
+
latencyMs,
|
|
228
|
+
tokenUsage: { input: inputTokens, output: outputTokens },
|
|
229
|
+
cost,
|
|
230
|
+
projectId: config.projectId,
|
|
231
|
+
metadata: config.metadata,
|
|
232
|
+
guardrailResult,
|
|
233
|
+
outputScore: outputScore ?? undefined,
|
|
234
|
+
traceId,
|
|
235
|
+
idempotencyKey,
|
|
236
|
+
})
|
|
237
|
+
.catch(() => {
|
|
238
|
+
/* logging must never throw */
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
return response;
|
|
242
|
+
}
|
|
243
|
+
// ── Streaming handler ───────────────────────────────────────────────────────
|
|
244
|
+
async function handleStreamingResponse(originalCreate, args, model, messages, startTime, guardrail, enableLogging, config, guardrailResult, traceId) {
|
|
245
|
+
const stream = await originalCreate(...args);
|
|
246
|
+
if (!enableLogging) {
|
|
247
|
+
return stream;
|
|
248
|
+
}
|
|
249
|
+
// Wrap the async iterable to intercept chunks for logging while
|
|
250
|
+
// passing them through transparently to the caller.
|
|
251
|
+
return wrapAsyncIterable(stream, model, messages, startTime, guardrail, config, guardrailResult, traceId);
|
|
252
|
+
}
|
|
253
|
+
function finalizeOpenAIStream(state) {
|
|
254
|
+
const { assembledContent, inputTokens, outputTokens, model, messages, startTime, guardrail, config, guardrailResult, traceId, } = state;
|
|
255
|
+
const latencyMs = Math.round(performance.now() - startTime);
|
|
256
|
+
const cost = estimateCost(model, inputTokens, outputTokens);
|
|
257
|
+
const idempotencyKey = resolveIdempotencyKey(config);
|
|
258
|
+
runPostResponseEval(guardrail, config, assembledContent, { model, provider: "openai", projectId: config.projectId, ...config.metadata }, traceId, idempotencyKey)
|
|
259
|
+
.catch((err) => {
|
|
260
|
+
if (err && typeof err === "object" && err.score) {
|
|
261
|
+
const score = err.score;
|
|
262
|
+
try {
|
|
263
|
+
config.onOutputViolation?.(score);
|
|
264
|
+
}
|
|
265
|
+
catch {
|
|
266
|
+
/* user callback errors must not break the stream */
|
|
267
|
+
}
|
|
268
|
+
return score;
|
|
269
|
+
}
|
|
270
|
+
return null;
|
|
271
|
+
})
|
|
272
|
+
.then((outputScore) => {
|
|
273
|
+
guardrail
|
|
274
|
+
.logTrace({
|
|
275
|
+
model,
|
|
276
|
+
provider: "openai",
|
|
277
|
+
input: messages,
|
|
278
|
+
output: assembledContent,
|
|
279
|
+
latencyMs,
|
|
280
|
+
tokenUsage: { input: inputTokens, output: outputTokens },
|
|
281
|
+
cost,
|
|
282
|
+
projectId: config.projectId,
|
|
283
|
+
metadata: config.metadata,
|
|
284
|
+
guardrailResult,
|
|
285
|
+
outputScore: outputScore ?? undefined,
|
|
286
|
+
traceId,
|
|
287
|
+
idempotencyKey,
|
|
288
|
+
})
|
|
289
|
+
.catch(() => {
|
|
290
|
+
/* logging never throws */
|
|
291
|
+
});
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
function wrapAsyncIterable(stream, model, messages, startTime, guardrail, config, guardrailResult, traceId) {
|
|
295
|
+
let assembledContent = "";
|
|
296
|
+
let inputTokens = 0;
|
|
297
|
+
let outputTokens = 0;
|
|
298
|
+
const originalIterator = Symbol.asyncIterator in stream
|
|
299
|
+
? stream[Symbol.asyncIterator]()
|
|
300
|
+
: stream;
|
|
301
|
+
const wrappedIterator = {
|
|
302
|
+
async next() {
|
|
303
|
+
const result = await originalIterator.next();
|
|
304
|
+
if (result.done) {
|
|
305
|
+
// Stream complete -- finalize (eval-on-response + trace log) in the
|
|
306
|
+
// background. We never await inside `next()` — that would deadlock
|
|
307
|
+
// callers who hold the iterator.
|
|
308
|
+
finalizeOpenAIStream({
|
|
309
|
+
assembledContent,
|
|
310
|
+
inputTokens,
|
|
311
|
+
outputTokens,
|
|
312
|
+
model,
|
|
313
|
+
messages,
|
|
314
|
+
startTime,
|
|
315
|
+
guardrail,
|
|
316
|
+
config,
|
|
317
|
+
guardrailResult,
|
|
318
|
+
traceId,
|
|
319
|
+
});
|
|
320
|
+
return result;
|
|
321
|
+
}
|
|
322
|
+
// Accumulate content from chunk
|
|
323
|
+
const chunk = result.value;
|
|
324
|
+
const choices = chunk.choices;
|
|
325
|
+
if (choices?.[0]?.delta?.content) {
|
|
326
|
+
assembledContent += choices[0].delta.content;
|
|
327
|
+
}
|
|
328
|
+
// Capture usage if present (some models report on final chunk)
|
|
329
|
+
const usage = chunk.usage;
|
|
330
|
+
if (usage) {
|
|
331
|
+
inputTokens = usage.prompt_tokens ?? inputTokens;
|
|
332
|
+
outputTokens = usage.completion_tokens ?? outputTokens;
|
|
333
|
+
}
|
|
334
|
+
return result;
|
|
335
|
+
},
|
|
336
|
+
async return(value) {
|
|
337
|
+
if (originalIterator.return) {
|
|
338
|
+
return originalIterator.return(value);
|
|
339
|
+
}
|
|
340
|
+
return { done: true, value: undefined };
|
|
341
|
+
},
|
|
342
|
+
async throw(error) {
|
|
343
|
+
if (originalIterator.throw) {
|
|
344
|
+
return originalIterator.throw(error);
|
|
345
|
+
}
|
|
346
|
+
throw error;
|
|
347
|
+
},
|
|
348
|
+
[Symbol.asyncIterator]() {
|
|
349
|
+
return this;
|
|
350
|
+
},
|
|
351
|
+
};
|
|
352
|
+
// Preserve additional properties on the stream object (e.g., .controller,
|
|
353
|
+
// .response, .toReadableStream() from the OpenAI SDK).
|
|
354
|
+
return new Proxy(stream, {
|
|
355
|
+
get(_target, prop, receiver) {
|
|
356
|
+
if (prop === Symbol.asyncIterator) {
|
|
357
|
+
return () => wrappedIterator;
|
|
358
|
+
}
|
|
359
|
+
// Delegate everything else to the original stream
|
|
360
|
+
return Reflect.get(stream, prop, receiver);
|
|
361
|
+
},
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
// ── Intercepted stream() helper method (check.txt #17) ──────────────────────
|
|
365
|
+
/**
|
|
366
|
+
* Intercept `chat.completions.stream()` — the SDK's streaming convenience
|
|
367
|
+
* helper that returns a ChatCompletionStream (async-iterable AND event-emitter
|
|
368
|
+
* with .finalChatCompletion()/.finalContent()/.on('content')).
|
|
369
|
+
*
|
|
370
|
+
* Mirrors the Anthropic wrapper's stream() interception, then goes further:
|
|
371
|
+
* the OpenAI helper is very commonly consumed via `await stream.finalChatCompletion()`
|
|
372
|
+
* WITHOUT `for await`, so an iteration-only hook would leave cost + output-eval
|
|
373
|
+
* unmeasured for those callers (a half-fix). We hook BOTH consumption modes and
|
|
374
|
+
* use a one-shot `settled` latch so whichever resolves first finalizes exactly
|
|
375
|
+
* once. The pre-request input guardrail fires regardless of consumption mode.
|
|
376
|
+
*/
|
|
377
|
+
function createInterceptedStream(completions, guardrail, blockOnViolation, enableLogging, config) {
|
|
378
|
+
const originalStream = "stream" in completions &&
|
|
379
|
+
typeof completions.stream === "function"
|
|
380
|
+
? completions.stream.bind(completions)
|
|
381
|
+
: null;
|
|
382
|
+
// Older SDKs (or a fake without .stream) — fall through to the real value.
|
|
383
|
+
if (!originalStream) {
|
|
384
|
+
return completions.stream;
|
|
385
|
+
}
|
|
386
|
+
// NOTE: like every EvalGuard wrapper (anthropic/vercel/gemini), the wrapped
|
|
387
|
+
// .stream() resolves through a Promise so the async input guardrail runs
|
|
388
|
+
// BEFORE the upstream request — a blocked prompt never reaches the provider.
|
|
389
|
+
// Callers `await client.chat.completions.stream(...)`; the resolved value is
|
|
390
|
+
// the full ChatCompletionStream (async-iterable + .on/.finalChatCompletion/…).
|
|
391
|
+
return async function interceptedStream(...args) {
|
|
392
|
+
const body = (args[0] ?? {});
|
|
393
|
+
const messages = (body.messages ?? []);
|
|
394
|
+
const model = body.model ?? "unknown";
|
|
395
|
+
const traceId = newTraceId();
|
|
396
|
+
const upstreamArgs = injectTraceHeader(args, traceId);
|
|
397
|
+
// ── Pre-request guardrail check ─────────────────────────────────────
|
|
398
|
+
const promptText = extractPromptText(messages);
|
|
399
|
+
let guardrailResult;
|
|
400
|
+
try {
|
|
401
|
+
guardrailResult = await guardrail.checkInput(promptText, { model, provider: "openai", projectId: config.projectId, ...config.metadata }, traceId);
|
|
402
|
+
}
|
|
403
|
+
catch (err) {
|
|
404
|
+
// Unreachable guardrail is itself a high-severity violation
|
|
405
|
+
// (fail-closed by default) — symmetric with the create() path.
|
|
406
|
+
const unavailable = {
|
|
407
|
+
allowed: false,
|
|
408
|
+
violations: [
|
|
409
|
+
{
|
|
410
|
+
type: "guardrail_unavailable",
|
|
411
|
+
severity: "high",
|
|
412
|
+
message: err instanceof Error ? err.message : "guardrail check failed",
|
|
413
|
+
},
|
|
414
|
+
],
|
|
415
|
+
};
|
|
416
|
+
config.onViolation?.(unavailable);
|
|
417
|
+
if (blockOnViolation) {
|
|
418
|
+
throw new EvalGuardViolationError(unavailable);
|
|
419
|
+
}
|
|
420
|
+
guardrailResult = { allowed: true, violations: [] };
|
|
421
|
+
}
|
|
422
|
+
if (!guardrailResult.allowed) {
|
|
423
|
+
config.onViolation?.(guardrailResult);
|
|
424
|
+
if (blockOnViolation) {
|
|
425
|
+
throw new EvalGuardViolationError(guardrailResult);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
const startTime = performance.now();
|
|
429
|
+
const stream = originalStream(...upstreamArgs);
|
|
430
|
+
const resolved = stream instanceof Promise ? await stream : stream;
|
|
431
|
+
if (!enableLogging) {
|
|
432
|
+
return resolved;
|
|
433
|
+
}
|
|
434
|
+
return wrapChatCompletionStream(resolved, model, messages, startTime, guardrail, config, guardrailResult, traceId);
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Wrap a ChatCompletionStream so that cost + eval-on-response + trace logging
|
|
439
|
+
* fire exactly once, whether the caller drains it via `for await`, via
|
|
440
|
+
* `.finalChatCompletion()`, or via `.finalContent()`. All other methods/props
|
|
441
|
+
* (`.on`, `.controller`, `.toReadableStream`, `.totalUsage`, …) pass through.
|
|
442
|
+
*/
|
|
443
|
+
function wrapChatCompletionStream(stream, model, messages, startTime, guardrail, config, guardrailResult, traceId) {
|
|
444
|
+
let assembledContent = "";
|
|
445
|
+
let inputTokens = 0;
|
|
446
|
+
let outputTokens = 0;
|
|
447
|
+
let settled = false;
|
|
448
|
+
const finalizeOnce = (content, inTok, outTok) => {
|
|
449
|
+
if (settled)
|
|
450
|
+
return;
|
|
451
|
+
settled = true;
|
|
452
|
+
finalizeOpenAIStream({
|
|
453
|
+
assembledContent: content,
|
|
454
|
+
inputTokens: inTok,
|
|
455
|
+
outputTokens: outTok,
|
|
456
|
+
model,
|
|
457
|
+
messages,
|
|
458
|
+
startTime,
|
|
459
|
+
guardrail,
|
|
460
|
+
config,
|
|
461
|
+
guardrailResult,
|
|
462
|
+
traceId,
|
|
463
|
+
});
|
|
464
|
+
};
|
|
465
|
+
const originalIterator = Symbol.asyncIterator in stream
|
|
466
|
+
? stream[Symbol.asyncIterator]()
|
|
467
|
+
: stream;
|
|
468
|
+
const wrappedIterator = {
|
|
469
|
+
async next() {
|
|
470
|
+
const result = await originalIterator.next();
|
|
471
|
+
if (result.done) {
|
|
472
|
+
finalizeOnce(assembledContent, inputTokens, outputTokens);
|
|
473
|
+
return result;
|
|
474
|
+
}
|
|
475
|
+
const chunk = result.value;
|
|
476
|
+
const choices = chunk.choices;
|
|
477
|
+
if (choices?.[0]?.delta?.content) {
|
|
478
|
+
assembledContent += choices[0].delta.content;
|
|
479
|
+
}
|
|
480
|
+
const usage = chunk.usage;
|
|
481
|
+
if (usage) {
|
|
482
|
+
inputTokens = usage.prompt_tokens ?? inputTokens;
|
|
483
|
+
outputTokens = usage.completion_tokens ?? outputTokens;
|
|
484
|
+
}
|
|
485
|
+
return result;
|
|
486
|
+
},
|
|
487
|
+
async return(value) {
|
|
488
|
+
if (originalIterator.return) {
|
|
489
|
+
return originalIterator.return(value);
|
|
490
|
+
}
|
|
491
|
+
return { done: true, value: undefined };
|
|
492
|
+
},
|
|
493
|
+
async throw(error) {
|
|
494
|
+
if (originalIterator.throw) {
|
|
495
|
+
return originalIterator.throw(error);
|
|
496
|
+
}
|
|
497
|
+
throw error;
|
|
498
|
+
},
|
|
499
|
+
[Symbol.asyncIterator]() {
|
|
500
|
+
return this;
|
|
501
|
+
},
|
|
502
|
+
};
|
|
503
|
+
return new Proxy(stream, {
|
|
504
|
+
get(_target, prop, receiver) {
|
|
505
|
+
if (prop === Symbol.asyncIterator) {
|
|
506
|
+
return () => wrappedIterator;
|
|
507
|
+
}
|
|
508
|
+
// .finalChatCompletion() resolves to the assembled completion with usage
|
|
509
|
+
// — the cost-accurate finalize path for non-iterating consumers.
|
|
510
|
+
if (prop === "finalChatCompletion" && typeof stream.finalChatCompletion === "function") {
|
|
511
|
+
return async (...a) => {
|
|
512
|
+
const completion = (await stream.finalChatCompletion(...a));
|
|
513
|
+
const choice = completion.choices?.[0];
|
|
514
|
+
const text = String(choice?.message?.content ?? "");
|
|
515
|
+
const u = completion.usage;
|
|
516
|
+
finalizeOnce(text, u?.prompt_tokens ?? inputTokens, u?.completion_tokens ?? outputTokens);
|
|
517
|
+
return completion;
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
// .finalContent() returns just the text (no usage) — still finalize so
|
|
521
|
+
// output-eval + the trace fire; cost is best-effort from any chunks seen.
|
|
522
|
+
if (prop === "finalContent" && typeof stream.finalContent === "function") {
|
|
523
|
+
return async (...a) => {
|
|
524
|
+
const text = await stream.finalContent(...a);
|
|
525
|
+
finalizeOnce(String(text ?? ""), inputTokens, outputTokens);
|
|
526
|
+
return text;
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
return Reflect.get(stream, prop, receiver);
|
|
530
|
+
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I,YAAY,CAAC,CAAC;oBAC1F,OAAO,UAAU,CAAC;gBACpB,CAAC,CAAC;YACJ,CAAC;YACD,uEAAuE;YACvE,0EAA0E;YAC1E,IAAI,IAAI,KAAK,cAAc,IAAI,OAAO,MAAM,CAAC,YAAY,KAAK,UAAU,EAAE,CAAC;gBACzE,OAAO,KAAK,EAAE,GAAG,CAAY,EAAE,EAAE;oBAC/B,MAAM,IAAI,GAAG,MAAO,MAAM,CAAC,YAA4D,CAAC,GAAG,CAAC,CAAC,CAAC;oBAC9F,YAAY,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC,EAAE,WAAW,EAAE,YAAY,CAAC,CAAC;oBAC5D,OAAO,IAAI,CAAC;gBACd,CAAC,CAAC;YACJ,CAAC;YACD,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC7C,CAAC;KACF,CAA2C,CAAC;AAC/C,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@evalguard/openai",
|
|
3
|
+
"version": "1.1.1",
|
|
4
|
+
"description": "Drop-in OpenAI SDK wrapper with EvalGuard guardrails, logging & cost tracking",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"default": "./dist/index.js"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"dist",
|
|
14
|
+
"README.md",
|
|
15
|
+
"LICENSE"
|
|
16
|
+
],
|
|
17
|
+
"keywords": [
|
|
18
|
+
"openai",
|
|
19
|
+
"llm",
|
|
20
|
+
"guardrails",
|
|
21
|
+
"evalguard",
|
|
22
|
+
"ai-safety",
|
|
23
|
+
"prompt-injection",
|
|
24
|
+
"pii-detection",
|
|
25
|
+
"cost-tracking",
|
|
26
|
+
"observability"
|
|
27
|
+
],
|
|
28
|
+
"license": "Apache-2.0",
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=18"
|
|
31
|
+
},
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "https://github.com/EvalGuardAi/evalguard.git",
|
|
35
|
+
"directory": "packages/openai-wrapper"
|
|
36
|
+
},
|
|
37
|
+
"homepage": "https://evalguard.ai",
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/EvalGuardAi/evalguard/issues"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public",
|
|
43
|
+
"registry": "https://registry.npmjs.org/"
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"openai": ">=4.0.0"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@evalguard/wrapper-core": "1.0.1"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@typescript-eslint/eslint-plugin": "^8.59.3",
|
|
53
|
+
"@typescript-eslint/parser": "^8.59.3",
|
|
54
|
+
"eslint": "^10.4.0",
|
|
55
|
+
"openai": "^6.37.0",
|
|
56
|
+
"typescript": "^6.0.3",
|
|
57
|
+
"vitest": "^4.1.6",
|
|
58
|
+
"@evalguard/config": "0.0.1"
|
|
59
|
+
},
|
|
60
|
+
"type": "module",
|
|
61
|
+
"types": "./dist/index.d.ts",
|
|
62
|
+
"scripts": {
|
|
63
|
+
"build": "tsc",
|
|
64
|
+
"dev": "tsc --watch",
|
|
65
|
+
"type-check": "tsc --noEmit",
|
|
66
|
+
"test": "vitest run",
|
|
67
|
+
"lint": "eslint src --quiet",
|
|
68
|
+
"clean": "rm -rf dist .turbo"
|
|
69
|
+
}
|
|
70
|
+
}
|