promptlayer 1.0.61 → 1.2.0

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.
Files changed (54) hide show
  1. package/README.md +31 -0
  2. package/dist/claude-agents.d.mts +20 -0
  3. package/dist/claude-agents.d.ts +20 -0
  4. package/dist/claude-agents.js +2 -0
  5. package/dist/claude-agents.js.map +1 -0
  6. package/dist/esm/chunk-DFBRFJOL.js +2 -0
  7. package/dist/esm/chunk-DFBRFJOL.js.map +1 -0
  8. package/dist/esm/claude-agents.js +2 -0
  9. package/dist/esm/claude-agents.js.map +1 -0
  10. package/dist/esm/index.js +2 -2
  11. package/dist/esm/index.js.map +1 -1
  12. package/dist/esm/openai-agents.js +3 -0
  13. package/dist/esm/openai-agents.js.map +1 -0
  14. package/dist/index.js +2 -2
  15. package/dist/index.js.map +1 -1
  16. package/dist/openai-agents.d.mts +42 -0
  17. package/dist/openai-agents.d.ts +42 -0
  18. package/dist/openai-agents.js +3 -0
  19. package/dist/openai-agents.js.map +1 -0
  20. package/package.json +40 -2
  21. package/vendor/claude-agents/trace/.claude-plugin/plugin.json +8 -0
  22. package/vendor/claude-agents/trace/hooks/hook_utils.py +38 -0
  23. package/vendor/claude-agents/trace/hooks/hooks.json +60 -0
  24. package/vendor/claude-agents/trace/hooks/lib.sh +577 -0
  25. package/vendor/claude-agents/trace/hooks/parse_stop_transcript.py +375 -0
  26. package/vendor/claude-agents/trace/hooks/post_tool_use.sh +41 -0
  27. package/vendor/claude-agents/trace/hooks/session_end.sh +37 -0
  28. package/vendor/claude-agents/trace/hooks/session_start.sh +57 -0
  29. package/vendor/claude-agents/trace/hooks/stop_hook.sh +123 -0
  30. package/vendor/claude-agents/trace/hooks/user_prompt_submit.sh +25 -0
  31. package/vendor/claude-agents/vendor_metadata.json +5 -0
  32. package/.github/CODEOWNERS +0 -1
  33. package/.github/workflows/node.js.yml +0 -30
  34. package/.github/workflows/npm-publish.yml +0 -35
  35. package/src/groups.ts +0 -16
  36. package/src/index.ts +0 -383
  37. package/src/promptlayer.ts +0 -125
  38. package/src/run-error-tracking.test.ts +0 -146
  39. package/src/span-exporter.ts +0 -120
  40. package/src/span-wrapper.ts +0 -51
  41. package/src/templates.ts +0 -37
  42. package/src/tracing.ts +0 -20
  43. package/src/track.ts +0 -84
  44. package/src/types.ts +0 -689
  45. package/src/utils/blueprint-builder.test.ts +0 -727
  46. package/src/utils/blueprint-builder.ts +0 -1453
  47. package/src/utils/errors.test.ts +0 -68
  48. package/src/utils/errors.ts +0 -62
  49. package/src/utils/streaming.test.ts +0 -498
  50. package/src/utils/streaming.ts +0 -1402
  51. package/src/utils/utils.ts +0 -1228
  52. package/tsconfig.json +0 -115
  53. package/tsup.config.ts +0 -17
  54. package/vitest.config.ts +0 -6
