promptlayer 1.0.39 → 1.0.41
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/dist/esm/index.js +2 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
- package/src/index.ts +8 -1
- package/src/utils/blueprint-builder.ts +198 -0
- package/src/utils/utils.ts +91 -14
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/utils.ts","../../src/groups.ts","../../src/tracing.ts","../../src/span-exporter.ts","../../src/promptlayer.ts","../../src/span-wrapper.ts","../../src/templates.ts","../../src/track.ts","../../src/index.ts"],"sourcesContent":["import {\n GetPromptTemplateParams,\n GetPromptTemplateResponse,\n ListPromptTemplatesResponse,\n LogRequest,\n Pagination,\n PublishPromptTemplate,\n PublishPromptTemplateResponse,\n RequestLog,\n RunWorkflowRequestParams,\n TrackGroup,\n TrackMetadata,\n TrackPrompt,\n TrackRequest,\n TrackScore,\n WorkflowResponse,\n} from \"@/types\";\nimport type TypeAnthropic from \"@anthropic-ai/sdk\";\nimport {\n Completion as AnthropicCompletion,\n Message,\n} from \"@anthropic-ai/sdk/resources\";\nimport { MessageStreamEvent } from \"@anthropic-ai/sdk/resources/messages\";\nimport type { AnthropicVertex } from \"@anthropic-ai/vertex-sdk\";\nimport Ably from \"ably\";\nimport type TypeOpenAI from \"openai\";\nimport {\n ChatCompletion,\n ChatCompletionChunk,\n Completion,\n} from \"openai/resources\";\n\nexport const SET_WORKFLOW_COMPLETE_MESSAGE = \"SET_WORKFLOW_COMPLETE\";\n\nexport enum FinalOutputCode {\n OK = \"OK\",\n EXCEEDS_SIZE_LIMIT = \"EXCEEDS_SIZE_LIMIT\",\n}\n\nasync function getFinalOutput(\n executionId: number,\n returnAllOutputs: boolean,\n headers: Record<string, string>\n): Promise<any> {\n const response = await fetch(\n `${URL_API_PROMPTLAYER}/workflow-version-execution-results?workflow_version_execution_id=${executionId}&return_all_outputs=${returnAllOutputs}`,\n { headers }\n );\n if (!response.ok) {\n throw new Error(\"Failed to fetch final output\");\n }\n return response.json();\n}\n\nfunction makeMessageListener(\n resultsPromise: { resolve: (data: any) => void; reject: (err: any) => void },\n executionId: number,\n returnAllOutputs: boolean,\n headers: Record<string, string>\n) {\n return async function (message: any) {\n if (message.name !== SET_WORKFLOW_COMPLETE_MESSAGE) return;\n\n try {\n const data = JSON.parse(message.data);\n const resultCode = data.result_code;\n let results;\n\n if (resultCode === FinalOutputCode.OK || resultCode == null) {\n results = data.final_output;\n } else if (resultCode === FinalOutputCode.EXCEEDS_SIZE_LIMIT) {\n results = await getFinalOutput(executionId, returnAllOutputs, headers);\n } else {\n throw new Error(`Unsupported final output code: ${resultCode}`);\n }\n\n resultsPromise.resolve(results);\n } catch (err) {\n resultsPromise.reject(err);\n }\n };\n}\n\nasync function waitForWorkflowCompletion({\n token,\n channelName,\n executionId,\n returnAllOutputs,\n headers,\n timeout,\n}: {\n token: string;\n channelName: string;\n executionId: number;\n returnAllOutputs: boolean;\n headers: Record<string, string>;\n timeout: number;\n}): Promise<any> {\n const client = new Ably.Realtime(token);\n const channel = client.channels.get(channelName);\n\n const resultsPromise = {} as {\n resolve: (value: any) => void;\n reject: (reason?: any) => void;\n };\n\n const promise = new Promise<any>((resolve, reject) => {\n resultsPromise.resolve = resolve;\n resultsPromise.reject = reject;\n });\n\n const listener = makeMessageListener(\n resultsPromise,\n executionId,\n returnAllOutputs,\n headers\n );\n await channel.subscribe(SET_WORKFLOW_COMPLETE_MESSAGE, listener);\n\n try {\n return await new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new Error(\"Workflow execution did not complete properly (timeout)\")\n );\n }, timeout);\n\n promise\n .then((result) => {\n clearTimeout(timer);\n resolve(result);\n })\n .catch((err) => {\n clearTimeout(timer);\n reject(err);\n });\n });\n } finally {\n console.log(\"Closing client\");\n channel.unsubscribe(SET_WORKFLOW_COMPLETE_MESSAGE, listener);\n client.close();\n console.log(\"Closed client\");\n }\n}\n\nexport const URL_API_PROMPTLAYER =\n process.env.PROMPTLAYER_API_URL || \"https://api.promptlayer.com\";\n\nconst promptlayerApiHandler = async <Item>(\n apiKey: string,\n body: TrackRequest & {\n request_response: AsyncIterable<Item> | any;\n }\n) => {\n const isGenerator = body.request_response[Symbol.asyncIterator] !== undefined;\n if (isGenerator) {\n return proxyGenerator(apiKey, body.request_response, body);\n }\n return await promptLayerApiRequest(apiKey, body);\n};\n\nconst promptLayerApiRequest = async (apiKey: string, body: TrackRequest) => {\n try {\n const response = await fetch(`${URL_API_PROMPTLAYER}/track-request`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While logging your request, PromptLayer experienced the following error:\"\n );\n }\n if (data && body.return_pl_id) {\n return [body.request_response, data.request_id];\n }\n } catch (e) {\n console.warn(\n `WARNING: While logging your request PromptLayer had the following error: ${e}`\n );\n }\n return body.request_response;\n};\n\nconst promptLayerTrackMetadata = async (\n apiKey: string,\n body: TrackMetadata\n): Promise<boolean> => {\n try {\n const response = await fetch(\n `${URL_API_PROMPTLAYER}/library-track-metadata`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n ...body,\n api_key: apiKey,\n }),\n }\n );\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While logging metadata to your request, PromptLayer experienced the following error\"\n );\n return false;\n }\n } catch (e) {\n console.warn(\n `WARNING: While logging metadata to your request, PromptLayer experienced the following error: ${e}`\n );\n return false;\n }\n return true;\n};\n\nconst promptLayerTrackScore = async (\n apiKey: string,\n body: TrackScore\n): Promise<boolean> => {\n try {\n const response = await fetch(`${URL_API_PROMPTLAYER}/library-track-score`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n ...body,\n api_key: apiKey,\n }),\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While scoring your request, PromptLayer experienced the following error\"\n );\n return false;\n }\n } catch (e) {\n console.warn(\n `WARNING: While scoring your request, PromptLayer experienced the following error: ${e}`\n );\n return false;\n }\n return true;\n};\n\nconst promptLayerTrackPrompt = async (\n apiKey: string,\n body: TrackPrompt\n): Promise<boolean> => {\n try {\n const response = await fetch(\n `${URL_API_PROMPTLAYER}/library-track-prompt`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n ...body,\n api_key: apiKey,\n }),\n }\n );\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While associating your request with a prompt template, PromptLayer experienced the following error\"\n );\n return false;\n }\n } catch (e) {\n console.warn(\n `WARNING: While associating your request with a prompt template, PromptLayer experienced the following error: ${e}`\n );\n return false;\n }\n return true;\n};\n\nconst promptLayerTrackGroup = async (\n apiKey: string,\n body: TrackGroup\n): Promise<boolean> => {\n try {\n const response = await fetch(`${URL_API_PROMPTLAYER}/track-group`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n ...body,\n api_key: apiKey,\n }),\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While associating your request with a group, PromptLayer experienced the following error\"\n );\n return false;\n }\n } catch (e) {\n console.warn(\n `WARNING: While associating your request with a group, PromptLayer experienced the following error: ${e}`\n );\n return false;\n }\n return true;\n};\n\nconst promptLayerCreateGroup = async (\n apiKey: string\n): Promise<number | boolean> => {\n try {\n const response = await fetch(`${URL_API_PROMPTLAYER}/create-group`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n api_key: apiKey,\n }),\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While creating a group PromptLayer had the following error\"\n );\n return false;\n }\n return data.id;\n } catch (e) {\n console.warn(\n `WARNING: While creating a group PromptLayer had the following error: ${e}`\n );\n return false;\n }\n};\n\nconst getPromptTemplate = async (\n apiKey: string,\n promptName: string,\n params?: Partial<GetPromptTemplateParams>\n) => {\n try {\n const url = new URL(\n `${URL_API_PROMPTLAYER}/prompt-templates/${promptName}`\n );\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-API-KEY\": apiKey,\n },\n body: JSON.stringify(params),\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While fetching a prompt template PromptLayer had the following error\"\n );\n return null;\n }\n if (data.warning) {\n console.warn(\n `WARNING: While fetching your prompt PromptLayer had the following error: ${data.warning}`\n );\n }\n return data as Promise<GetPromptTemplateResponse>;\n } catch (e) {\n console.warn(\n `WARNING: While fetching a prompt template PromptLayer had the following error: ${e}`\n );\n return null;\n }\n};\n\nconst publishPromptTemplate = async (\n apiKey: string,\n body: PublishPromptTemplate\n) => {\n try {\n const response = await fetch(\n `${URL_API_PROMPTLAYER}/rest/prompt-templates`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-API-KEY\": apiKey,\n },\n body: JSON.stringify({\n prompt_template: { ...body },\n prompt_version: { ...body },\n release_labels: body.release_labels ? body.release_labels : undefined,\n }),\n }\n );\n const data = await response.json();\n if (response.status === 400) {\n warnOnBadResponse(\n data,\n \"WARNING: While publishing a prompt template PromptLayer had the following error\"\n );\n }\n return data as Promise<PublishPromptTemplateResponse>;\n } catch (e) {\n console.warn(\n `WARNING: While publishing a prompt template PromptLayer had the following error: ${e}`\n );\n }\n};\n\nconst getAllPromptTemplates = async (\n apiKey: string,\n params?: Partial<Pagination>\n) => {\n try {\n const url = new URL(`${URL_API_PROMPTLAYER}/prompt-templates`);\n Object.entries(params || {}).forEach(([key, value]) =>\n url.searchParams.append(key, value.toString())\n );\n const response = await fetch(url, {\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-API-KEY\": apiKey,\n },\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While fetching all prompt templates PromptLayer had the following error\"\n );\n return null;\n }\n return (data.items ?? []) as Promise<Array<ListPromptTemplatesResponse>>;\n } catch (e) {\n console.warn(\n `WARNING: While fetching all prompt templates PromptLayer had the following error: ${e}`\n );\n return null;\n }\n};\n\nexport const runWorkflowRequest = async ({\n workflow_name,\n input_variables,\n metadata = {},\n workflow_label_name = null,\n workflow_version_number = null,\n return_all_outputs = false,\n api_key,\n timeout = 3600000, // Default timeout is 1 hour in milliseconds\n}: RunWorkflowRequestParams): Promise<WorkflowResponse> => {\n const payload = {\n input_variables,\n metadata,\n workflow_label_name,\n workflow_version_number,\n return_all_outputs,\n };\n\n const headers = {\n \"X-API-KEY\": api_key,\n \"Content-Type\": \"application/json\",\n };\n\n try {\n const response = await fetch(\n `${URL_API_PROMPTLAYER}/workflows/${encodeURIComponent(\n workflow_name\n )}/run`,\n {\n method: \"POST\",\n headers: headers,\n body: JSON.stringify(payload),\n }\n );\n\n if (response.status !== 201) {\n const errorData = await response.json().catch(() => ({}));\n return {\n success: false,\n message: `Failed to run workflow: ${\n errorData.error || response.statusText\n }`,\n };\n }\n\n const result = await response.json();\n if (result.warning) {\n console.warn(`WARNING: ${result.warning}`);\n }\n const execution_id = result.workflow_version_execution_id;\n if (!execution_id) {\n console.log(\"No execution ID returned from workflow run\");\n return { success: false, message: \"Failed to run workflow\" };\n }\n\n const channel_name = `workflow_updates:${execution_id}`;\n const ws_response = await fetch(\n `${URL_API_PROMPTLAYER}/ws-token-request-library?capability=${channel_name}`,\n {\n method: \"POST\",\n headers: headers,\n }\n );\n\n const ws_token_response = await ws_response.json();\n const ably_token = ws_token_response.token_details.token;\n return await waitForWorkflowCompletion({\n token: ably_token,\n channelName: channel_name,\n executionId: execution_id,\n returnAllOutputs: return_all_outputs,\n headers: headers,\n timeout: timeout,\n });\n } catch (error) {\n console.error(\n `Failed to run workflow: ${\n error instanceof Error ? error.message : error\n }`\n );\n throw error;\n }\n};\n\nconst openaiStreamChat = (results: ChatCompletionChunk[]): ChatCompletion => {\n let content: ChatCompletion.Choice[\"message\"][\"content\"] = null;\n let functionCall: ChatCompletion.Choice[\"message\"][\"function_call\"] =\n undefined;\n const response: ChatCompletion = {\n id: \"\",\n choices: [],\n created: Date.now(),\n model: \"\",\n object: \"chat.completion\",\n };\n const lastResult = results.at(-1);\n if (!lastResult) return response;\n let toolCalls: ChatCompletion.Choice[\"message\"][\"tool_calls\"] = undefined;\n for (const result of results) {\n if (result.choices.length === 0) continue;\n const delta = result.choices[0].delta;\n\n if (delta.content) {\n content = `${content || \"\"}${delta.content || \"\"}`;\n }\n if (delta.function_call) {\n functionCall = {\n name: `${functionCall ? functionCall.name : \"\"}${\n delta.function_call.name || \"\"\n }`,\n arguments: `${functionCall ? functionCall.arguments : \"\"}${\n delta.function_call.arguments || \"\"\n }`,\n };\n }\n const toolCall = delta.tool_calls?.[0];\n if (toolCall) {\n toolCalls = toolCalls || [];\n const lastToolCall = toolCalls.at(-1);\n if (!lastToolCall || toolCall.id) {\n toolCalls.push({\n id: toolCall.id || \"\",\n type: toolCall.type || \"function\",\n function: {\n name: toolCall.function?.name || \"\",\n arguments: toolCall.function?.arguments || \"\",\n },\n });\n continue;\n }\n lastToolCall.function.name = `${lastToolCall.function.name}${\n toolCall.function?.name || \"\"\n }`;\n lastToolCall.function.arguments = `${lastToolCall.function.arguments}${\n toolCall.function?.arguments || \"\"\n }`;\n }\n }\n const firstChoice = results[0].choices.at(0);\n response.choices.push({\n finish_reason: firstChoice?.finish_reason ?? \"stop\",\n index: firstChoice?.index ?? 0,\n logprobs: firstChoice?.logprobs ?? null,\n message: {\n role: \"assistant\",\n content,\n function_call: functionCall ? functionCall : undefined,\n tool_calls: toolCalls ? toolCalls : undefined,\n refusal: firstChoice?.delta.refusal ?? null,\n },\n });\n response.id = lastResult.id;\n response.model = lastResult.model;\n response.created = lastResult.created;\n response.system_fingerprint = lastResult.system_fingerprint;\n response.usage = lastResult.usage ?? undefined;\n return response;\n};\n\nconst anthropicStreamMessage = (results: MessageStreamEvent[]): Message => {\n let response: Message = {\n id: \"\",\n model: \"\",\n content: [],\n role: \"assistant\",\n type: \"message\",\n stop_reason: \"stop_sequence\",\n stop_sequence: null,\n usage: {\n input_tokens: 0,\n output_tokens: 0,\n cache_creation_input_tokens: 0,\n cache_read_input_tokens: 0,\n server_tool_use: null,\n service_tier: null,\n },\n };\n const lastResult = results.at(-1);\n if (!lastResult) return response;\n let currentBlock: any = null;\n let currentSignature = \"\";\n let currentThinking = \"\";\n let currentText = \"\";\n let currentToolInputJson = \"\";\n\n for (const event of results) {\n if (event.type === \"message_start\") {\n response = { ...event.message };\n } else if (event.type === \"content_block_start\") {\n currentBlock = { ...event.content_block };\n if (currentBlock.type === \"thinking\") {\n currentSignature = \"\";\n currentThinking = \"\";\n } else if (currentBlock.type === \"text\") {\n currentText = \"\";\n } else if (\n currentBlock.type === \"tool_use\" ||\n currentBlock.type === \"server_tool_use\"\n ) {\n currentToolInputJson = \"\";\n }\n } else if (event.type === \"content_block_delta\" && currentBlock !== null) {\n if (currentBlock.type === \"thinking\") {\n if (\"signature\" in event.delta) {\n currentSignature = event.delta.signature || \"\";\n }\n if (\"thinking\" in event.delta) {\n currentThinking += event.delta.thinking || \"\";\n }\n } else if (currentBlock.type === \"text\") {\n if (\"text\" in event.delta) {\n currentText += event.delta.text || \"\";\n }\n } else if (\n currentBlock.type === \"tool_use\" ||\n currentBlock.type === \"server_tool_use\"\n ) {\n if (event.delta.type === \"input_json_delta\") {\n const inputJsonDelta = event.delta as any;\n currentToolInputJson += inputJsonDelta.partial_json || \"\";\n }\n }\n } else if (event.type === \"content_block_stop\" && currentBlock !== null) {\n if (currentBlock.type === \"thinking\") {\n currentBlock.signature = currentSignature;\n currentBlock.thinking = currentThinking;\n } else if (currentBlock.type === \"text\") {\n currentBlock.text = currentText;\n currentBlock.citations = null;\n } else if (\n currentBlock.type === \"tool_use\" ||\n currentBlock.type === \"server_tool_use\"\n ) {\n try {\n currentBlock.input = currentToolInputJson\n ? JSON.parse(currentToolInputJson)\n : {};\n } catch (e) {\n currentBlock.input = {};\n }\n }\n response.content!.push(currentBlock);\n currentBlock = null;\n currentSignature = \"\";\n currentThinking = \"\";\n currentText = \"\";\n currentToolInputJson = \"\";\n } else if (event.type === \"message_delta\") {\n if (\"usage\" in event && event.usage) {\n response.usage = {\n ...response.usage,\n output_tokens: event.usage.output_tokens ?? 0,\n };\n }\n if (\"delta\" in event && event.delta) {\n if (\n \"stop_reason\" in event.delta &&\n event.delta.stop_reason !== undefined\n ) {\n response.stop_reason = event.delta.stop_reason;\n }\n if (\n \"stop_sequence\" in event.delta &&\n event.delta.stop_sequence !== undefined\n ) {\n response.stop_sequence = event.delta.stop_sequence;\n }\n }\n }\n }\n\n return response;\n};\n\nconst cleaned_result = (\n results: any[],\n function_name = \"openai.chat.completions.create\"\n) => {\n if (\"completion\" in results[0]) {\n return results.reduce(\n (prev, current) => ({\n ...current,\n completion: `${prev.completion}${current.completion}`,\n }),\n {}\n );\n }\n\n if (function_name === \"anthropic.messages.create\")\n return anthropicStreamMessage(results);\n\n if (\"text\" in results[0].choices[0]) {\n let response = \"\";\n for (const result of results) {\n response = `${response}${result.choices[0].text}`;\n }\n const final_result = structuredClone(results.at(-1));\n final_result.choices[0].text = response;\n return final_result;\n }\n\n if (\"delta\" in results[0].choices[0]) {\n const response = openaiStreamChat(results);\n response.choices[0] = {\n ...response.choices[0],\n ...response.choices[0].message,\n };\n return response;\n }\n\n return \"\";\n};\n\nasync function* proxyGenerator<Item>(\n apiKey: string,\n generator: AsyncIterable<Item>,\n body: TrackRequest\n) {\n const results = [];\n for await (const value of generator) {\n yield body.return_pl_id ? [value, null] : value;\n results.push(value);\n }\n const request_response = cleaned_result(results, body.function_name);\n const response = await promptLayerApiRequest(apiKey, {\n ...body,\n request_response,\n request_end_time: new Date().toISOString(),\n });\n if (response) {\n if (body.return_pl_id) {\n const request_id = (response as any)[1];\n const lastResult = results.at(-1);\n yield [lastResult, request_id];\n }\n }\n}\n\nconst warnOnBadResponse = (request_response: any, main_message: string) => {\n try {\n console.warn(`${main_message}: ${request_response.message}`);\n } catch (e) {\n console.warn(`${main_message}: ${request_response}`);\n }\n};\n\nconst trackRequest = async (body: TrackRequest) => {\n try {\n const response = await fetch(`${URL_API_PROMPTLAYER}/track-request`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While logging your request, PromptLayer experienced the following error:\"\n );\n }\n return data;\n } catch (e) {\n console.warn(\n `WARNING: While logging your request PromptLayer had the following error: ${e}`\n );\n }\n return {};\n};\n\nconst openaiStreamCompletion = (results: Completion[]) => {\n const response: Completion = {\n id: \"\",\n choices: [\n {\n finish_reason: \"stop\",\n index: 0,\n text: \"\",\n logprobs: null,\n },\n ],\n created: Date.now(),\n model: \"\",\n object: \"text_completion\",\n };\n const lastResult = results.at(-1);\n if (!lastResult) return response;\n let text = \"\";\n for (const result of results) {\n if (result.choices.length > 0 && result.choices[0].text) {\n text = `${text}${result.choices[0].text}`;\n }\n }\n response.choices[0].text = text;\n response.id = lastResult.id;\n response.created = lastResult.created;\n response.model = lastResult.model;\n response.system_fingerprint = lastResult.system_fingerprint;\n response.usage = lastResult.usage;\n return response;\n};\n\nconst anthropicStreamCompletion = (results: AnthropicCompletion[]) => {\n const response: AnthropicCompletion = {\n completion: \"\",\n id: \"\",\n model: \"\",\n stop_reason: \"\",\n type: \"completion\",\n };\n const lastResult = results.at(-1);\n if (!lastResult) return response;\n let completion = \"\";\n for (const result of results) {\n completion = `${completion}${result.completion}`;\n }\n response.completion = completion;\n response.id = lastResult.id;\n response.model = lastResult.model;\n response.stop_reason = lastResult.stop_reason;\n return response;\n};\n\nasync function* streamResponse<Item>(\n generator: AsyncIterable<Item>,\n afterStream: (body: object) => any,\n mapResults: any\n) {\n const data: {\n request_id: number | null;\n raw_response: any;\n prompt_blueprint: any;\n } = {\n request_id: null,\n raw_response: null,\n prompt_blueprint: null,\n };\n const results = [];\n for await (const result of generator) {\n results.push(result);\n data.raw_response = result;\n yield data;\n }\n const request_response = mapResults(results);\n const response = await afterStream({ request_response });\n data.request_id = response.request_id;\n data.prompt_blueprint = response.prompt_blueprint;\n yield data;\n}\n\nconst openaiChatRequest = async (client: TypeOpenAI, kwargs: any) => {\n return client.chat.completions.create(kwargs);\n};\n\nconst openaiCompletionsRequest = async (client: TypeOpenAI, kwargs: any) => {\n return client.completions.create(kwargs);\n};\n\nconst MAP_TYPE_TO_OPENAI_FUNCTION = {\n chat: openaiChatRequest,\n completion: openaiCompletionsRequest,\n};\n\nconst openaiRequest = async (\n promptBlueprint: GetPromptTemplateResponse,\n kwargs: any\n) => {\n const OpenAI = require(\"openai\").default;\n const client = new OpenAI({\n baseURL: kwargs.baseURL,\n apiKey: kwargs.apiKey,\n });\n const requestToMake =\n MAP_TYPE_TO_OPENAI_FUNCTION[promptBlueprint.prompt_template.type];\n return requestToMake(client, kwargs);\n};\n\nconst azureOpenAIRequest = async (\n promptBlueprint: GetPromptTemplateResponse,\n kwargs: any\n) => {\n const { AzureOpenAI } = require(\"openai\");\n const client = new AzureOpenAI({\n endpoint: process.env.AZURE_OPENAI_ENDPOINT || kwargs.baseURL,\n apiVersion: process.env.OPENAI_API_VERSION || kwargs.apiVersion,\n apiKey: process.env.AZURE_OPENAI_API_KEY || kwargs.apiKey,\n });\n delete kwargs?.baseURL;\n delete kwargs?.apiVersion;\n delete kwargs?.apiKey;\n const requestToMake =\n MAP_TYPE_TO_OPENAI_FUNCTION[promptBlueprint.prompt_template.type];\n return requestToMake(client, kwargs);\n};\n\nconst anthropicChatRequest = async (\n client: TypeAnthropic | AnthropicVertex,\n kwargs: any\n) => {\n return client.messages.create(kwargs);\n};\n\nconst anthropicCompletionsRequest = async (\n client: TypeAnthropic,\n kwargs: any\n) => {\n return client.completions.create(kwargs);\n};\n\nconst MAP_TYPE_TO_ANTHROPIC_FUNCTION = {\n chat: anthropicChatRequest,\n completion: anthropicCompletionsRequest,\n};\n\nconst anthropicRequest = async (\n promptBlueprint: GetPromptTemplateResponse,\n kwargs: any\n) => {\n const Anthropic = require(\"@anthropic-ai/sdk\").default;\n const client = new Anthropic({\n baseURL: kwargs.baseURL,\n });\n const requestToMake =\n MAP_TYPE_TO_ANTHROPIC_FUNCTION[promptBlueprint.prompt_template.type];\n return requestToMake(client, kwargs);\n};\n\nconst utilLogRequest = async (\n apiKey: string,\n body: LogRequest\n): Promise<RequestLog | null> => {\n try {\n const response = await fetch(`${URL_API_PROMPTLAYER}/log-request`, {\n method: \"POST\",\n headers: {\n \"X-API-KEY\": apiKey,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n const data = await response.json();\n if (response.status !== 201) {\n warnOnBadResponse(\n data,\n \"WARNING: While logging your request PromptLayer had the following error\"\n );\n return null;\n }\n return data;\n } catch (e) {\n console.warn(\n `WARNING: While tracking your prompt PromptLayer had the following error: ${e}`\n );\n return null;\n }\n};\n\nconst buildGoogleResponseFromParts = (\n thoughtContent: string,\n regularContent: string,\n functionCalls: any[],\n lastResult: any\n) => {\n const response = { ...lastResult };\n const finalParts = [];\n\n if (thoughtContent) {\n const thoughtPart = {\n text: thoughtContent,\n thought: true,\n };\n finalParts.push(thoughtPart);\n }\n\n if (regularContent) {\n const textPart = {\n text: regularContent,\n thought: null,\n };\n finalParts.push(textPart);\n }\n\n for (const functionCall of functionCalls) {\n const functionPart = {\n function_call: functionCall,\n };\n finalParts.push(functionPart);\n }\n\n if (finalParts.length > 0 && response.candidates?.[0]?.content) {\n response.candidates[0].content.parts = finalParts;\n }\n\n return response;\n};\n\nconst googleStreamResponse = (results: any[]) => {\n const { GenerateContentResponse } = require(\"@google/genai\");\n\n if (!results.length) {\n return new GenerateContentResponse();\n }\n\n let thoughtContent = \"\";\n let regularContent = \"\";\n const functionCalls: any[] = [];\n\n for (const result of results) {\n if (result.candidates && result.candidates[0]?.content?.parts) {\n for (const part of result.candidates[0].content.parts) {\n if (part.text) {\n if (part.thought === true) {\n thoughtContent += part.text;\n } else {\n regularContent += part.text;\n }\n } else if (part.functionCall) {\n functionCalls.push(part.functionCall);\n }\n }\n }\n }\n\n return buildGoogleResponseFromParts(\n thoughtContent,\n regularContent,\n functionCalls,\n results[results.length - 1]\n );\n};\n\nconst googleStreamChat = (results: any[]) => {\n return googleStreamResponse(results);\n};\n\nconst googleStreamCompletion = (results: any[]) => {\n return googleStreamResponse(results);\n};\n\nconst googleChatRequest = async (model_client: any, kwargs: any) => {\n const history = kwargs?.history;\n const generationConfig = kwargs?.generationConfig;\n const lastMessage =\n history.length > 0 ? history[history.length - 1]?.parts : \"\";\n const chat = model_client.chats.create({\n model: kwargs?.model,\n history: history.slice(0, -1) ?? [],\n config: generationConfig,\n });\n\n if (kwargs?.stream)\n return await chat.sendMessageStream({ message: lastMessage });\n return await chat.sendMessage({ message: lastMessage });\n};\n\nconst googleCompletionsRequest = async (\n model_client: any,\n { stream, ...kwargs }: any\n) => {\n if (stream) return await model_client.generateContentStream({ ...kwargs });\n return await model_client.generateContent({ ...kwargs });\n};\n\nconst MAP_TYPE_TO_GOOGLE_FUNCTION = {\n chat: googleChatRequest,\n completion: googleCompletionsRequest,\n};\n\nconst googleRequest = async (\n promptBlueprint: GetPromptTemplateResponse,\n kwargs: any\n) => {\n const { GoogleGenAI } = await import(\"@google/genai\");\n\n const geminiAPI = process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY;\n const project =\n process.env.VERTEX_AI_PROJECT_ID ||\n process.env.GOOGLE_PROJECT_ID ||\n process.env.GOOGLE_CLOUD_PROJECT;\n const location =\n process.env.VERTEX_AI_PROJECT_LOCATION ||\n process.env.GOOGLE_PROJECT_LOCATION ||\n process.env.GOOGLE_CLOUD_PROJECT_LOCATION;\n const googleAuthOptions = {\n keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS,\n projectId: project,\n scopes: [\"https://www.googleapis.com/auth/cloud-platform\"],\n };\n\n const genAI = geminiAPI\n ? new GoogleGenAI({ apiKey: geminiAPI })\n : new GoogleGenAI({\n vertexai: true,\n project: project,\n location: location,\n googleAuthOptions,\n });\n const requestToMake =\n MAP_TYPE_TO_GOOGLE_FUNCTION[promptBlueprint.prompt_template.type];\n\n const kwargsCamelCased = convertKeysToCamelCase(kwargs);\n if (kwargsCamelCased.generationConfig)\n kwargsCamelCased.generationConfig = convertKeysToCamelCase(\n kwargsCamelCased.generationConfig\n );\n\n return await requestToMake(genAI, kwargsCamelCased);\n};\n\nconst snakeToCamel = (str: string): string =>\n str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());\n\nconst convertKeysToCamelCase = <T>(obj: T): T => {\n if (!obj || typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) return obj.map(convertKeysToCamelCase) as T;\n\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [snakeToCamel(key), value])\n ) as T;\n};\n\nconst STREAMING_PROVIDERS_WITH_USAGE = [\"openai\", \"openai.azure\"] as const;\n\nconst MAP_PROVIDER_TO_FUNCTION_NAME = {\n openai: {\n chat: {\n function_name: \"openai.chat.completions.create\",\n stream_function: openaiStreamChat,\n },\n completion: {\n function_name: \"openai.completions.create\",\n stream_function: openaiStreamCompletion,\n },\n },\n anthropic: {\n chat: {\n function_name: \"anthropic.messages.create\",\n stream_function: anthropicStreamMessage,\n },\n completion: {\n function_name: \"anthropic.completions.create\",\n stream_function: anthropicStreamCompletion,\n },\n },\n \"openai.azure\": {\n chat: {\n function_name: \"openai.AzureOpenAI.chat.completions.create\",\n stream_function: openaiStreamChat,\n },\n completion: {\n function_name: \"openai.AzureOpenAI.completions.create\",\n stream_function: openaiStreamCompletion,\n },\n },\n google: {\n chat: {\n function_name: \"google.convo.send_message\",\n stream_function: googleStreamChat,\n },\n completion: {\n function_name: \"google.model.generate_content\",\n stream_function: googleStreamCompletion,\n },\n },\n};\n\nconst configureProviderSettings = (\n promptBlueprint: any,\n customProvider: any,\n modelParameterOverrides: any = {},\n stream: boolean = false\n) => {\n const provider_type =\n customProvider?.client ?? promptBlueprint.metadata?.model?.provider;\n\n if (!provider_type) {\n throw new Error(\n \"Provider type not found in prompt blueprint or custom provider\"\n );\n }\n\n const kwargs = {\n ...(promptBlueprint.llm_kwargs || {}),\n ...modelParameterOverrides,\n stream,\n };\n\n const providerConfig = {\n baseURL: customProvider?.base_url ?? promptBlueprint.provider_base_url?.url,\n apiKey: customProvider?.api_key,\n };\n\n Object.entries(providerConfig).forEach(([key, value]) => {\n if (value !== undefined) {\n kwargs[key] = value;\n }\n });\n\n if (stream && STREAMING_PROVIDERS_WITH_USAGE.includes(provider_type as any)) {\n kwargs.stream_options = { include_usage: true };\n }\n\n return { provider_type, kwargs };\n};\n\nconst getProviderConfig = (provider_type: string, promptTemplate: any) => {\n const providerMap =\n MAP_PROVIDER_TO_FUNCTION_NAME[\n provider_type as keyof typeof MAP_PROVIDER_TO_FUNCTION_NAME\n ];\n\n if (!providerMap) {\n throw new Error(`Unsupported provider type: ${provider_type}`);\n }\n\n const templateType = promptTemplate.type as keyof typeof providerMap;\n const config = providerMap[templateType];\n\n if (!config) {\n throw new Error(\n `Unsupported template type '${promptTemplate.type}' for provider '${provider_type}'`\n );\n }\n\n return config;\n};\n\nconst vertexaiRequest = async (\n promptBlueprint: GetPromptTemplateResponse,\n kwargs: any\n) => {\n const model = promptBlueprint.metadata?.model;\n if (!model) throw new Error(\"Model metadata not found in prompt blueprint\");\n if (model.name.startsWith(\"gemini\"))\n return googleRequest(promptBlueprint, kwargs);\n if (model.name.startsWith(\"claude\")) {\n const { AnthropicVertex } = await import(\"@anthropic-ai/vertex-sdk\");\n const client = new AnthropicVertex({ baseURL: kwargs.baseURL });\n if (promptBlueprint.prompt_template.type === \"chat\")\n return anthropicChatRequest(client, kwargs);\n throw new Error(\n `Unsupported prompt template type '${promptBlueprint.prompt_template.type}' for Anthropic Vertex AI`\n );\n }\n throw new Error(\n `Unsupported model name '${model.name}' for Vertex AI request`\n );\n};\nexport {\n anthropicRequest,\n anthropicStreamCompletion,\n anthropicStreamMessage,\n azureOpenAIRequest,\n configureProviderSettings,\n getAllPromptTemplates,\n getPromptTemplate,\n getProviderConfig,\n googleRequest,\n googleStreamChat,\n googleStreamCompletion,\n openaiRequest,\n openaiStreamChat,\n openaiStreamCompletion,\n promptlayerApiHandler,\n promptLayerApiRequest,\n promptLayerCreateGroup,\n promptLayerTrackGroup,\n promptLayerTrackMetadata,\n promptLayerTrackPrompt,\n promptLayerTrackScore,\n publishPromptTemplate,\n streamResponse,\n trackRequest,\n utilLogRequest,\n vertexaiRequest,\n};\n","import { promptLayerCreateGroup } from \"@/utils/utils\";\n\nexport class GroupManager {\n apiKey: string;\n\n constructor(apiKey: string) {\n this.apiKey = apiKey;\n }\n\n create = () => promptLayerCreateGroup(this.apiKey);\n}\n","import * as opentelemetry from '@opentelemetry/api';\nimport {SimpleSpanProcessor} from '@opentelemetry/sdk-trace-base';\nimport {NodeTracerProvider} from '@opentelemetry/sdk-trace-node';\nimport PromptLayerSpanExporter from '@/span-exporter';\n\nexport const getTracer = (name: string = 'promptlayer-tracer') => {\n return opentelemetry.trace.getTracer(name);\n}\n\nexport const setupTracing = (enableTracing: boolean, apiKey?: string) => {\n const provider = new NodeTracerProvider();\n const exporter = new PromptLayerSpanExporter(enableTracing, apiKey);\n const processor = new SimpleSpanProcessor(exporter);\n provider.addSpanProcessor(processor);\n provider.register();\n}\n","import { Attributes, SpanKind, SpanStatusCode } from \"@opentelemetry/api\";\nimport { ReadableSpan, SpanExporter } from \"@opentelemetry/sdk-trace-base\";\nimport { ExportResultCode } from \"@opentelemetry/core\";\nimport { URL_API_PROMPTLAYER } from \"@/utils/utils\";\n\nclass PromptLayerSpanExporter implements SpanExporter {\n private apiKey: string | undefined;\n private enableTracing: boolean;\n private url: string;\n\n constructor(enableTracing: boolean, apiKey?: string) {\n this.apiKey = apiKey || process.env.PROMPTLAYER_API_KEY;\n this.enableTracing = enableTracing;\n this.url = `${URL_API_PROMPTLAYER}/spans-bulk`;\n }\n\n private attributesToObject(\n attributes: Attributes | undefined\n ): Record<string, any> {\n if (!attributes) return {};\n return Object.fromEntries(Object.entries(attributes));\n }\n\n private spanKindToString(kind: SpanKind): string {\n const kindMap: Record<SpanKind, string> = {\n [SpanKind.INTERNAL]: \"SpanKind.INTERNAL\",\n [SpanKind.SERVER]: \"SpanKind.SERVER\",\n [SpanKind.CLIENT]: \"SpanKind.CLIENT\",\n [SpanKind.PRODUCER]: \"SpanKind.PRODUCER\",\n [SpanKind.CONSUMER]: \"SpanKind.CONSUMER\",\n };\n return kindMap[kind] || \"SpanKind.INTERNAL\";\n }\n\n private statusCodeToString(code: SpanStatusCode): string {\n const statusMap: Record<SpanStatusCode, string> = {\n [SpanStatusCode.ERROR]: \"StatusCode.ERROR\",\n [SpanStatusCode.OK]: \"StatusCode.OK\",\n [SpanStatusCode.UNSET]: \"StatusCode.UNSET\",\n };\n return statusMap[code] || \"StatusCode.UNSET\";\n }\n\n private toNanoseconds(time: [number, number]): string {\n return (BigInt(time[0]) * BigInt(1e9) + BigInt(time[1])).toString();\n }\n\n export(spans: ReadableSpan[]): Promise<ExportResultCode> {\n if (!this.enableTracing) {\n return Promise.resolve(ExportResultCode.SUCCESS);\n }\n\n const requestData = spans.map((span) => ({\n name: span.name,\n context: {\n trace_id: span.spanContext().traceId,\n span_id: span.spanContext().spanId,\n trace_state: span.spanContext().traceState?.serialize() || \"\",\n },\n kind: this.spanKindToString(span.kind),\n parent_id: span.parentSpanId || null,\n start_time: this.toNanoseconds(span.startTime),\n end_time: this.toNanoseconds(span.endTime),\n status: {\n status_code: this.statusCodeToString(span.status.code),\n description: span.status.message,\n },\n attributes: this.attributesToObject(span.attributes),\n events: span.events.map((event) => ({\n name: event.name,\n timestamp: this.toNanoseconds(event.time),\n attributes: this.attributesToObject(event.attributes),\n })),\n links: span.links.map((link) => ({\n context: link.context,\n attributes: this.attributesToObject(link.attributes),\n })),\n resource: {\n attributes: {\n ...span.resource.attributes,\n \"service.name\": \"prompt-layer-js\",\n },\n schema_url: \"\",\n },\n }));\n\n return fetch(this.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-API-KEY\": this.apiKey || \"\",\n },\n body: JSON.stringify({\n spans: requestData,\n }),\n })\n .then((response) => {\n if (!response.ok) {\n console.error(\n `Error exporting spans\\nHTTP error! status: ${response.status}`\n );\n return ExportResultCode.FAILED;\n }\n return ExportResultCode.SUCCESS;\n })\n .catch((error) => {\n console.error(\"Error exporting spans:\", error);\n return ExportResultCode.FAILED;\n });\n }\n\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nexport default PromptLayerSpanExporter;\n","import { getTracer } from \"@/tracing\";\nimport { promptlayerApiHandler } from \"@/utils/utils\";\n\nconst tracer = getTracer();\n\nexport const promptLayerBase = (\n apiKey: string,\n llm: object,\n function_name = \"\",\n provider = \"openai\"\n) => {\n const handler: ProxyHandler<any> = {\n construct: (target, args) => {\n const newTarget = Reflect.construct(target, args);\n Object.defineProperties(newTarget, {\n function_name: {\n value: function_name,\n writable: true,\n },\n provider: {\n value: provider,\n },\n });\n return new Proxy(newTarget, handler);\n },\n get: (target, prop, receiver) => {\n const value = target[prop];\n const function_name = `${Reflect.get(\n target,\n \"function_name\"\n )}.${prop.toString()}`;\n\n if (typeof value === \"object\") {\n Object.defineProperties(value, {\n function_name: {\n value: function_name,\n writable: true,\n },\n provider: {\n value: provider,\n },\n });\n return new Proxy(value, handler);\n }\n\n if (typeof value === \"function\") {\n return (...args: any[]) => {\n const request_start_time = new Date().toISOString();\n const provider_type = Reflect.get(target, \"provider\");\n const return_pl_id = args[0]?.return_pl_id;\n const pl_tags = args[0]?.pl_tags;\n delete args[0]?.return_pl_id;\n delete args[0]?.pl_tags;\n\n return tracer.startActiveSpan(\n `${provider_type}.${function_name}`,\n async (span: any) => {\n try {\n span.setAttribute(\"function_input\", JSON.stringify(args));\n const response = Reflect.apply(value, target, args);\n const spanId = span.spanContext().spanId;\n\n if (response instanceof Promise) {\n return new Promise((resolve, reject) => {\n response\n .then(async (request_response) => {\n const response = await promptlayerApiHandler(apiKey, {\n api_key: apiKey,\n provider_type,\n function_name,\n request_start_time,\n request_end_time: new Date().toISOString(),\n request_response,\n kwargs: args[0],\n return_pl_id,\n tags: pl_tags,\n span_id: spanId,\n });\n\n span.setAttribute(\n \"function_output\",\n JSON.stringify(response)\n );\n span.setAttribute(\"response_status\", \"success\");\n span.end();\n resolve(response);\n })\n .catch((error) => {\n span.recordException(error);\n span.setAttribute(\"response_status\", \"error\");\n span.end();\n reject(error);\n });\n });\n }\n\n span.setAttribute(\"function_output\", JSON.stringify(response));\n span.setAttribute(\"response_status\", \"success\");\n span.end();\n return response;\n } catch (error) {\n span.recordException(error);\n span.setAttribute(\"response_status\", \"error\");\n span.end();\n throw error;\n }\n }\n );\n };\n }\n\n return Reflect.get(target, prop, receiver);\n },\n };\n\n return new Proxy(llm, handler);\n};\n","import * as opentelemetry from '@opentelemetry/api';\nimport { getTracer } from '@/tracing';\n\nexport const wrapWithSpan = (functionName: string, func: Function, attributes?: Record<string, any>) => {\n return function (...args: any[]) {\n const tracer = getTracer();\n\n const wrapperFunction = (span: opentelemetry.Span) => {\n try {\n if (attributes) {\n Object.entries(attributes).forEach(([key, value]) => {\n span.setAttribute(key, value);\n });\n }\n\n span.setAttribute('function_input', JSON.stringify(args));\n const result = func(...args);\n\n if (result instanceof Promise) {\n return result.then((resolvedResult) => {\n span.setAttribute('function_output', JSON.stringify(resolvedResult));\n span.setStatus({ code: opentelemetry.SpanStatusCode.OK });\n return resolvedResult;\n }).catch((error) => {\n handleError(span, error, args);\n throw error;\n }).finally(() => span.end());\n } else {\n span.setAttribute('function_output', JSON.stringify(result));\n span.setStatus({ code: opentelemetry.SpanStatusCode.OK });\n span.end();\n return result;\n }\n } catch (error) {\n handleError(span, error, args);\n throw error;\n }\n };\n\n return tracer.startActiveSpan(functionName, wrapperFunction);\n };\n};\n\nconst handleError = (span: opentelemetry.Span, error: any, args: any[]) => {\n span.setAttribute('function_input', JSON.stringify(args));\n span.setStatus({\n code: opentelemetry.SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n span.end();\n}\n","import {\n GetPromptTemplateParams,\n Pagination,\n PublishPromptTemplate,\n} from \"@/types\";\nimport {\n getAllPromptTemplates,\n getPromptTemplate,\n publishPromptTemplate,\n} from \"@/utils/utils\";\n\nexport class TemplateManager {\n apiKey: string;\n\n constructor(apiKey: string) {\n this.apiKey = apiKey;\n }\n\n get = (promptName: string, params?: Partial<GetPromptTemplateParams>) =>\n getPromptTemplate(this.apiKey, promptName, params);\n\n publish = (body: PublishPromptTemplate) =>\n publishPromptTemplate(this.apiKey, body);\n\n all = (params?: Pagination) => getAllPromptTemplates(this.apiKey, params);\n}\n","import { TrackGroup, TrackMetadata, TrackPrompt, TrackScore } from \"@/types\";\nimport {\n promptLayerTrackGroup,\n promptLayerTrackMetadata,\n promptLayerTrackPrompt,\n promptLayerTrackScore,\n} from \"@/utils/utils\";\n\nconst metadata = (apiKey: string, body: TrackMetadata): Promise<boolean> => {\n if (!(body.metadata instanceof Object)) {\n throw new Error(\"Please provide a dictionary of metadata.\");\n }\n for (const [key, value] of Object.entries(body.metadata)) {\n if (typeof key !== \"string\" || typeof value !== \"string\") {\n throw new Error(\n \"Please provide a dictionary of metadata with key value pair of strings.\"\n );\n }\n }\n return promptLayerTrackMetadata(apiKey, body);\n};\n\nconst score = (apiKey: string, body: TrackScore): Promise<boolean> => {\n if (typeof body.score !== \"number\") {\n throw new Error(\"Score must be a number\");\n }\n if (body.score < 0 || body.score > 100) {\n throw new Error(\"Score must be a number between 0 and 100.\");\n }\n return promptLayerTrackScore(apiKey, body);\n};\n\nconst prompt = (apiKey: string, body: TrackPrompt): Promise<boolean> => {\n if (!(body.prompt_input_variables instanceof Object)) {\n throw new Error(\"Prompt template input variable dictionary not provided.\");\n }\n return promptLayerTrackPrompt(apiKey, body);\n};\n\nconst group = (apiKey: string, body: TrackGroup) =>\n promptLayerTrackGroup(apiKey, body);\n\nexport class TrackManager {\n apiKey: string;\n\n constructor(apiKey: string) {\n this.apiKey = apiKey;\n }\n\n group = (body: TrackGroup) => group(this.apiKey, body);\n\n metadata = (body: TrackMetadata) => metadata(this.apiKey, body);\n\n prompt = (body: TrackPrompt) => prompt(this.apiKey, body);\n\n score = (body: TrackScore) => score(this.apiKey, body);\n}\n","import { GroupManager } from \"@/groups\";\nimport { promptLayerBase } from \"@/promptlayer\";\nimport { wrapWithSpan } from \"@/span-wrapper\";\nimport { TemplateManager } from \"@/templates\";\nimport { getTracer, setupTracing } from \"@/tracing\";\nimport { TrackManager } from \"@/track\";\nimport {\n GetPromptTemplateParams,\n LogRequest,\n RunRequest,\n WorkflowRequest,\n WorkflowResponse,\n} from \"@/types\";\nimport {\n anthropicRequest,\n azureOpenAIRequest,\n configureProviderSettings,\n getProviderConfig,\n googleRequest,\n openaiRequest,\n runWorkflowRequest,\n streamResponse,\n trackRequest,\n utilLogRequest,\n vertexaiRequest,\n} from \"@/utils/utils\";\nimport * as opentelemetry from \"@opentelemetry/api\";\n\nconst MAP_PROVIDER_TO_FUNCTION: Record<string, any> = {\n openai: openaiRequest,\n anthropic: anthropicRequest,\n \"openai.azure\": azureOpenAIRequest,\n google: googleRequest,\n vertexai: vertexaiRequest,\n};\n\nexport interface ClientOptions {\n apiKey?: string;\n enableTracing?: boolean;\n workspaceId?: number;\n}\n\nconst isWorkflowResultsDict = (obj: any): boolean => {\n if (!obj || typeof obj !== \"object\" || Array.isArray(obj)) {\n return false;\n }\n\n const REQUIRED_KEYS = [\n \"status\",\n \"value\",\n \"error_message\",\n \"raw_error_message\",\n \"is_output_node\",\n ];\n const values = Object.values(obj);\n\n return values.every((val) => {\n if (typeof val !== \"object\" || val === null) return false;\n return REQUIRED_KEYS.every((key) => key in val);\n });\n};\n\nexport class PromptLayer {\n apiKey: string;\n templates: TemplateManager;\n group: GroupManager;\n track: TrackManager;\n enableTracing: boolean;\n wrapWithSpan: typeof wrapWithSpan;\n\n constructor({\n apiKey = process.env.PROMPTLAYER_API_KEY,\n enableTracing = false,\n }: ClientOptions = {}) {\n if (apiKey === undefined) {\n throw new Error(\n \"PromptLayer API key not provided. Please set the PROMPTLAYER_API_KEY environment variable or pass the api_key parameter.\"\n );\n }\n\n this.apiKey = apiKey;\n this.enableTracing = enableTracing;\n this.templates = new TemplateManager(apiKey);\n this.group = new GroupManager(apiKey);\n this.track = new TrackManager(apiKey);\n this.wrapWithSpan = wrapWithSpan;\n\n if (enableTracing) {\n setupTracing(enableTracing, apiKey);\n }\n }\n\n get Anthropic() {\n try {\n const module = require(\"@anthropic-ai/sdk\").default;\n return promptLayerBase(this.apiKey, module, \"anthropic\", \"anthropic\");\n } catch (e) {\n console.error(\n \"To use the Anthropic module, you must install the @anthropic-ai/sdk package.\"\n );\n }\n }\n\n get OpenAI() {\n try {\n const module = require(\"openai\").default;\n return promptLayerBase(this.apiKey, module, \"openai\", \"openai\");\n } catch (e) {\n console.error(\n \"To use the OpenAI module, you must install the @openai/api package.\"\n );\n }\n }\n\n async run({\n promptName,\n promptVersion,\n promptReleaseLabel,\n inputVariables,\n tags,\n metadata,\n groupId,\n modelParameterOverrides,\n stream = false,\n provider,\n model,\n }: RunRequest) {\n const tracer = getTracer();\n\n return tracer.startActiveSpan(\"PromptLayer Run\", async (span) => {\n try {\n const functionInput = {\n promptName,\n promptVersion,\n promptReleaseLabel,\n inputVariables,\n tags,\n metadata,\n groupId,\n modelParameterOverrides,\n stream,\n };\n span.setAttribute(\"function_input\", JSON.stringify(functionInput));\n\n const prompt_input_variables = inputVariables;\n const templateGetParams: GetPromptTemplateParams = {\n label: promptReleaseLabel,\n version: promptVersion,\n metadata_filters: metadata,\n provider,\n model,\n };\n if (inputVariables) templateGetParams.input_variables = inputVariables;\n\n const promptBlueprint = await this.templates.get(\n promptName,\n templateGetParams\n );\n\n if (!promptBlueprint) throw new Error(\"Prompt not found\");\n\n const promptTemplate = promptBlueprint.prompt_template;\n if (!promptBlueprint.llm_kwargs) {\n console.warn(\n `Prompt '${promptName}' does not have any LLM kwargs associated with it. Please set your model parameters in the registry in the PromptLayer dashbaord.`\n );\n }\n\n const promptBlueprintMetadata = promptBlueprint.metadata;\n if (!promptBlueprintMetadata) {\n throw new Error(\n `Prompt '${promptName}' does not have any metadata associated with it.`\n );\n }\n\n const promptBlueprintModel = promptBlueprintMetadata.model;\n if (!promptBlueprintModel) {\n throw new Error(\n `Prompt '${promptName}' does not have a model parameters associated with it.`\n );\n }\n\n const customProvider = promptBlueprint.custom_provider;\n const request_start_time = new Date().toISOString();\n\n const { provider_type, kwargs } = configureProviderSettings(\n promptBlueprint,\n customProvider,\n modelParameterOverrides,\n stream\n );\n\n let provider_type_config = provider_type;\n if (promptBlueprintModel.name.startsWith(\"gemini\")) {\n provider_type_config = \"google\";\n } else if (promptBlueprintModel.name.startsWith(\"claude\")) {\n provider_type_config = \"anthropic\";\n }\n\n const config = getProviderConfig(provider_type_config, promptTemplate);\n const { function_name, stream_function } = config;\n\n const request_function = MAP_PROVIDER_TO_FUNCTION[provider_type];\n if (!request_function) {\n throw new Error(\n `No request function found for provider: ${provider_type}`\n );\n }\n\n const response = await request_function(promptBlueprint, kwargs);\n\n const _trackRequest = (body: object) => {\n const request_end_time = new Date().toISOString();\n return trackRequest({\n function_name,\n provider_type,\n args: [],\n kwargs,\n tags,\n request_start_time,\n request_end_time,\n api_key: this.apiKey,\n metadata,\n prompt_id: promptBlueprint.id,\n prompt_version: promptBlueprint.version,\n prompt_input_variables,\n group_id: groupId,\n return_prompt_blueprint: true,\n span_id: span.spanContext().spanId,\n ...body,\n });\n };\n\n if (stream)\n return streamResponse(response, _trackRequest, stream_function);\n const requestLog = await _trackRequest({ request_response: response });\n\n const functionOutput = {\n request_id: requestLog.request_id,\n raw_response: response,\n prompt_blueprint: requestLog.prompt_blueprint,\n };\n span.setAttribute(\"function_output\", JSON.stringify(functionOutput));\n\n return functionOutput;\n } catch (error) {\n span.setStatus({\n code: opentelemetry.SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : \"Unknown error\",\n });\n throw error;\n } finally {\n span.end();\n }\n });\n }\n\n async runWorkflow({\n workflowName,\n inputVariables = {},\n metadata = {},\n workflowLabelName = null,\n workflowVersion = null, // This is the version number, not the version ID\n returnAllOutputs = false,\n }: WorkflowRequest): Promise<WorkflowResponse> {\n try {\n const result = await runWorkflowRequest({\n workflow_name: workflowName,\n input_variables: inputVariables,\n metadata,\n workflow_label_name: workflowLabelName,\n workflow_version_number: workflowVersion,\n return_all_outputs: returnAllOutputs,\n api_key: this.apiKey,\n });\n\n if (!returnAllOutputs) {\n if (isWorkflowResultsDict(result)) {\n const nodeValues = Object.values(result);\n\n const outputNodes = nodeValues.filter(\n (node: any) => node.is_output_node === true\n );\n\n if (outputNodes.length === 0) {\n throw new Error(JSON.stringify(result, null, 2));\n }\n\n const anyOutputSuccess = outputNodes.some(\n (node: any) => node.status === \"SUCCESS\"\n );\n if (!anyOutputSuccess) {\n throw new Error(JSON.stringify(result, null, 2));\n }\n }\n }\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n console.error(\"Error running workflow:\", error.message);\n throw new Error(`Error running workflow: ${error.message}`);\n } else {\n console.error(\"Unknown error running workflow:\", error);\n throw new Error(\"Unknown error running workflow\");\n }\n }\n }\n\n async logRequest(body: LogRequest) {\n return utilLogRequest(this.apiKey, body);\n }\n}\n"],"mappings":"8yDAwBA,OAAOA,OAAU,OAQV,IAAMC,EAAgC,wBAO7C,SAAeC,GACbC,EACAC,EACAC,EACc,QAAAC,EAAA,sBACd,IAAMC,EAAW,MAAM,MACrB,GAAGC,CAAmB,qEAAqEL,CAAW,uBAAuBC,CA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":["Ably","SET_WORKFLOW_COMPLETE_MESSAGE","getFinalOutput","executionId","returnAllOutputs","headers","__async","response","URL_API_PROMPTLAYER","makeMessageListener","resultsPromise","message","SET_WORKFLOW_COMPLETE_MESSAGE","data","resultCode","results","err","waitForWorkflowCompletion","_0","token","channelName","timeout","client","Ably","channel","promise","resolve","reject","listener","timer","result","promptlayerApiHandler","apiKey","body","proxyGenerator","promptLayerApiRequest","warnOnBadResponse","e","promptLayerTrackMetadata","__spreadProps","__spreadValues","promptLayerTrackScore","promptLayerTrackPrompt","promptLayerTrackGroup","promptLayerCreateGroup","getPromptTemplate","promptName","params","url","publishPromptTemplate","getAllPromptTemplates","_a","key","value","runWorkflowRequest","workflow_name","input_variables","metadata","workflow_label_name","workflow_version_number","return_all_outputs","api_key","payload","execution_id","channel_name","ably_token","error","openaiStreamChat","_b","_c","_d","_e","_f","_g","_h","_i","_j","content","functionCall","lastResult","toolCalls","delta","toolCall","lastToolCall","firstChoice","anthropicStreamMessage","currentBlock","currentSignature","currentThinking","currentText","currentToolInputJson","event","inputJsonDelta","cleaned_result","function_name","prev","current","final_result","generator","__asyncGenerator","iter","__forAwait","more","temp","__await","request_response","request_id","main_message","trackRequest","openaiStreamCompletion","text","anthropicStreamCompletion","completion","streamResponse","afterStream","mapResults","openaiChatRequest","kwargs","openaiCompletionsRequest","MAP_TYPE_TO_OPENAI_FUNCTION","openaiRequest","promptBlueprint","OpenAI","requestToMake","azureOpenAIRequest","AzureOpenAI","anthropicChatRequest","anthropicCompletionsRequest","MAP_TYPE_TO_ANTHROPIC_FUNCTION","anthropicRequest","Anthropic","utilLogRequest","buildGoogleResponseFromParts","thoughtContent","regularContent","functionCalls","finalParts","thoughtPart","textPart","functionPart","googleStreamResponse","GenerateContentResponse","part","googleStreamChat","googleStreamCompletion","googleChatRequest","model_client","history","generationConfig","lastMessage","chat","googleCompletionsRequest","stream","__objRest","MAP_TYPE_TO_GOOGLE_FUNCTION","googleRequest","GoogleGenAI","geminiAPI","project","location","googleAuthOptions","genAI","kwargsCamelCased","convertKeysToCamelCase","snakeToCamel","str","_","letter","obj","STREAMING_PROVIDERS_WITH_USAGE","MAP_PROVIDER_TO_FUNCTION_NAME","configureProviderSettings","customProvider","modelParameterOverrides","provider_type","providerConfig","getProviderConfig","promptTemplate","providerMap","templateType","config","vertexaiRequest","model","AnthropicVertex","GroupManager","apiKey","promptLayerCreateGroup","opentelemetry","SimpleSpanProcessor","NodeTracerProvider","SpanKind","SpanStatusCode","ExportResultCode","PromptLayerSpanExporter","enableTracing","apiKey","URL_API_PROMPTLAYER","attributes","kind","SpanKind","code","SpanStatusCode","time","spans","ExportResultCode","requestData","span","_a","event","link","__spreadProps","__spreadValues","response","error","span_exporter_default","getTracer","name","setupTracing","enableTracing","apiKey","provider","NodeTracerProvider","exporter","span_exporter_default","processor","SimpleSpanProcessor","tracer","getTracer","promptLayerBase","apiKey","llm","function_name","provider","handler","target","args","newTarget","prop","receiver","value","_a","_b","_c","_d","request_start_time","provider_type","return_pl_id","pl_tags","span","__async","response","spanId","resolve","reject","request_response","promptlayerApiHandler","error","opentelemetry","wrapWithSpan","functionName","func","attributes","args","tracer","getTracer","wrapperFunction","span","key","value","result","resolvedResult","error","handleError","TemplateManager","apiKey","promptName","params","getPromptTemplate","body","publishPromptTemplate","getAllPromptTemplates","metadata","apiKey","body","key","value","promptLayerTrackMetadata","score","promptLayerTrackScore","prompt","promptLayerTrackPrompt","group","promptLayerTrackGroup","TrackManager","opentelemetry","MAP_PROVIDER_TO_FUNCTION","openaiRequest","anthropicRequest","azureOpenAIRequest","googleRequest","vertexaiRequest","isWorkflowResultsDict","obj","REQUIRED_KEYS","val","key","PromptLayer","apiKey","enableTracing","TemplateManager","GroupManager","TrackManager","wrapWithSpan","setupTracing","module","promptLayerBase","_0","__async","promptName","promptVersion","promptReleaseLabel","inputVariables","tags","metadata","groupId","modelParameterOverrides","stream","provider","model","getTracer","span","functionInput","prompt_input_variables","templateGetParams","promptBlueprint","promptTemplate","promptBlueprintMetadata","promptBlueprintModel","customProvider","request_start_time","provider_type","kwargs","configureProviderSettings","provider_type_config","config","getProviderConfig","function_name","stream_function","request_function","response","_trackRequest","body","request_end_time","trackRequest","__spreadValues","streamResponse","requestLog","functionOutput","error","workflowName","workflowLabelName","workflowVersion","returnAllOutputs","result","runWorkflowRequest","outputNodes","node","utilLogRequest"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/utils.ts","../../src/utils/blueprint-builder.ts","../../src/groups.ts","../../src/tracing.ts","../../src/span-exporter.ts","../../src/promptlayer.ts","../../src/span-wrapper.ts","../../src/templates.ts","../../src/track.ts","../../src/index.ts"],"sourcesContent":["import {\n GetPromptTemplateParams,\n GetPromptTemplateResponse,\n ListPromptTemplatesResponse,\n LogRequest,\n Pagination,\n PublishPromptTemplate,\n PublishPromptTemplateResponse,\n RequestLog,\n RunWorkflowRequestParams,\n TrackGroup,\n TrackMetadata,\n TrackPrompt,\n TrackRequest,\n TrackScore,\n WorkflowResponse,\n} from \"@/types\";\nimport type { AnthropicBedrock } from \"@anthropic-ai/bedrock-sdk\";\nimport type TypeAnthropic from \"@anthropic-ai/sdk\";\nimport {\n Completion as AnthropicCompletion,\n Message,\n} from \"@anthropic-ai/sdk/resources\";\nimport { MessageStreamEvent } from \"@anthropic-ai/sdk/resources/messages\";\nimport type { AnthropicVertex } from \"@anthropic-ai/vertex-sdk\";\nimport Ably from \"ably\";\nimport type TypeOpenAI from \"openai\";\nimport {\n ChatCompletion,\n ChatCompletionChunk,\n Completion,\n} from \"openai/resources\";\nimport {\n buildPromptBlueprintFromAnthropicEvent,\n buildPromptBlueprintFromGoogleEvent,\n buildPromptBlueprintFromOpenAIEvent,\n} from \"./blueprint-builder\";\n\nexport const SET_WORKFLOW_COMPLETE_MESSAGE = \"SET_WORKFLOW_COMPLETE\";\n\nexport enum FinalOutputCode {\n OK = \"OK\",\n EXCEEDS_SIZE_LIMIT = \"EXCEEDS_SIZE_LIMIT\",\n}\n\nasync function getFinalOutput(\n executionId: number,\n returnAllOutputs: boolean,\n headers: Record<string, string>\n): Promise<any> {\n const response = await fetch(\n `${URL_API_PROMPTLAYER}/workflow-version-execution-results?workflow_version_execution_id=${executionId}&return_all_outputs=${returnAllOutputs}`,\n { headers }\n );\n if (!response.ok) {\n throw new Error(\"Failed to fetch final output\");\n }\n return response.json();\n}\n\nfunction makeMessageListener(\n resultsPromise: { resolve: (data: any) => void; reject: (err: any) => void },\n executionId: number,\n returnAllOutputs: boolean,\n headers: Record<string, string>\n) {\n return async function (message: any) {\n if (message.name !== SET_WORKFLOW_COMPLETE_MESSAGE) return;\n\n try {\n const data = JSON.parse(message.data);\n const resultCode = data.result_code;\n let results;\n\n if (resultCode === FinalOutputCode.OK || resultCode == null) {\n results = data.final_output;\n } else if (resultCode === FinalOutputCode.EXCEEDS_SIZE_LIMIT) {\n results = await getFinalOutput(executionId, returnAllOutputs, headers);\n } else {\n throw new Error(`Unsupported final output code: ${resultCode}`);\n }\n\n resultsPromise.resolve(results);\n } catch (err) {\n resultsPromise.reject(err);\n }\n };\n}\n\nasync function waitForWorkflowCompletion({\n token,\n channelName,\n executionId,\n returnAllOutputs,\n headers,\n timeout,\n}: {\n token: string;\n channelName: string;\n executionId: number;\n returnAllOutputs: boolean;\n headers: Record<string, string>;\n timeout: number;\n}): Promise<any> {\n const client = new Ably.Realtime(token);\n const channel = client.channels.get(channelName);\n\n const resultsPromise = {} as {\n resolve: (value: any) => void;\n reject: (reason?: any) => void;\n };\n\n const promise = new Promise<any>((resolve, reject) => {\n resultsPromise.resolve = resolve;\n resultsPromise.reject = reject;\n });\n\n const listener = makeMessageListener(\n resultsPromise,\n executionId,\n returnAllOutputs,\n headers\n );\n await channel.subscribe(SET_WORKFLOW_COMPLETE_MESSAGE, listener);\n\n try {\n return await new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new Error(\"Workflow execution did not complete properly (timeout)\")\n );\n }, timeout);\n\n promise\n .then((result) => {\n clearTimeout(timer);\n resolve(result);\n })\n .catch((err) => {\n clearTimeout(timer);\n reject(err);\n });\n });\n } finally {\n console.log(\"Closing client\");\n channel.unsubscribe(SET_WORKFLOW_COMPLETE_MESSAGE, listener);\n client.close();\n console.log(\"Closed client\");\n }\n}\n\nexport const URL_API_PROMPTLAYER =\n process.env.PROMPTLAYER_API_URL || \"https://api.promptlayer.com\";\n\nconst promptlayerApiHandler = async <Item>(\n apiKey: string,\n body: TrackRequest & {\n request_response: AsyncIterable<Item> | any;\n }\n) => {\n const isGenerator = body.request_response[Symbol.asyncIterator] !== undefined;\n if (isGenerator) {\n return proxyGenerator(apiKey, body.request_response, body);\n }\n return await promptLayerApiRequest(apiKey, body);\n};\n\nconst promptLayerApiRequest = async (apiKey: string, body: TrackRequest) => {\n try {\n const response = await fetch(`${URL_API_PROMPTLAYER}/track-request`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While logging your request, PromptLayer experienced the following error:\"\n );\n }\n if (data && body.return_pl_id) {\n return [body.request_response, data.request_id];\n }\n } catch (e) {\n console.warn(\n `WARNING: While logging your request PromptLayer had the following error: ${e}`\n );\n }\n return body.request_response;\n};\n\nconst promptLayerTrackMetadata = async (\n apiKey: string,\n body: TrackMetadata\n): Promise<boolean> => {\n try {\n const response = await fetch(\n `${URL_API_PROMPTLAYER}/library-track-metadata`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n ...body,\n api_key: apiKey,\n }),\n }\n );\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While logging metadata to your request, PromptLayer experienced the following error\"\n );\n return false;\n }\n } catch (e) {\n console.warn(\n `WARNING: While logging metadata to your request, PromptLayer experienced the following error: ${e}`\n );\n return false;\n }\n return true;\n};\n\nconst promptLayerTrackScore = async (\n apiKey: string,\n body: TrackScore\n): Promise<boolean> => {\n try {\n const response = await fetch(`${URL_API_PROMPTLAYER}/library-track-score`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n ...body,\n api_key: apiKey,\n }),\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While scoring your request, PromptLayer experienced the following error\"\n );\n return false;\n }\n } catch (e) {\n console.warn(\n `WARNING: While scoring your request, PromptLayer experienced the following error: ${e}`\n );\n return false;\n }\n return true;\n};\n\nconst promptLayerTrackPrompt = async (\n apiKey: string,\n body: TrackPrompt\n): Promise<boolean> => {\n try {\n const response = await fetch(\n `${URL_API_PROMPTLAYER}/library-track-prompt`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n ...body,\n api_key: apiKey,\n }),\n }\n );\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While associating your request with a prompt template, PromptLayer experienced the following error\"\n );\n return false;\n }\n } catch (e) {\n console.warn(\n `WARNING: While associating your request with a prompt template, PromptLayer experienced the following error: ${e}`\n );\n return false;\n }\n return true;\n};\n\nconst promptLayerTrackGroup = async (\n apiKey: string,\n body: TrackGroup\n): Promise<boolean> => {\n try {\n const response = await fetch(`${URL_API_PROMPTLAYER}/track-group`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n ...body,\n api_key: apiKey,\n }),\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While associating your request with a group, PromptLayer experienced the following error\"\n );\n return false;\n }\n } catch (e) {\n console.warn(\n `WARNING: While associating your request with a group, PromptLayer experienced the following error: ${e}`\n );\n return false;\n }\n return true;\n};\n\nconst promptLayerCreateGroup = async (\n apiKey: string\n): Promise<number | boolean> => {\n try {\n const response = await fetch(`${URL_API_PROMPTLAYER}/create-group`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n api_key: apiKey,\n }),\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While creating a group PromptLayer had the following error\"\n );\n return false;\n }\n return data.id;\n } catch (e) {\n console.warn(\n `WARNING: While creating a group PromptLayer had the following error: ${e}`\n );\n return false;\n }\n};\n\nconst getPromptTemplate = async (\n apiKey: string,\n promptName: string,\n params?: Partial<GetPromptTemplateParams>\n) => {\n try {\n const url = new URL(\n `${URL_API_PROMPTLAYER}/prompt-templates/${promptName}`\n );\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-API-KEY\": apiKey,\n },\n body: JSON.stringify(params),\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While fetching a prompt template PromptLayer had the following error\"\n );\n return null;\n }\n if (data.warning) {\n console.warn(\n `WARNING: While fetching your prompt PromptLayer had the following error: ${data.warning}`\n );\n }\n return data as Promise<GetPromptTemplateResponse>;\n } catch (e) {\n console.warn(\n `WARNING: While fetching a prompt template PromptLayer had the following error: ${e}`\n );\n return null;\n }\n};\n\nconst publishPromptTemplate = async (\n apiKey: string,\n body: PublishPromptTemplate\n) => {\n try {\n const response = await fetch(\n `${URL_API_PROMPTLAYER}/rest/prompt-templates`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-API-KEY\": apiKey,\n },\n body: JSON.stringify({\n prompt_template: { ...body },\n prompt_version: { ...body },\n release_labels: body.release_labels ? body.release_labels : undefined,\n }),\n }\n );\n const data = await response.json();\n if (response.status === 400) {\n warnOnBadResponse(\n data,\n \"WARNING: While publishing a prompt template PromptLayer had the following error\"\n );\n }\n return data as Promise<PublishPromptTemplateResponse>;\n } catch (e) {\n console.warn(\n `WARNING: While publishing a prompt template PromptLayer had the following error: ${e}`\n );\n }\n};\n\nconst getAllPromptTemplates = async (\n apiKey: string,\n params?: Partial<Pagination>\n) => {\n try {\n const url = new URL(`${URL_API_PROMPTLAYER}/prompt-templates`);\n Object.entries(params || {}).forEach(([key, value]) =>\n url.searchParams.append(key, value.toString())\n );\n const response = await fetch(url, {\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-API-KEY\": apiKey,\n },\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While fetching all prompt templates PromptLayer had the following error\"\n );\n return null;\n }\n return (data.items ?? []) as Promise<Array<ListPromptTemplatesResponse>>;\n } catch (e) {\n console.warn(\n `WARNING: While fetching all prompt templates PromptLayer had the following error: ${e}`\n );\n return null;\n }\n};\n\nexport const runWorkflowRequest = async ({\n workflow_name,\n input_variables,\n metadata = {},\n workflow_label_name = null,\n workflow_version_number = null,\n return_all_outputs = false,\n api_key,\n timeout = 3600000, // Default timeout is 1 hour in milliseconds\n}: RunWorkflowRequestParams): Promise<WorkflowResponse> => {\n const payload = {\n input_variables,\n metadata,\n workflow_label_name,\n workflow_version_number,\n return_all_outputs,\n };\n\n const headers = {\n \"X-API-KEY\": api_key,\n \"Content-Type\": \"application/json\",\n };\n\n try {\n const response = await fetch(\n `${URL_API_PROMPTLAYER}/workflows/${encodeURIComponent(\n workflow_name\n )}/run`,\n {\n method: \"POST\",\n headers: headers,\n body: JSON.stringify(payload),\n }\n );\n\n if (response.status !== 201) {\n const errorData = await response.json().catch(() => ({}));\n return {\n success: false,\n message: `Failed to run workflow: ${\n errorData.error || response.statusText\n }`,\n };\n }\n\n const result = await response.json();\n if (result.warning) {\n console.warn(`WARNING: ${result.warning}`);\n }\n const execution_id = result.workflow_version_execution_id;\n if (!execution_id) {\n console.log(\"No execution ID returned from workflow run\");\n return { success: false, message: \"Failed to run workflow\" };\n }\n\n const channel_name = `workflow_updates:${execution_id}`;\n const ws_response = await fetch(\n `${URL_API_PROMPTLAYER}/ws-token-request-library?capability=${channel_name}`,\n {\n method: \"POST\",\n headers: headers,\n }\n );\n\n const ws_token_response = await ws_response.json();\n const ably_token = ws_token_response.token_details.token;\n return await waitForWorkflowCompletion({\n token: ably_token,\n channelName: channel_name,\n executionId: execution_id,\n returnAllOutputs: return_all_outputs,\n headers: headers,\n timeout: timeout,\n });\n } catch (error) {\n console.error(\n `Failed to run workflow: ${\n error instanceof Error ? error.message : error\n }`\n );\n throw error;\n }\n};\n\nconst openaiStreamChat = (results: ChatCompletionChunk[]): ChatCompletion => {\n let content: ChatCompletion.Choice[\"message\"][\"content\"] = null;\n let functionCall: ChatCompletion.Choice[\"message\"][\"function_call\"] =\n undefined;\n const response: ChatCompletion = {\n id: \"\",\n choices: [],\n created: Date.now(),\n model: \"\",\n object: \"chat.completion\",\n };\n const lastResult = results.at(-1);\n if (!lastResult) return response;\n let toolCalls: ChatCompletion.Choice[\"message\"][\"tool_calls\"] = undefined;\n for (const result of results) {\n if (result.choices.length === 0) continue;\n const delta = result.choices[0].delta;\n\n if (delta.content) {\n content = `${content || \"\"}${delta.content || \"\"}`;\n }\n if (delta.function_call) {\n functionCall = {\n name: `${functionCall ? functionCall.name : \"\"}${\n delta.function_call.name || \"\"\n }`,\n arguments: `${functionCall ? functionCall.arguments : \"\"}${\n delta.function_call.arguments || \"\"\n }`,\n };\n }\n const toolCall = delta.tool_calls?.[0];\n if (toolCall) {\n toolCalls = toolCalls || [];\n const lastToolCall = toolCalls.at(-1);\n if (!lastToolCall || toolCall.id) {\n toolCalls.push({\n id: toolCall.id || \"\",\n type: toolCall.type || \"function\",\n function: {\n name: toolCall.function?.name || \"\",\n arguments: toolCall.function?.arguments || \"\",\n },\n });\n continue;\n }\n lastToolCall.function.name = `${lastToolCall.function.name}${\n toolCall.function?.name || \"\"\n }`;\n lastToolCall.function.arguments = `${lastToolCall.function.arguments}${\n toolCall.function?.arguments || \"\"\n }`;\n }\n }\n const firstChoice = results[0].choices.at(0);\n response.choices.push({\n finish_reason: firstChoice?.finish_reason ?? \"stop\",\n index: firstChoice?.index ?? 0,\n logprobs: firstChoice?.logprobs ?? null,\n message: {\n role: \"assistant\",\n content,\n function_call: functionCall ? functionCall : undefined,\n tool_calls: toolCalls ? toolCalls : undefined,\n refusal: firstChoice?.delta.refusal ?? null,\n },\n });\n response.id = lastResult.id;\n response.model = lastResult.model;\n response.created = lastResult.created;\n response.system_fingerprint = lastResult.system_fingerprint;\n response.usage = lastResult.usage ?? undefined;\n return response;\n};\n\nconst anthropicStreamMessage = (results: MessageStreamEvent[]): Message => {\n let response: Message = {\n id: \"\",\n model: \"\",\n content: [],\n role: \"assistant\",\n type: \"message\",\n stop_reason: \"stop_sequence\",\n stop_sequence: null,\n usage: {\n input_tokens: 0,\n output_tokens: 0,\n cache_creation_input_tokens: 0,\n cache_read_input_tokens: 0,\n server_tool_use: null,\n service_tier: null,\n },\n };\n const lastResult = results.at(-1);\n if (!lastResult) return response;\n let currentBlock: any = null;\n let currentSignature = \"\";\n let currentThinking = \"\";\n let currentText = \"\";\n let currentToolInputJson = \"\";\n\n for (const event of results) {\n if (event.type === \"message_start\") {\n response = { ...event.message };\n } else if (event.type === \"content_block_start\") {\n currentBlock = { ...event.content_block };\n if (currentBlock.type === \"thinking\") {\n currentSignature = \"\";\n currentThinking = \"\";\n } else if (currentBlock.type === \"text\") {\n currentText = \"\";\n } else if (\n currentBlock.type === \"tool_use\" ||\n currentBlock.type === \"server_tool_use\"\n ) {\n currentToolInputJson = \"\";\n }\n } else if (event.type === \"content_block_delta\" && currentBlock !== null) {\n if (currentBlock.type === \"thinking\") {\n if (\"signature\" in event.delta) {\n currentSignature = event.delta.signature || \"\";\n }\n if (\"thinking\" in event.delta) {\n currentThinking += event.delta.thinking || \"\";\n }\n } else if (currentBlock.type === \"text\") {\n if (\"text\" in event.delta) {\n currentText += event.delta.text || \"\";\n }\n } else if (\n currentBlock.type === \"tool_use\" ||\n currentBlock.type === \"server_tool_use\"\n ) {\n if (event.delta.type === \"input_json_delta\") {\n const inputJsonDelta = event.delta as any;\n currentToolInputJson += inputJsonDelta.partial_json || \"\";\n }\n }\n } else if (event.type === \"content_block_stop\" && currentBlock !== null) {\n if (currentBlock.type === \"thinking\") {\n currentBlock.signature = currentSignature;\n currentBlock.thinking = currentThinking;\n } else if (currentBlock.type === \"text\") {\n currentBlock.text = currentText;\n currentBlock.citations = null;\n } else if (\n currentBlock.type === \"tool_use\" ||\n currentBlock.type === \"server_tool_use\"\n ) {\n try {\n currentBlock.input = currentToolInputJson\n ? JSON.parse(currentToolInputJson)\n : {};\n } catch (e) {\n currentBlock.input = {};\n }\n }\n response.content!.push(currentBlock);\n currentBlock = null;\n currentSignature = \"\";\n currentThinking = \"\";\n currentText = \"\";\n currentToolInputJson = \"\";\n } else if (event.type === \"message_delta\") {\n if (\"usage\" in event && event.usage) {\n response.usage = {\n ...response.usage,\n output_tokens: event.usage.output_tokens ?? 0,\n };\n }\n if (\"delta\" in event && event.delta) {\n if (\n \"stop_reason\" in event.delta &&\n event.delta.stop_reason !== undefined\n ) {\n response.stop_reason = event.delta.stop_reason;\n }\n if (\n \"stop_sequence\" in event.delta &&\n event.delta.stop_sequence !== undefined\n ) {\n response.stop_sequence = event.delta.stop_sequence;\n }\n }\n }\n }\n\n return response;\n};\n\nconst cleaned_result = (\n results: any[],\n function_name = \"openai.chat.completions.create\"\n) => {\n if (\"completion\" in results[0]) {\n return results.reduce(\n (prev, current) => ({\n ...current,\n completion: `${prev.completion}${current.completion}`,\n }),\n {}\n );\n }\n\n if (function_name === \"anthropic.messages.create\")\n return anthropicStreamMessage(results);\n\n if (\"text\" in results[0].choices[0]) {\n let response = \"\";\n for (const result of results) {\n response = `${response}${result.choices[0].text}`;\n }\n const final_result = structuredClone(results.at(-1));\n final_result.choices[0].text = response;\n return final_result;\n }\n\n if (\"delta\" in results[0].choices[0]) {\n const response = openaiStreamChat(results);\n response.choices[0] = {\n ...response.choices[0],\n ...response.choices[0].message,\n };\n return response;\n }\n\n return \"\";\n};\n\nasync function* proxyGenerator<Item>(\n apiKey: string,\n generator: AsyncIterable<Item>,\n body: TrackRequest\n) {\n const results = [];\n for await (const value of generator) {\n yield body.return_pl_id ? [value, null] : value;\n results.push(value);\n }\n const request_response = cleaned_result(results, body.function_name);\n const response = await promptLayerApiRequest(apiKey, {\n ...body,\n request_response,\n request_end_time: new Date().toISOString(),\n });\n if (response) {\n if (body.return_pl_id) {\n const request_id = (response as any)[1];\n const lastResult = results.at(-1);\n yield [lastResult, request_id];\n }\n }\n}\n\nconst warnOnBadResponse = (request_response: any, main_message: string) => {\n try {\n console.warn(`${main_message}: ${request_response.message}`);\n } catch (e) {\n console.warn(`${main_message}: ${request_response}`);\n }\n};\n\nconst trackRequest = async (body: TrackRequest) => {\n try {\n const response = await fetch(`${URL_API_PROMPTLAYER}/track-request`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n const data = await response.json();\n if (response.status !== 200) {\n warnOnBadResponse(\n data,\n \"WARNING: While logging your request, PromptLayer experienced the following error:\"\n );\n }\n return data;\n } catch (e) {\n console.warn(\n `WARNING: While logging your request PromptLayer had the following error: ${e}`\n );\n }\n return {};\n};\n\nconst openaiStreamCompletion = (results: Completion[]) => {\n const response: Completion = {\n id: \"\",\n choices: [\n {\n finish_reason: \"stop\",\n index: 0,\n text: \"\",\n logprobs: null,\n },\n ],\n created: Date.now(),\n model: \"\",\n object: \"text_completion\",\n };\n const lastResult = results.at(-1);\n if (!lastResult) return response;\n let text = \"\";\n for (const result of results) {\n if (result.choices.length > 0 && result.choices[0].text) {\n text = `${text}${result.choices[0].text}`;\n }\n }\n response.choices[0].text = text;\n response.id = lastResult.id;\n response.created = lastResult.created;\n response.model = lastResult.model;\n response.system_fingerprint = lastResult.system_fingerprint;\n response.usage = lastResult.usage;\n return response;\n};\n\nconst anthropicStreamCompletion = (results: AnthropicCompletion[]) => {\n const response: AnthropicCompletion = {\n completion: \"\",\n id: \"\",\n model: \"\",\n stop_reason: \"\",\n type: \"completion\",\n };\n const lastResult = results.at(-1);\n if (!lastResult) return response;\n let completion = \"\";\n for (const result of results) {\n completion = `${completion}${result.completion}`;\n }\n response.completion = completion;\n response.id = lastResult.id;\n response.model = lastResult.model;\n response.stop_reason = lastResult.stop_reason;\n return response;\n};\n\nasync function* streamResponse<Item>(\n generator: AsyncIterable<Item>,\n afterStream: (body: object) => any,\n mapResults: any,\n metadata: any\n) {\n const data: {\n request_id: number | null;\n raw_response: any;\n prompt_blueprint: any;\n } = {\n request_id: null,\n raw_response: null,\n prompt_blueprint: null,\n };\n const results = [];\n for await (const result of generator) {\n results.push(result);\n data.raw_response = result;\n\n // Build prompt blueprint for Anthropic streaming events\n if (result && typeof result === \"object\" && \"type\" in result) {\n data.prompt_blueprint = buildPromptBlueprintFromAnthropicEvent(\n result as MessageStreamEvent,\n metadata\n );\n }\n\n // Build prompt blueprint for Google streaming events\n if (result && typeof result === \"object\" && \"candidates\" in result) {\n data.prompt_blueprint = buildPromptBlueprintFromGoogleEvent(\n result,\n metadata\n );\n }\n\n // Build prompt blueprint for OpenAI streaming events\n if (result && typeof result === \"object\" && \"choices\" in result) {\n data.prompt_blueprint = buildPromptBlueprintFromOpenAIEvent(\n result,\n metadata\n );\n }\n\n yield data;\n }\n const request_response = mapResults(results);\n const response = await afterStream({ request_response });\n data.request_id = response.request_id;\n data.prompt_blueprint = response.prompt_blueprint;\n yield data;\n}\n\nconst openaiChatRequest = async (client: TypeOpenAI, kwargs: any) => {\n return client.chat.completions.create(kwargs);\n};\n\nconst openaiCompletionsRequest = async (client: TypeOpenAI, kwargs: any) => {\n return client.completions.create(kwargs);\n};\n\nconst MAP_TYPE_TO_OPENAI_FUNCTION = {\n chat: openaiChatRequest,\n completion: openaiCompletionsRequest,\n};\n\nconst openaiRequest = async (\n promptBlueprint: GetPromptTemplateResponse,\n kwargs: any\n) => {\n const OpenAI = require(\"openai\").default;\n const client = new OpenAI({\n baseURL: kwargs.baseURL,\n apiKey: kwargs.apiKey,\n });\n const requestToMake =\n MAP_TYPE_TO_OPENAI_FUNCTION[promptBlueprint.prompt_template.type];\n return requestToMake(client, kwargs);\n};\n\nconst azureOpenAIRequest = async (\n promptBlueprint: GetPromptTemplateResponse,\n kwargs: any\n) => {\n const { AzureOpenAI } = require(\"openai\");\n const client = new AzureOpenAI({\n endpoint: process.env.AZURE_OPENAI_ENDPOINT || kwargs.baseURL,\n apiVersion: process.env.OPENAI_API_VERSION || kwargs.apiVersion,\n apiKey: process.env.AZURE_OPENAI_API_KEY || kwargs.apiKey,\n });\n delete kwargs?.baseURL;\n delete kwargs?.apiVersion;\n delete kwargs?.apiKey;\n const requestToMake =\n MAP_TYPE_TO_OPENAI_FUNCTION[promptBlueprint.prompt_template.type];\n return requestToMake(client, kwargs);\n};\n\nconst anthropicChatRequest = async (\n client: TypeAnthropic | AnthropicVertex | AnthropicBedrock,\n kwargs: any\n) => {\n return client.messages.create(kwargs);\n};\n\nconst anthropicCompletionsRequest = async (\n client: TypeAnthropic | AnthropicBedrock,\n kwargs: any\n) => {\n return client.completions.create(kwargs);\n};\n\nconst MAP_TYPE_TO_ANTHROPIC_FUNCTION = {\n chat: anthropicChatRequest,\n completion: anthropicCompletionsRequest,\n};\n\nconst anthropicRequest = async (\n promptBlueprint: GetPromptTemplateResponse,\n kwargs: any\n) => {\n const Anthropic = require(\"@anthropic-ai/sdk\").default;\n const client = new Anthropic({\n baseURL: kwargs.baseURL,\n apiKey: kwargs.apiKey,\n });\n const requestToMake =\n MAP_TYPE_TO_ANTHROPIC_FUNCTION[promptBlueprint.prompt_template.type];\n return requestToMake(client, kwargs);\n};\n\nconst utilLogRequest = async (\n apiKey: string,\n body: LogRequest\n): Promise<RequestLog | null> => {\n try {\n const response = await fetch(`${URL_API_PROMPTLAYER}/log-request`, {\n method: \"POST\",\n headers: {\n \"X-API-KEY\": apiKey,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n const data = await response.json();\n if (response.status !== 201) {\n warnOnBadResponse(\n data,\n \"WARNING: While logging your request PromptLayer had the following error\"\n );\n return null;\n }\n return data;\n } catch (e) {\n console.warn(\n `WARNING: While tracking your prompt PromptLayer had the following error: ${e}`\n );\n return null;\n }\n};\n\nconst buildGoogleResponseFromParts = (\n thoughtContent: string,\n regularContent: string,\n functionCalls: any[],\n lastResult: any\n) => {\n const response = { ...lastResult };\n const finalParts = [];\n\n if (thoughtContent) {\n const thoughtPart = {\n text: thoughtContent,\n thought: true,\n };\n finalParts.push(thoughtPart);\n }\n\n if (regularContent) {\n const textPart = {\n text: regularContent,\n thought: null,\n };\n finalParts.push(textPart);\n }\n\n for (const functionCall of functionCalls) {\n const functionPart = {\n function_call: functionCall,\n };\n finalParts.push(functionPart);\n }\n\n if (finalParts.length > 0 && response.candidates?.[0]?.content) {\n response.candidates[0].content.parts = finalParts;\n }\n\n return response;\n};\n\nconst googleStreamResponse = (results: any[]) => {\n const { GenerateContentResponse } = require(\"@google/genai\");\n\n if (!results.length) {\n return new GenerateContentResponse();\n }\n\n let thoughtContent = \"\";\n let regularContent = \"\";\n const functionCalls: any[] = [];\n\n for (const result of results) {\n if (result.candidates && result.candidates[0]?.content?.parts) {\n for (const part of result.candidates[0].content.parts) {\n if (part.text) {\n if (part.thought === true) {\n thoughtContent += part.text;\n } else {\n regularContent += part.text;\n }\n } else if (part.functionCall) {\n functionCalls.push(part.functionCall);\n }\n }\n }\n }\n\n return buildGoogleResponseFromParts(\n thoughtContent,\n regularContent,\n functionCalls,\n results[results.length - 1]\n );\n};\n\nconst googleStreamChat = (results: any[]) => {\n return googleStreamResponse(results);\n};\n\nconst googleStreamCompletion = (results: any[]) => {\n return googleStreamResponse(results);\n};\n\nconst googleChatRequest = async (model_client: any, kwargs: any) => {\n const history = kwargs?.history;\n const generationConfig = kwargs?.generationConfig;\n const lastMessage =\n history.length > 0 ? history[history.length - 1]?.parts : \"\";\n const chat = model_client.chats.create({\n model: kwargs?.model,\n history: history.slice(0, -1) ?? [],\n config: generationConfig,\n });\n\n if (kwargs?.stream)\n return await chat.sendMessageStream({ message: lastMessage });\n return await chat.sendMessage({ message: lastMessage });\n};\n\nconst googleCompletionsRequest = async (\n model_client: any,\n { stream, ...kwargs }: any\n) => {\n if (stream) return await model_client.generateContentStream({ ...kwargs });\n return await model_client.generateContent({ ...kwargs });\n};\n\nconst MAP_TYPE_TO_GOOGLE_FUNCTION = {\n chat: googleChatRequest,\n completion: googleCompletionsRequest,\n};\n\nconst googleRequest = async (\n promptBlueprint: GetPromptTemplateResponse,\n kwargs: any\n) => {\n const { GoogleGenAI } = await import(\"@google/genai\");\n\n const geminiAPI = process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY;\n const project =\n process.env.VERTEX_AI_PROJECT_ID ||\n process.env.GOOGLE_PROJECT_ID ||\n process.env.GOOGLE_CLOUD_PROJECT;\n const location =\n process.env.VERTEX_AI_PROJECT_LOCATION ||\n process.env.GOOGLE_PROJECT_LOCATION ||\n process.env.GOOGLE_CLOUD_PROJECT_LOCATION;\n const googleAuthOptions = {\n keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS,\n projectId: project,\n scopes: [\"https://www.googleapis.com/auth/cloud-platform\"],\n };\n\n const genAI = geminiAPI\n ? new GoogleGenAI({ apiKey: geminiAPI })\n : new GoogleGenAI({\n vertexai: true,\n project: project,\n location: location,\n googleAuthOptions,\n });\n const requestToMake =\n MAP_TYPE_TO_GOOGLE_FUNCTION[promptBlueprint.prompt_template.type];\n\n return await requestToMake(genAI, kwargs);\n};\n\nconst snakeToCamel = (str: string): string =>\n str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());\n\nconst convertKeysToCamelCase = <T>(\n obj: T,\n ignoreValuesWithKeys: Set<string> = new Set()\n): T => {\n if (!obj || typeof obj !== \"object\") return obj;\n if (Array.isArray(obj))\n return obj.map((item) =>\n convertKeysToCamelCase(item, ignoreValuesWithKeys)\n ) as T;\n\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => {\n if (ignoreValuesWithKeys.has(key)) {\n return [snakeToCamel(key), value];\n }\n return [\n snakeToCamel(key),\n convertKeysToCamelCase(value, ignoreValuesWithKeys),\n ];\n })\n ) as T;\n};\n\nconst STREAMING_PROVIDERS_WITH_USAGE = [\"openai\", \"openai.azure\"] as const;\n\nconst MAP_PROVIDER_TO_FUNCTION_NAME = {\n openai: {\n chat: {\n function_name: \"openai.chat.completions.create\",\n stream_function: openaiStreamChat,\n },\n completion: {\n function_name: \"openai.completions.create\",\n stream_function: openaiStreamCompletion,\n },\n },\n anthropic: {\n chat: {\n function_name: \"anthropic.messages.create\",\n stream_function: anthropicStreamMessage,\n },\n completion: {\n function_name: \"anthropic.completions.create\",\n stream_function: anthropicStreamCompletion,\n },\n },\n \"openai.azure\": {\n chat: {\n function_name: \"openai.AzureOpenAI.chat.completions.create\",\n stream_function: openaiStreamChat,\n },\n completion: {\n function_name: \"openai.AzureOpenAI.completions.create\",\n stream_function: openaiStreamCompletion,\n },\n },\n google: {\n chat: {\n function_name: \"google.convo.send_message\",\n stream_function: googleStreamChat,\n },\n completion: {\n function_name: \"google.model.generate_content\",\n stream_function: googleStreamCompletion,\n },\n },\n \"anthropic.bedrock\": {\n chat: {\n function_name: \"anthropic.messages.create\",\n stream_function: anthropicStreamMessage,\n },\n completion: {\n function_name: \"anthropic.completions.create\",\n stream_function: anthropicStreamCompletion,\n },\n },\n};\n\nconst configureProviderSettings = (\n promptBlueprint: any,\n customProvider: any,\n modelParameterOverrides: any = {},\n stream: boolean = false\n) => {\n const provider_type =\n customProvider?.client ?? promptBlueprint.metadata?.model?.provider;\n\n if (!provider_type) {\n throw new Error(\n \"Provider type not found in prompt blueprint or custom provider\"\n );\n }\n\n let kwargs = {\n ...(promptBlueprint.llm_kwargs || {}),\n ...modelParameterOverrides,\n stream,\n };\n\n if (\n [\"google\", \"vertexai\"].includes(provider_type) &&\n promptBlueprint.metadata?.model?.name.startsWith(\"gemini\")\n )\n kwargs = convertKeysToCamelCase(kwargs, new Set([\"function_declarations\"]));\n\n const providerConfig = {\n baseURL: customProvider?.base_url ?? promptBlueprint.provider_base_url?.url,\n apiKey: customProvider?.api_key,\n };\n\n Object.entries(providerConfig).forEach(([key, value]) => {\n if (value !== undefined) {\n kwargs[key] = value;\n }\n });\n\n if (stream && STREAMING_PROVIDERS_WITH_USAGE.includes(provider_type as any)) {\n kwargs.stream_options = { include_usage: true };\n }\n\n return { provider_type, kwargs };\n};\n\nconst getProviderConfig = (provider_type: string, promptTemplate: any) => {\n const providerMap =\n MAP_PROVIDER_TO_FUNCTION_NAME[\n provider_type as keyof typeof MAP_PROVIDER_TO_FUNCTION_NAME\n ];\n\n if (!providerMap) {\n throw new Error(`Unsupported provider type: ${provider_type}`);\n }\n\n const templateType = promptTemplate.type as keyof typeof providerMap;\n const config = providerMap[templateType];\n\n if (!config) {\n throw new Error(\n `Unsupported template type '${promptTemplate.type}' for provider '${provider_type}'`\n );\n }\n\n return config;\n};\n\nconst vertexaiRequest = async (\n promptBlueprint: GetPromptTemplateResponse,\n kwargs: any\n) => {\n const model = promptBlueprint.metadata?.model;\n if (!model) throw new Error(\"Model metadata not found in prompt blueprint\");\n if (model.name.startsWith(\"gemini\"))\n return googleRequest(promptBlueprint, kwargs);\n if (model.name.startsWith(\"claude\")) {\n const { AnthropicVertex } = await import(\"@anthropic-ai/vertex-sdk\");\n const client = new AnthropicVertex({ baseURL: kwargs.baseURL });\n if (promptBlueprint.prompt_template.type === \"chat\")\n return anthropicChatRequest(client, kwargs);\n throw new Error(\n `Unsupported prompt template type '${promptBlueprint.prompt_template.type}' for Anthropic Vertex AI`\n );\n }\n throw new Error(\n `Unsupported model name '${model.name}' for Vertex AI request`\n );\n};\n\nconst anthropicBedrockRequest = async (\n promptBlueprint: GetPromptTemplateResponse,\n kwargs: any\n) => {\n const { AnthropicBedrock } = await import(\"@anthropic-ai/bedrock-sdk\");\n const client = new AnthropicBedrock({\n awsAccessKey: kwargs.aws_access_key,\n awsSecretKey: kwargs.aws_secret_key,\n awsRegion: kwargs.aws_region,\n awsSessionToken: kwargs.aws_session_token,\n baseURL: kwargs.base_url,\n });\n\n const requestToMake =\n MAP_TYPE_TO_ANTHROPIC_FUNCTION[promptBlueprint.prompt_template.type];\n return requestToMake(client, kwargs);\n};\n\nexport {\n anthropicBedrockRequest,\n anthropicRequest,\n anthropicStreamCompletion,\n anthropicStreamMessage,\n azureOpenAIRequest,\n configureProviderSettings,\n getAllPromptTemplates,\n getPromptTemplate,\n getProviderConfig,\n googleRequest,\n googleStreamChat,\n googleStreamCompletion,\n openaiRequest,\n openaiStreamChat,\n openaiStreamCompletion,\n promptlayerApiHandler,\n promptLayerApiRequest,\n promptLayerCreateGroup,\n promptLayerTrackGroup,\n promptLayerTrackMetadata,\n promptLayerTrackPrompt,\n promptLayerTrackScore,\n publishPromptTemplate,\n streamResponse,\n trackRequest,\n utilLogRequest,\n vertexaiRequest,\n};\n","const _buildToolCall = (id: string, name: string, input: any) => {\n return {\n id,\n function: {\n name,\n input,\n },\n };\n};\n\nconst _buildContentBlock = ({\n type,\n ...rest\n}: {\n type: string;\n [key: string]: any;\n}) => {\n return {\n type,\n ...rest,\n };\n};\n\nconst _buildAssistantMessage = (content: any[], tool_calls: any[]) => {\n return {\n input_variables: [],\n template_format: \"f-string\" as const,\n content: content,\n role: \"assistant\" as const,\n function_call: null,\n name: null,\n tool_calls: tool_calls,\n };\n};\n\nconst _buildPromptTemplate = (assistantMessage: any, metadata: any) => {\n const promptTemplate = {\n messages: [assistantMessage],\n type: \"chat\" as const,\n input_variables: [],\n };\n\n return {\n prompt_template: promptTemplate,\n metadata: metadata,\n };\n};\n\nexport const buildPromptBlueprintFromAnthropicEvent = (\n event: any,\n metadata: any\n) => {\n const assistantContent: any[] = [];\n const tool_calls: any[] = [];\n\n if (event.type === \"content_block_start\") {\n if (event.content_block.type === \"thinking\") {\n assistantContent.push(\n _buildContentBlock({\n type: \"thinking\",\n thinking: \"\",\n signature: \"\",\n })\n );\n } else if (event.content_block.type === \"text\") {\n assistantContent.push(\n _buildContentBlock({\n type: \"text\",\n text: \"\",\n })\n );\n } else if (event.content_block.type === \"tool_use\") {\n tool_calls.push(\n _buildToolCall(\n event.content_block.id || \"\",\n event.content_block.name || \"\",\n {}\n )\n );\n }\n } else if (event.type === \"content_block_delta\") {\n if (event.delta.type === \"thinking_delta\") {\n assistantContent.push(\n _buildContentBlock({\n type: \"thinking\",\n thinking: event.delta.thinking || \"\",\n signature: \"\",\n })\n );\n } else if (event.delta.type === \"text_delta\") {\n assistantContent.push(\n _buildContentBlock({\n type: \"text\",\n text: event.delta.text || \"\",\n })\n );\n } else if (event.delta.type === \"signature_delta\") {\n assistantContent.push(\n _buildContentBlock({\n type: \"thinking\",\n thinking: \"\",\n signature: event.delta.signature || \"\",\n })\n );\n } else if (event.delta.type === \"input_json_delta\") {\n tool_calls.push(_buildToolCall(\"\", \"\", event.delta.partial_json));\n }\n }\n\n const assistantMessage = _buildAssistantMessage(assistantContent, tool_calls);\n return _buildPromptTemplate(assistantMessage, metadata);\n};\n\nexport const buildPromptBlueprintFromGoogleEvent = (\n event: any,\n metadata: any\n) => {\n const assistantContent: any[] = [];\n const tool_calls: any[] = [];\n\n for (const candidate of event.candidates) {\n if (\n candidate.content &&\n candidate.content.parts &&\n Array.isArray(candidate.content.parts)\n ) {\n for (const part of candidate.content.parts) {\n if (part.text) {\n if (part.thought === true) {\n assistantContent.push(\n _buildContentBlock({\n type: \"thinking\",\n thinking: part.text,\n signature: part.thoughtSignature || \"\",\n })\n );\n } else {\n assistantContent.push(\n _buildContentBlock({\n type: \"text\",\n text: part.text,\n })\n );\n }\n } else if (part.functionCall) {\n tool_calls.push(\n _buildToolCall(\n part.functionCall.id || \"\",\n part.functionCall.name || \"\",\n part.functionCall.args || {}\n )\n );\n }\n }\n }\n }\n\n const assistantMessage = _buildAssistantMessage(assistantContent, tool_calls);\n return _buildPromptTemplate(assistantMessage, metadata);\n};\n\nexport const buildPromptBlueprintFromOpenAIEvent = (\n event: any,\n metadata: any\n) => {\n const assistantContent: any[] = [];\n const tool_calls: any[] = [];\n\n for (const choice of event.choices) {\n if (choice.delta) {\n if (choice.delta.content) {\n assistantContent.push(\n _buildContentBlock({\n type: \"text\",\n text: choice.delta.content,\n })\n );\n }\n\n if (choice.delta.tool_calls && Array.isArray(choice.delta.tool_calls)) {\n for (const toolCall of choice.delta.tool_calls) {\n if (toolCall.function) {\n tool_calls.push(\n _buildToolCall(\n toolCall.id || \"\",\n toolCall.function.name || \"\",\n toolCall.function.arguments || \"\"\n )\n );\n }\n }\n }\n }\n }\n\n const assistantMessage = _buildAssistantMessage(assistantContent, tool_calls);\n return _buildPromptTemplate(assistantMessage, metadata);\n};\n","import { promptLayerCreateGroup } from \"@/utils/utils\";\n\nexport class GroupManager {\n apiKey: string;\n\n constructor(apiKey: string) {\n this.apiKey = apiKey;\n }\n\n create = () => promptLayerCreateGroup(this.apiKey);\n}\n","import * as opentelemetry from '@opentelemetry/api';\nimport {SimpleSpanProcessor} from '@opentelemetry/sdk-trace-base';\nimport {NodeTracerProvider} from '@opentelemetry/sdk-trace-node';\nimport PromptLayerSpanExporter from '@/span-exporter';\n\nexport const getTracer = (name: string = 'promptlayer-tracer') => {\n return opentelemetry.trace.getTracer(name);\n}\n\nexport const setupTracing = (enableTracing: boolean, apiKey?: string) => {\n const provider = new NodeTracerProvider();\n const exporter = new PromptLayerSpanExporter(enableTracing, apiKey);\n const processor = new SimpleSpanProcessor(exporter);\n provider.addSpanProcessor(processor);\n provider.register();\n}\n","import { Attributes, SpanKind, SpanStatusCode } from \"@opentelemetry/api\";\nimport { ReadableSpan, SpanExporter } from \"@opentelemetry/sdk-trace-base\";\nimport { ExportResultCode } from \"@opentelemetry/core\";\nimport { URL_API_PROMPTLAYER } from \"@/utils/utils\";\n\nclass PromptLayerSpanExporter implements SpanExporter {\n private apiKey: string | undefined;\n private enableTracing: boolean;\n private url: string;\n\n constructor(enableTracing: boolean, apiKey?: string) {\n this.apiKey = apiKey || process.env.PROMPTLAYER_API_KEY;\n this.enableTracing = enableTracing;\n this.url = `${URL_API_PROMPTLAYER}/spans-bulk`;\n }\n\n private attributesToObject(\n attributes: Attributes | undefined\n ): Record<string, any> {\n if (!attributes) return {};\n return Object.fromEntries(Object.entries(attributes));\n }\n\n private spanKindToString(kind: SpanKind): string {\n const kindMap: Record<SpanKind, string> = {\n [SpanKind.INTERNAL]: \"SpanKind.INTERNAL\",\n [SpanKind.SERVER]: \"SpanKind.SERVER\",\n [SpanKind.CLIENT]: \"SpanKind.CLIENT\",\n [SpanKind.PRODUCER]: \"SpanKind.PRODUCER\",\n [SpanKind.CONSUMER]: \"SpanKind.CONSUMER\",\n };\n return kindMap[kind] || \"SpanKind.INTERNAL\";\n }\n\n private statusCodeToString(code: SpanStatusCode): string {\n const statusMap: Record<SpanStatusCode, string> = {\n [SpanStatusCode.ERROR]: \"StatusCode.ERROR\",\n [SpanStatusCode.OK]: \"StatusCode.OK\",\n [SpanStatusCode.UNSET]: \"StatusCode.UNSET\",\n };\n return statusMap[code] || \"StatusCode.UNSET\";\n }\n\n private toNanoseconds(time: [number, number]): string {\n return (BigInt(time[0]) * BigInt(1e9) + BigInt(time[1])).toString();\n }\n\n export(spans: ReadableSpan[]): Promise<ExportResultCode> {\n if (!this.enableTracing) {\n return Promise.resolve(ExportResultCode.SUCCESS);\n }\n\n const requestData = spans.map((span) => ({\n name: span.name,\n context: {\n trace_id: span.spanContext().traceId,\n span_id: span.spanContext().spanId,\n trace_state: span.spanContext().traceState?.serialize() || \"\",\n },\n kind: this.spanKindToString(span.kind),\n parent_id: span.parentSpanId || null,\n start_time: this.toNanoseconds(span.startTime),\n end_time: this.toNanoseconds(span.endTime),\n status: {\n status_code: this.statusCodeToString(span.status.code),\n description: span.status.message,\n },\n attributes: this.attributesToObject(span.attributes),\n events: span.events.map((event) => ({\n name: event.name,\n timestamp: this.toNanoseconds(event.time),\n attributes: this.attributesToObject(event.attributes),\n })),\n links: span.links.map((link) => ({\n context: link.context,\n attributes: this.attributesToObject(link.attributes),\n })),\n resource: {\n attributes: {\n ...span.resource.attributes,\n \"service.name\": \"prompt-layer-js\",\n },\n schema_url: \"\",\n },\n }));\n\n return fetch(this.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-API-KEY\": this.apiKey || \"\",\n },\n body: JSON.stringify({\n spans: requestData,\n }),\n })\n .then((response) => {\n if (!response.ok) {\n console.error(\n `Error exporting spans\\nHTTP error! status: ${response.status}`\n );\n return ExportResultCode.FAILED;\n }\n return ExportResultCode.SUCCESS;\n })\n .catch((error) => {\n console.error(\"Error exporting spans:\", error);\n return ExportResultCode.FAILED;\n });\n }\n\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nexport default PromptLayerSpanExporter;\n","import { getTracer } from \"@/tracing\";\nimport { promptlayerApiHandler } from \"@/utils/utils\";\n\nconst tracer = getTracer();\n\nexport const promptLayerBase = (\n apiKey: string,\n llm: object,\n function_name = \"\",\n provider = \"openai\"\n) => {\n const handler: ProxyHandler<any> = {\n construct: (target, args) => {\n const newTarget = Reflect.construct(target, args);\n Object.defineProperties(newTarget, {\n function_name: {\n value: function_name,\n writable: true,\n },\n provider: {\n value: provider,\n },\n });\n return new Proxy(newTarget, handler);\n },\n get: (target, prop, receiver) => {\n const value = target[prop];\n const function_name = `${Reflect.get(\n target,\n \"function_name\"\n )}.${prop.toString()}`;\n\n if (typeof value === \"object\") {\n Object.defineProperties(value, {\n function_name: {\n value: function_name,\n writable: true,\n },\n provider: {\n value: provider,\n },\n });\n return new Proxy(value, handler);\n }\n\n if (typeof value === \"function\") {\n return (...args: any[]) => {\n const request_start_time = new Date().toISOString();\n const provider_type = Reflect.get(target, \"provider\");\n const return_pl_id = args[0]?.return_pl_id;\n const pl_tags = args[0]?.pl_tags;\n delete args[0]?.return_pl_id;\n delete args[0]?.pl_tags;\n\n return tracer.startActiveSpan(\n `${provider_type}.${function_name}`,\n async (span: any) => {\n try {\n span.setAttribute(\"function_input\", JSON.stringify(args));\n const response = Reflect.apply(value, target, args);\n const spanId = span.spanContext().spanId;\n\n if (response instanceof Promise) {\n return new Promise((resolve, reject) => {\n response\n .then(async (request_response) => {\n const response = await promptlayerApiHandler(apiKey, {\n api_key: apiKey,\n provider_type,\n function_name,\n request_start_time,\n request_end_time: new Date().toISOString(),\n request_response,\n kwargs: args[0],\n return_pl_id,\n tags: pl_tags,\n span_id: spanId,\n });\n\n span.setAttribute(\n \"function_output\",\n JSON.stringify(response)\n );\n span.setAttribute(\"response_status\", \"success\");\n span.end();\n resolve(response);\n })\n .catch((error) => {\n span.recordException(error);\n span.setAttribute(\"response_status\", \"error\");\n span.end();\n reject(error);\n });\n });\n }\n\n span.setAttribute(\"function_output\", JSON.stringify(response));\n span.setAttribute(\"response_status\", \"success\");\n span.end();\n return response;\n } catch (error) {\n span.recordException(error);\n span.setAttribute(\"response_status\", \"error\");\n span.end();\n throw error;\n }\n }\n );\n };\n }\n\n return Reflect.get(target, prop, receiver);\n },\n };\n\n return new Proxy(llm, handler);\n};\n","import * as opentelemetry from '@opentelemetry/api';\nimport { getTracer } from '@/tracing';\n\nexport const wrapWithSpan = (functionName: string, func: Function, attributes?: Record<string, any>) => {\n return function (...args: any[]) {\n const tracer = getTracer();\n\n const wrapperFunction = (span: opentelemetry.Span) => {\n try {\n if (attributes) {\n Object.entries(attributes).forEach(([key, value]) => {\n span.setAttribute(key, value);\n });\n }\n\n span.setAttribute('function_input', JSON.stringify(args));\n const result = func(...args);\n\n if (result instanceof Promise) {\n return result.then((resolvedResult) => {\n span.setAttribute('function_output', JSON.stringify(resolvedResult));\n span.setStatus({ code: opentelemetry.SpanStatusCode.OK });\n return resolvedResult;\n }).catch((error) => {\n handleError(span, error, args);\n throw error;\n }).finally(() => span.end());\n } else {\n span.setAttribute('function_output', JSON.stringify(result));\n span.setStatus({ code: opentelemetry.SpanStatusCode.OK });\n span.end();\n return result;\n }\n } catch (error) {\n handleError(span, error, args);\n throw error;\n }\n };\n\n return tracer.startActiveSpan(functionName, wrapperFunction);\n };\n};\n\nconst handleError = (span: opentelemetry.Span, error: any, args: any[]) => {\n span.setAttribute('function_input', JSON.stringify(args));\n span.setStatus({\n code: opentelemetry.SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n span.end();\n}\n","import {\n GetPromptTemplateParams,\n Pagination,\n PublishPromptTemplate,\n} from \"@/types\";\nimport {\n getAllPromptTemplates,\n getPromptTemplate,\n publishPromptTemplate,\n} from \"@/utils/utils\";\n\nexport class TemplateManager {\n apiKey: string;\n\n constructor(apiKey: string) {\n this.apiKey = apiKey;\n }\n\n get = (promptName: string, params?: Partial<GetPromptTemplateParams>) =>\n getPromptTemplate(this.apiKey, promptName, params);\n\n publish = (body: PublishPromptTemplate) =>\n publishPromptTemplate(this.apiKey, body);\n\n all = (params?: Pagination) => getAllPromptTemplates(this.apiKey, params);\n}\n","import { TrackGroup, TrackMetadata, TrackPrompt, TrackScore } from \"@/types\";\nimport {\n promptLayerTrackGroup,\n promptLayerTrackMetadata,\n promptLayerTrackPrompt,\n promptLayerTrackScore,\n} from \"@/utils/utils\";\n\nconst metadata = (apiKey: string, body: TrackMetadata): Promise<boolean> => {\n if (!(body.metadata instanceof Object)) {\n throw new Error(\"Please provide a dictionary of metadata.\");\n }\n for (const [key, value] of Object.entries(body.metadata)) {\n if (typeof key !== \"string\" || typeof value !== \"string\") {\n throw new Error(\n \"Please provide a dictionary of metadata with key value pair of strings.\"\n );\n }\n }\n return promptLayerTrackMetadata(apiKey, body);\n};\n\nconst score = (apiKey: string, body: TrackScore): Promise<boolean> => {\n if (typeof body.score !== \"number\") {\n throw new Error(\"Score must be a number\");\n }\n if (body.score < 0 || body.score > 100) {\n throw new Error(\"Score must be a number between 0 and 100.\");\n }\n return promptLayerTrackScore(apiKey, body);\n};\n\nconst prompt = (apiKey: string, body: TrackPrompt): Promise<boolean> => {\n if (!(body.prompt_input_variables instanceof Object)) {\n throw new Error(\"Prompt template input variable dictionary not provided.\");\n }\n return promptLayerTrackPrompt(apiKey, body);\n};\n\nconst group = (apiKey: string, body: TrackGroup) =>\n promptLayerTrackGroup(apiKey, body);\n\nexport class TrackManager {\n apiKey: string;\n\n constructor(apiKey: string) {\n this.apiKey = apiKey;\n }\n\n group = (body: TrackGroup) => group(this.apiKey, body);\n\n metadata = (body: TrackMetadata) => metadata(this.apiKey, body);\n\n prompt = (body: TrackPrompt) => prompt(this.apiKey, body);\n\n score = (body: TrackScore) => score(this.apiKey, body);\n}\n","import { GroupManager } from \"@/groups\";\nimport { promptLayerBase } from \"@/promptlayer\";\nimport { wrapWithSpan } from \"@/span-wrapper\";\nimport { TemplateManager } from \"@/templates\";\nimport { getTracer, setupTracing } from \"@/tracing\";\nimport { TrackManager } from \"@/track\";\nimport {\n GetPromptTemplateParams,\n LogRequest,\n RunRequest,\n WorkflowRequest,\n WorkflowResponse,\n} from \"@/types\";\nimport {\n anthropicBedrockRequest,\n anthropicRequest,\n azureOpenAIRequest,\n configureProviderSettings,\n getProviderConfig,\n googleRequest,\n openaiRequest,\n runWorkflowRequest,\n streamResponse,\n trackRequest,\n utilLogRequest,\n vertexaiRequest,\n} from \"@/utils/utils\";\nimport * as opentelemetry from \"@opentelemetry/api\";\n\nconst MAP_PROVIDER_TO_FUNCTION: Record<string, any> = {\n openai: openaiRequest,\n anthropic: anthropicRequest,\n \"openai.azure\": azureOpenAIRequest,\n google: googleRequest,\n vertexai: vertexaiRequest,\n \"anthropic.bedrock\": anthropicBedrockRequest,\n};\n\nexport interface ClientOptions {\n apiKey?: string;\n enableTracing?: boolean;\n workspaceId?: number;\n}\n\nconst isWorkflowResultsDict = (obj: any): boolean => {\n if (!obj || typeof obj !== \"object\" || Array.isArray(obj)) {\n return false;\n }\n\n const REQUIRED_KEYS = [\n \"status\",\n \"value\",\n \"error_message\",\n \"raw_error_message\",\n \"is_output_node\",\n ];\n const values = Object.values(obj);\n\n return values.every((val) => {\n if (typeof val !== \"object\" || val === null) return false;\n return REQUIRED_KEYS.every((key) => key in val);\n });\n};\n\nexport class PromptLayer {\n apiKey: string;\n templates: TemplateManager;\n group: GroupManager;\n track: TrackManager;\n enableTracing: boolean;\n wrapWithSpan: typeof wrapWithSpan;\n\n constructor({\n apiKey = process.env.PROMPTLAYER_API_KEY,\n enableTracing = false,\n }: ClientOptions = {}) {\n if (apiKey === undefined) {\n throw new Error(\n \"PromptLayer API key not provided. Please set the PROMPTLAYER_API_KEY environment variable or pass the api_key parameter.\"\n );\n }\n\n this.apiKey = apiKey;\n this.enableTracing = enableTracing;\n this.templates = new TemplateManager(apiKey);\n this.group = new GroupManager(apiKey);\n this.track = new TrackManager(apiKey);\n this.wrapWithSpan = wrapWithSpan;\n\n if (enableTracing) {\n setupTracing(enableTracing, apiKey);\n }\n }\n\n get Anthropic() {\n try {\n const module = require(\"@anthropic-ai/sdk\").default;\n return promptLayerBase(this.apiKey, module, \"anthropic\", \"anthropic\");\n } catch (e) {\n console.error(\n \"To use the Anthropic module, you must install the @anthropic-ai/sdk package.\"\n );\n }\n }\n\n get OpenAI() {\n try {\n const module = require(\"openai\").default;\n return promptLayerBase(this.apiKey, module, \"openai\", \"openai\");\n } catch (e) {\n console.error(\n \"To use the OpenAI module, you must install the @openai/api package.\"\n );\n }\n }\n\n async run({\n promptName,\n promptVersion,\n promptReleaseLabel,\n inputVariables,\n tags,\n metadata,\n groupId,\n modelParameterOverrides,\n stream = false,\n provider,\n model,\n }: RunRequest) {\n const tracer = getTracer();\n\n return tracer.startActiveSpan(\"PromptLayer Run\", async (span) => {\n try {\n const functionInput = {\n promptName,\n promptVersion,\n promptReleaseLabel,\n inputVariables,\n tags,\n metadata,\n groupId,\n modelParameterOverrides,\n stream,\n };\n span.setAttribute(\"function_input\", JSON.stringify(functionInput));\n\n const prompt_input_variables = inputVariables;\n const templateGetParams: GetPromptTemplateParams = {\n label: promptReleaseLabel,\n version: promptVersion,\n metadata_filters: metadata,\n provider,\n model,\n };\n if (inputVariables) templateGetParams.input_variables = inputVariables;\n\n const promptBlueprint = await this.templates.get(\n promptName,\n templateGetParams\n );\n\n if (!promptBlueprint) throw new Error(\"Prompt not found\");\n\n const promptTemplate = promptBlueprint.prompt_template;\n if (!promptBlueprint.llm_kwargs) {\n console.warn(\n `Prompt '${promptName}' does not have any LLM kwargs associated with it. Please set your model parameters in the registry in the PromptLayer dashbaord.`\n );\n }\n\n const promptBlueprintMetadata = promptBlueprint.metadata;\n if (!promptBlueprintMetadata) {\n throw new Error(\n `Prompt '${promptName}' does not have any metadata associated with it.`\n );\n }\n\n const promptBlueprintModel = promptBlueprintMetadata.model;\n if (!promptBlueprintModel) {\n throw new Error(\n `Prompt '${promptName}' does not have a model parameters associated with it.`\n );\n }\n\n const customProvider = promptBlueprint.custom_provider;\n const request_start_time = new Date().toISOString();\n\n const { provider_type, kwargs } = configureProviderSettings(\n promptBlueprint,\n customProvider,\n modelParameterOverrides,\n stream\n );\n\n let provider_type_config = provider_type;\n if (promptBlueprintModel.name.startsWith(\"gemini\")) {\n provider_type_config = \"google\";\n } else if (promptBlueprintModel.name.startsWith(\"claude\")) {\n provider_type_config = \"anthropic\";\n }\n\n const config = getProviderConfig(provider_type_config, promptTemplate);\n const { function_name, stream_function } = config;\n\n const request_function = MAP_PROVIDER_TO_FUNCTION[provider_type];\n if (!request_function) {\n throw new Error(\n `No request function found for provider: ${provider_type}`\n );\n }\n\n const response = await request_function(promptBlueprint, kwargs);\n\n const _trackRequest = (body: object) => {\n const request_end_time = new Date().toISOString();\n return trackRequest({\n function_name,\n provider_type,\n args: [],\n kwargs,\n tags,\n request_start_time,\n request_end_time,\n api_key: this.apiKey,\n metadata,\n prompt_id: promptBlueprint.id,\n prompt_version: promptBlueprint.version,\n prompt_input_variables,\n group_id: groupId,\n return_prompt_blueprint: true,\n span_id: span.spanContext().spanId,\n ...body,\n });\n };\n\n if (stream)\n return streamResponse(\n response,\n _trackRequest,\n stream_function,\n metadata\n );\n const requestLog = await _trackRequest({ request_response: response });\n\n const functionOutput = {\n request_id: requestLog.request_id,\n raw_response: response,\n prompt_blueprint: requestLog.prompt_blueprint,\n };\n span.setAttribute(\"function_output\", JSON.stringify(functionOutput));\n\n return functionOutput;\n } catch (error) {\n span.setStatus({\n code: opentelemetry.SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : \"Unknown error\",\n });\n throw error;\n } finally {\n span.end();\n }\n });\n }\n\n async runWorkflow({\n workflowName,\n inputVariables = {},\n metadata = {},\n workflowLabelName = null,\n workflowVersion = null, // This is the version number, not the version ID\n returnAllOutputs = false,\n }: WorkflowRequest): Promise<WorkflowResponse> {\n try {\n const result = await runWorkflowRequest({\n workflow_name: workflowName,\n input_variables: inputVariables,\n metadata,\n workflow_label_name: workflowLabelName,\n workflow_version_number: workflowVersion,\n return_all_outputs: returnAllOutputs,\n api_key: this.apiKey,\n });\n\n if (!returnAllOutputs) {\n if (isWorkflowResultsDict(result)) {\n const nodeValues = Object.values(result);\n\n const outputNodes = nodeValues.filter(\n (node: any) => node.is_output_node === true\n );\n\n if (outputNodes.length === 0) {\n throw new Error(JSON.stringify(result, null, 2));\n }\n\n const anyOutputSuccess = outputNodes.some(\n (node: any) => node.status === \"SUCCESS\"\n );\n if (!anyOutputSuccess) {\n throw new Error(JSON.stringify(result, null, 2));\n }\n }\n }\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n console.error(\"Error running workflow:\", error.message);\n throw new Error(`Error running workflow: ${error.message}`);\n } else {\n console.error(\"Unknown error running workflow:\", error);\n throw new Error(\"Unknown error running workflow\");\n }\n }\n }\n\n async logRequest(body: LogRequest) {\n return utilLogRequest(this.apiKey, body);\n }\n}\n"],"mappings":"6yDAyBA,OAAOA,OAAU,OCzBjB,IAAMC,EAAiB,CAACC,EAAYC,EAAcC,KACzC,CACL,GAAAF,EACA,SAAU,CACR,KAAAC,EACA,MAAAC,CACF,CACF,GAGIC,EAAsBC,GAMtB,CANsB,IAAAC,EAAAD,EAC1B,MAAAE,CAXF,EAU4BD,EAEvBE,EAAAC,EAFuBH,EAEvB,CADH,SAMA,OAAOI,EAAA,CACL,KAAAH,GACGC,EAEP,EAEMG,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ACnC,QAAS4B,aAAiB,MAAQA,EAAM,QAAU,eACpD,CAAC,EACKA,CACR,QAAE,CACA5B,EAAK,IAAI,CACX,CACF,EAAC,CACH,GAEM,YAAYd,EAO6B,QAAAC,EAAA,yBAP7B,CAChB,aAAA0C,EACA,eAAAtC,EAAiB,CAAC,EAClB,SAAAE,EAAW,CAAC,EACZ,kBAAAqC,EAAoB,KACpB,gBAAAC,EAAkB,KAClB,iBAAAC,EAAmB,EACrB,EAA+C,CAC7C,GAAI,CACF,IAAMC,EAAS,MAAMC,GAAmB,CACtC,cAAeL,EACf,gBAAiBtC,EACjB,SAAAE,EACA,oBAAqBqC,EACrB,wBAAyBC,EACzB,mBAAoBC,EACpB,QAAS,KAAK,MAChB,CAAC,EAED,GAAI,CAACA,GACC7D,GAAsB8D,CAAM,EAAG,CAGjC,IAAME,EAFa,OAAO,OAAOF,CAAM,EAER,OAC5BG,GAAcA,EAAK,iBAAmB,EACzC,EAEA,GAAID,EAAY,SAAW,EACzB,MAAM,IAAI,MAAM,KAAK,UAAUF,EAAQ,KAAM,CAAC,CAAC,EAMjD,GAAI,CAHqBE,EAAY,KAClCC,GAAcA,EAAK,SAAW,SACjC,EAEE,MAAM,IAAI,MAAM,KAAK,UAAUH,EAAQ,KAAM,CAAC,CAAC,CAEnD,CAGF,OAAOA,CACT,OAASL,EAAO,CACd,MAAIA,aAAiB,OACnB,QAAQ,MAAM,0BAA2BA,EAAM,OAAO,EAChD,IAAI,MAAM,2BAA2BA,EAAM,OAAO,EAAE,IAE1D,QAAQ,MAAM,kCAAmCA,CAAK,EAChD,IAAI,MAAM,gCAAgC,EAEpD,CACF,GAEM,WAAWP,EAAkB,QAAAlC,EAAA,sBACjC,OAAOkD,GAAe,KAAK,OAAQhB,CAAI,CACzC,GACF","names":["Ably","_buildToolCall","id","name","input","_buildContentBlock","_a","_b","type","rest","__objRest","__spreadValues","_buildAssistantMessage","content","tool_calls","_buildPromptTemplate","assistantMessage","metadata","buildPromptBlueprintFromAnthropicEvent","event","assistantContent","buildPromptBlueprintFromGoogleEvent","candidate","part","buildPromptBlueprintFromOpenAIEvent","choice","toolCall","SET_WORKFLOW_COMPLETE_MESSAGE","getFinalOutput","executionId","returnAllOutputs","headers","__async","response","URL_API_PROMPTLAYER","makeMessageListener","resultsPromise","message","SET_WORKFLOW_COMPLETE_MESSAGE","data","resultCode","results","err","waitForWorkflowCompletion","_0","token","channelName","timeout","client","Ably","channel","promise","resolve","reject","listener","timer","result","promptlayerApiHandler","apiKey","body","proxyGenerator","promptLayerApiRequest","warnOnBadResponse","e","promptLayerTrackMetadata","__spreadProps","__spreadValues","promptLayerTrackScore","promptLayerTrackPrompt","promptLayerTrackGroup","promptLayerCreateGroup","getPromptTemplate","promptName","params","url","publishPromptTemplate","getAllPromptTemplates","_a","key","value","runWorkflowRequest","workflow_name","input_variables","metadata","workflow_label_name","workflow_version_number","return_all_outputs","api_key","payload","execution_id","channel_name","ably_token","error","openaiStreamChat","_b","_c","_d","_e","_f","_g","_h","_i","_j","content","functionCall","lastResult","toolCalls","delta","toolCall","lastToolCall","firstChoice","anthropicStreamMessage","currentBlock","currentSignature","currentThinking","currentText","currentToolInputJson","event","inputJsonDelta","cleaned_result","function_name","prev","current","final_result","generator","__asyncGenerator","iter","__forAwait","more","temp","__await","request_response","request_id","main_message","trackRequest","openaiStreamCompletion","text","anthropicStreamCompletion","completion","streamResponse","afterStream","mapResults","buildPromptBlueprintFromAnthropicEvent","buildPromptBlueprintFromGoogleEvent","buildPromptBlueprintFromOpenAIEvent","openaiChatRequest","kwargs","openaiCompletionsRequest","MAP_TYPE_TO_OPENAI_FUNCTION","openaiRequest","promptBlueprint","OpenAI","requestToMake","azureOpenAIRequest","AzureOpenAI","anthropicChatRequest","anthropicCompletionsRequest","MAP_TYPE_TO_ANTHROPIC_FUNCTION","anthropicRequest","Anthropic","utilLogRequest","buildGoogleResponseFromParts","thoughtContent","regularContent","functionCalls","finalParts","thoughtPart","textPart","functionPart","googleStreamResponse","GenerateContentResponse","part","googleStreamChat","googleStreamCompletion","googleChatRequest","model_client","history","generationConfig","lastMessage","chat","googleCompletionsRequest","stream","__objRest","MAP_TYPE_TO_GOOGLE_FUNCTION","googleRequest","GoogleGenAI","geminiAPI","project","location","googleAuthOptions","genAI","snakeToCamel","str","_","letter","convertKeysToCamelCase","obj","ignoreValuesWithKeys","item","STREAMING_PROVIDERS_WITH_USAGE","MAP_PROVIDER_TO_FUNCTION_NAME","configureProviderSettings","customProvider","modelParameterOverrides","provider_type","providerConfig","getProviderConfig","promptTemplate","providerMap","templateType","config","vertexaiRequest","model","AnthropicVertex","anthropicBedrockRequest","AnthropicBedrock","GroupManager","apiKey","promptLayerCreateGroup","opentelemetry","SimpleSpanProcessor","NodeTracerProvider","SpanKind","SpanStatusCode","ExportResultCode","PromptLayerSpanExporter","enableTracing","apiKey","URL_API_PROMPTLAYER","attributes","kind","SpanKind","code","SpanStatusCode","time","spans","ExportResultCode","requestData","span","_a","event","link","__spreadProps","__spreadValues","response","error","span_exporter_default","getTracer","name","setupTracing","enableTracing","apiKey","provider","NodeTracerProvider","exporter","span_exporter_default","processor","SimpleSpanProcessor","tracer","getTracer","promptLayerBase","apiKey","llm","function_name","provider","handler","target","args","newTarget","prop","receiver","value","_a","_b","_c","_d","request_start_time","provider_type","return_pl_id","pl_tags","span","__async","response","spanId","resolve","reject","request_response","promptlayerApiHandler","error","opentelemetry","wrapWithSpan","functionName","func","attributes","args","tracer","getTracer","wrapperFunction","span","key","value","result","resolvedResult","error","handleError","TemplateManager","apiKey","promptName","params","getPromptTemplate","body","publishPromptTemplate","getAllPromptTemplates","metadata","apiKey","body","key","value","promptLayerTrackMetadata","score","promptLayerTrackScore","prompt","promptLayerTrackPrompt","group","promptLayerTrackGroup","TrackManager","opentelemetry","MAP_PROVIDER_TO_FUNCTION","openaiRequest","anthropicRequest","azureOpenAIRequest","googleRequest","vertexaiRequest","anthropicBedrockRequest","isWorkflowResultsDict","obj","REQUIRED_KEYS","val","key","PromptLayer","apiKey","enableTracing","TemplateManager","GroupManager","TrackManager","wrapWithSpan","setupTracing","module","promptLayerBase","_0","__async","promptName","promptVersion","promptReleaseLabel","inputVariables","tags","metadata","groupId","modelParameterOverrides","stream","provider","model","getTracer","span","functionInput","prompt_input_variables","templateGetParams","promptBlueprint","promptTemplate","promptBlueprintMetadata","promptBlueprintModel","customProvider","request_start_time","provider_type","kwargs","configureProviderSettings","provider_type_config","config","getProviderConfig","function_name","stream_function","request_function","response","_trackRequest","body","request_end_time","trackRequest","__spreadValues","streamResponse","requestLog","functionOutput","error","workflowName","workflowLabelName","workflowVersion","returnAllOutputs","result","runWorkflowRequest","outputNodes","node","utilLogRequest"]}
|