@@ -1,30 +0,0 @@
1
- # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run lint across different versions of node
2
- # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs
3
-
4
- name: Node.js CI
5
-
6
- on:
7
- push:
8
- branches: ["master"]
9
- pull_request:
10
- branches: ["master"]
11
-
12
- jobs:
13
- build:
14
- runs-on: ubuntu-latest
15
-
16
- strategy:
17
- matrix:
18
- node-version: [18.x, 20.x, 22.x]
19
- # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
20
-
21
- steps:
22
- - uses: actions/checkout@v4
23
- - name: Use Node.js ${{ matrix.node-version }}
24
- uses: actions/setup-node@v3
25
- with:
26
- node-version: ${{ matrix.node-version }}
27
- cache: "npm"
28
- - run: npm ci
29
- - run: npm test
30
- - run: npm run lint && npm run build
@@ -1,35 +0,0 @@
1
- # This workflow will publish a package to NPM when a release is created
2
- # For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages
3
-
4
- name: Node.js Package
5
-
6
- on:
7
- release:
8
- types: [created]
9
-
10
- jobs:
11
- build:
12
- runs-on: ubuntu-latest
13
- steps:
14
- - uses: actions/checkout@v4
15
- - uses: actions/setup-node@v3
16
- with:
17
- node-version: 16
18
- cache: "npm"
19
- - run: npm ci
20
- - run: npm run lint && npm run build
21
-
22
- publish-npm:
23
- needs: build
24
- runs-on: ubuntu-latest
25
- steps:
26
- - uses: actions/checkout@v4
27
- - uses: actions/setup-node@v3
28
- with:
29
- node-version: 16
30
- registry-url: https://registry.npmjs.org/
31
- cache: "npm"
32
- - run: npm ci
33
- - run: npm run release
34
- env:
35
- NODE_AUTH_TOKEN: ${{secrets.npm_token}}
package/src/groups.ts DELETED
@@ -1,16 +0,0 @@
1
- import { promptLayerCreateGroup } from "@/utils/utils";
2
-
3
- export class GroupManager {
4
- apiKey: string;
5
- baseURL: string;
6
- throwOnError: boolean;
7
-
8
- constructor(apiKey: string, baseURL: string, throwOnError: boolean = true) {
9
- this.apiKey = apiKey;
10
- this.baseURL = baseURL;
11
- this.throwOnError = throwOnError;
12
- }
13
-
14
- create = () =>
15
- promptLayerCreateGroup(this.apiKey, this.baseURL, this.throwOnError);
16
- }
package/src/index.ts DELETED
@@ -1,383 +0,0 @@
1
- import { GroupManager } from "@/groups";
2
- import { promptLayerBase } from "@/promptlayer";
3
- import { wrapWithSpan } from "@/span-wrapper";
4
- import { TemplateManager } from "@/templates";
5
- import { getTracer, setupTracing } from "@/tracing";
6
- import { TrackManager } from "@/track";
7
- import {
8
- GetPromptTemplateParams,
9
- LogRequest,
10
- RunRequest,
11
- WorkflowRequest,
12
- WorkflowResponse,
13
- } from "@/types";
14
- import {
15
- amazonBedrockRequest,
16
- anthropicBedrockRequest,
17
- anthropicRequest,
18
- azureOpenAIRequest,
19
- configureProviderSettings,
20
- getProviderConfig,
21
- googleRequest,
22
- mistralRequest,
23
- openaiRequest,
24
- readEnv,
25
- runWorkflowRequest,
26
- trackRequest,
27
- utilLogRequest,
28
- vertexaiRequest,
29
- } from "@/utils/utils";
30
- import { categorizeError } from "@/utils/errors";
31
- import { streamResponse } from "@/utils/streaming";
32
- import * as opentelemetry from "@opentelemetry/api";
33
-
34
- const MAP_PROVIDER_TO_FUNCTION: Record<string, any> = {
35
- openai: openaiRequest,
36
- anthropic: anthropicRequest,
37
- "openai.azure": azureOpenAIRequest,
38
- google: googleRequest,
39
- vertexai: vertexaiRequest,
40
- "amazon.bedrock": amazonBedrockRequest,
41
- "anthropic.bedrock": anthropicBedrockRequest,
42
- mistral: mistralRequest,
43
- };
44
-
45
- export interface ClientOptions {
46
- apiKey?: string;
47
- enableTracing?: boolean;
48
- workspaceId?: number;
49
- throwOnError?: boolean;
50
- baseURL?: string;
51
- }
52
-
53
- const isWorkflowResultsDict = (obj: any): boolean => {
54
- if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
55
- return false;
56
- }
57
-
58
- const REQUIRED_KEYS = [
59
- "status",
60
- "value",
61
- "error_message",
62
- "raw_error_message",
63
- "is_output_node",
64
- ];
65
- const values = Object.values(obj);
66
-
67
- return values.every((val) => {
68
- if (typeof val !== "object" || val === null) return false;
69
- return REQUIRED_KEYS.every((key) => key in val);
70
- });
71
- };
72
-
73
- export class PromptLayer {
74
- apiKey: string;
75
- baseURL: string;
76
- templates: TemplateManager;
77
- group: GroupManager;
78
- track: TrackManager;
79
- enableTracing: boolean;
80
- throwOnError: boolean;
81
- wrapWithSpan: typeof wrapWithSpan;
82
-
83
- constructor({
84
- apiKey = readEnv("PROMPTLAYER_API_KEY"),
85
- baseURL = readEnv("PROMPTLAYER_BASE_URL"),
86
- enableTracing = false,
87
- throwOnError = true,
88
- }: ClientOptions = {}) {
89
- if (apiKey === undefined) {
90
- throw new Error(
91
- "PromptLayer API key not provided. Please set the PROMPTLAYER_API_KEY environment variable or pass the api_key parameter."
92
- );
93
- }
94
-
95
- this.apiKey = apiKey;
96
- this.baseURL = baseURL || "https://api.promptlayer.com";
97
- this.enableTracing = enableTracing;
98
- this.throwOnError = throwOnError;
99
- this.templates = new TemplateManager(
100
- apiKey,
101
- this.baseURL,
102
- this.throwOnError
103
- );
104
- this.group = new GroupManager(apiKey, this.baseURL, this.throwOnError);
105
- this.track = new TrackManager(apiKey, this.baseURL, this.throwOnError);
106
- this.wrapWithSpan = wrapWithSpan;
107
-
108
- if (enableTracing) {
109
- setupTracing(enableTracing, apiKey, this.baseURL);
110
- }
111
- }
112
-
113
- get Anthropic() {
114
- try {
115
- const module = require("@anthropic-ai/sdk").default;
116
- return promptLayerBase(
117
- this.apiKey,
118
- this.baseURL,
119
- module,
120
- "anthropic",
121
- "anthropic"
122
- );
123
- } catch (e) {
124
- console.error(
125
- "To use the Anthropic module, you must install the @anthropic-ai/sdk package."
126
- );
127
- }
128
- }
129
-
130
- get OpenAI() {
131
- try {
132
- const module = require("openai").default;
133
- return promptLayerBase(
134
- this.apiKey,
135
- this.baseURL,
136
- module,
137
- "openai",
138
- "openai"
139
- );
140
- } catch (e) {
141
- console.error(
142
- "To use the OpenAI module, you must install the @openai/api package."
143
- );
144
- }
145
- }
146
-
147
- async run({
148
- promptName,
149
- promptVersion,
150
- promptReleaseLabel,
151
- inputVariables,
152
- tags,
153
- metadata,
154
- groupId,
155
- modelParameterOverrides,
156
- stream = false,
157
- provider,
158
- model,
159
- }: RunRequest) {
160
- const tracer = getTracer();
161
-
162
- return tracer.startActiveSpan("PromptLayer Run", async (span) => {
163
- try {
164
- const functionInput = {
165
- promptName,
166
- promptVersion,
167
- promptReleaseLabel,
168
- inputVariables,
169
- tags,
170
- metadata,
171
- groupId,
172
- modelParameterOverrides,
173
- stream,
174
- };
175
- span.setAttribute("function_input", JSON.stringify(functionInput));
176
-
177
- const prompt_input_variables = inputVariables;
178
- const templateGetParams: GetPromptTemplateParams = {
179
- label: promptReleaseLabel,
180
- version: promptVersion,
181
- metadata_filters: metadata,
182
- provider,
183
- model,
184
- model_parameter_overrides: modelParameterOverrides,
185
- };
186
- if (inputVariables) templateGetParams.input_variables = inputVariables;
187
-
188
- const promptBlueprint = await this.templates.get(
189
- promptName,
190
- templateGetParams
191
- );
192
-
193
- if (!promptBlueprint) {
194
- throw new Error(
195
- `Cannot proceed: prompt template '${promptName}' could not be fetched. ` +
196
- `Check the warnings above for the actual error.`
197
- );
198
- }
199
-
200
- const promptTemplate = promptBlueprint.prompt_template;
201
- if (!promptBlueprint!.llm_kwargs) {
202
- const errorMessage = `Prompt '${promptName}' does not have any LLM kwargs associated with it. Please set your model parameters in the registry in the PromptLayer dashboard.`;
203
- if (this.throwOnError) {
204
- throw new Error(errorMessage);
205
- } else {
206
- console.warn(`WARNING: ${errorMessage}`);
207
- }
208
- }
209
-
210
- const promptBlueprintMetadata = promptBlueprint!.metadata;
211
- if (!promptBlueprintMetadata) {
212
- throw new Error(
213
- `Prompt '${promptName}' does not have any metadata associated with it.`
214
- );
215
- }
216
-
217
- const promptBlueprintModel = promptBlueprintMetadata.model;
218
- if (!promptBlueprintModel) {
219
- throw new Error(
220
- `Prompt '${promptName}' does not have a model parameters associated with it.`
221
- );
222
- }
223
-
224
- const customProvider = promptBlueprint!.custom_provider;
225
- const request_start_time = new Date().toISOString();
226
-
227
- const { provider_type, kwargs } = configureProviderSettings(
228
- promptBlueprint,
229
- customProvider,
230
- modelParameterOverrides,
231
- stream
232
- );
233
-
234
- let provider_type_config = provider_type;
235
- if (provider_type === "openai" || provider_type === "openai.azure") {
236
- const api_type = promptBlueprintModel.api_type;
237
- provider_type_config = `${provider_type}:${api_type}`;
238
- }
239
-
240
- if (promptBlueprintModel.name.startsWith("gemini")) {
241
- provider_type_config = "google";
242
- } else if (promptBlueprintModel.name.startsWith("claude")) {
243
- provider_type_config = "anthropic";
244
- }
245
-
246
- const config = getProviderConfig(provider_type_config, promptTemplate);
247
- const { function_name, stream_function } = config;
248
-
249
- const request_function = MAP_PROVIDER_TO_FUNCTION[provider_type];
250
- if (!request_function) {
251
- throw new Error(
252
- `No request function found for provider: ${provider_type}`
253
- );
254
- }
255
-
256
- const _trackRequest = (body: object) => {
257
- const request_end_time = new Date().toISOString();
258
- return trackRequest(
259
- this.baseURL,
260
- {
261
- function_name,
262
- provider_type,
263
- args: [],
264
- kwargs,
265
- tags,
266
- request_start_time,
267
- request_end_time,
268
- api_key: this.apiKey,
269
- metadata,
270
- prompt_id: promptBlueprint!.id,
271
- prompt_version: promptBlueprint!.version,
272
- prompt_input_variables,
273
- group_id: groupId,
274
- return_prompt_blueprint: true,
275
- span_id: span.spanContext().spanId,
276
- ...body,
277
- },
278
- this.throwOnError
279
- );
280
- };
281
-
282
- let response: any;
283
- try {
284
- response = await request_function(promptBlueprint!, kwargs);
285
- } catch (llmError: unknown) {
286
- const errorType = categorizeError(llmError);
287
- const errorMessage =
288
- llmError instanceof Error ? llmError.message : String(llmError);
289
- await _trackRequest({
290
- request_response: {},
291
- status: "ERROR",
292
- error_type: errorType,
293
- error_message: errorMessage,
294
- });
295
- throw llmError;
296
- }
297
-
298
- if (stream)
299
- return streamResponse(
300
- response,
301
- _trackRequest,
302
- stream_function,
303
- metadata || promptBlueprint!.metadata
304
- );
305
- const requestLog = await _trackRequest({ request_response: response });
306
-
307
- const functionOutput = {
308
- request_id: requestLog.request_id,
309
- raw_response: response,
310
- prompt_blueprint: requestLog.prompt_blueprint,
311
- };
312
- span.setAttribute("function_output", JSON.stringify(functionOutput));
313
-
314
- return functionOutput;
315
- } catch (error) {
316
- span.setStatus({
317
- code: opentelemetry.SpanStatusCode.ERROR,
318
- message: error instanceof Error ? error.message : "Unknown error",
319
- });
320
- throw error;
321
- } finally {
322
- span.end();
323
- }
324
- });
325
- }
326
-
327
- async runWorkflow({
328
- workflowName,
329
- inputVariables = {},
330
- metadata = {},
331
- workflowLabelName = null,
332
- workflowVersion = null, // This is the version number, not the version ID
333
- returnAllOutputs = false,
334
- }: WorkflowRequest): Promise<WorkflowResponse> {
335
- try {
336
- const result = await runWorkflowRequest({
337
- workflow_name: workflowName,
338
- input_variables: inputVariables,
339
- metadata,
340
- workflow_label_name: workflowLabelName,
341
- workflow_version_number: workflowVersion,
342
- return_all_outputs: returnAllOutputs,
343
- api_key: this.apiKey,
344
- baseURL: this.baseURL,
345
- });
346
-
347
- if (!returnAllOutputs) {
348
- if (isWorkflowResultsDict(result)) {
349
- const nodeValues = Object.values(result);
350
-
351
- const outputNodes = nodeValues.filter(
352
- (node: any) => node.is_output_node === true
353
- );
354
-
355
- if (outputNodes.length === 0) {
356
- throw new Error(JSON.stringify(result, null, 2));
357
- }
358
-
359
- const anyOutputSuccess = outputNodes.some(
360
- (node: any) => node.status === "SUCCESS"
361
- );
362
- if (!anyOutputSuccess) {
363
- throw new Error(JSON.stringify(result, null, 2));
364
- }
365
- }
366
- }
367
-
368
- return result;
369
- } catch (error) {
370
- if (error instanceof Error) {
371
- console.error("Error running workflow:", error.message);
372
- throw new Error(`Error running workflow: ${error.message}`);
373
- } else {
374
- console.error("Unknown error running workflow:", error);
375
- throw new Error("Unknown error running workflow");
376
- }
377
- }
378
- }
379
-
380
- async logRequest(body: LogRequest) {
381
- return utilLogRequest(this.apiKey, this.baseURL, body, this.throwOnError);
382
- }
383
- }
@@ -1,125 +0,0 @@
1
- import { getTracer } from "@/tracing";
2
- import { promptlayerApiHandler } from "@/utils/utils";
3
-
4
- const tracer = getTracer();
5
-
6
- export const promptLayerBase = (
7
- apiKey: string,
8
- baseURL: string,
9
- llm: object,
10
- function_name = "",
11
- provider = "openai"
12
- ) => {
13
- const handler: ProxyHandler<any> = {
14
- construct: (target, args) => {
15
- const newTarget = Reflect.construct(target, args);
16
- Object.defineProperties(newTarget, {
17
- function_name: {
18
- value: function_name,
19
- writable: true,
20
- },
21
- provider: {
22
- value: provider,
23
- },
24
- });
25
- return new Proxy(newTarget, handler);
26
- },
27
- get: (target, prop, receiver) => {
28
- const value = target[prop];
29
- const function_name = `${Reflect.get(
30
- target,
31
- "function_name"
32
- )}.${prop.toString()}`;
33
-
34
- if (typeof value === "object") {
35
- Object.defineProperties(value, {
36
- function_name: {
37
- value: function_name,
38
- writable: true,
39
- },
40
- provider: {
41
- value: provider,
42
- },
43
- });
44
- return new Proxy(value, handler);
45
- }
46
-
47
- if (typeof value === "function") {
48
- return (...args: any[]) => {
49
- const request_start_time = new Date().toISOString();
50
- const provider_type = Reflect.get(target, "provider");
51
- const return_pl_id = args[0]?.return_pl_id;
52
- const pl_tags = args[0]?.pl_tags;
53
- const pl_warn_on_error = args[0]?.pl_warn_on_error;
54
- delete args[0]?.return_pl_id;
55
- delete args[0]?.pl_tags;
56
- delete args[0]?.pl_warn_on_error;
57
-
58
- return tracer.startActiveSpan(
59
- `${provider_type}.${function_name}`,
60
- async (span: any) => {
61
- try {
62
- span.setAttribute("function_input", JSON.stringify(args));
63
- const response = Reflect.apply(value, target, args);
64
- const spanId = span.spanContext().spanId;
65
-
66
- if (response instanceof Promise) {
67
- return new Promise((resolve, reject) => {
68
- response
69
- .then(async (request_response) => {
70
- const response = await promptlayerApiHandler(
71
- apiKey,
72
- baseURL,
73
- {
74
- api_key: apiKey,
75
- provider_type,
76
- function_name,
77
- request_start_time,
78
- request_end_time: new Date().toISOString(),
79
- request_response,
80
- kwargs: args[0],
81
- return_pl_id,
82
- tags: pl_tags,
83
- span_id: spanId,
84
- },
85
- !pl_warn_on_error
86
- );
87
-
88
- span.setAttribute(
89
- "function_output",
90
- JSON.stringify(response)
91
- );
92
- span.setAttribute("response_status", "success");
93
- span.end();
94
- resolve(response);
95
- })
96
- .catch((error) => {
97
- span.recordException(error);
98
- span.setAttribute("response_status", "error");
99
- span.end();
100
- reject(error);
101
- });
102
- });
103
- }
104
-
105
- span.setAttribute("function_output", JSON.stringify(response));
106
- span.setAttribute("response_status", "success");
107
- span.end();
108
- return response;
109
- } catch (error) {
110
- span.recordException(error);
111
- span.setAttribute("response_status", "error");
112
- span.end();
113
- throw error;
114
- }
115
- }
116
- );
117
- };
118
- }
119
-
120
- return Reflect.get(target, prop, receiver);
121
- },
122
- };
123
-
124
- return new Proxy(llm, handler);
125
- };