openlit 1.3.0 → 1.4.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,9 @@
1
1
  <div align="center">
2
- <img src="https://github.com/openlit/.github/blob/main/profile/assets/wide-logo-no-bg.png?raw=true" alt="OpenLIT Logo" width="30%"><h1>
3
- OpenTelemetry Auto-Instrumentation for GenAI & LLM Applications</h1>
2
+ <img src="https://github.com/openlit/.github/blob/main/profile/assets/wide-logo-no-bg.png?raw=true" alt="OpenLIT Logo" width="30%">
3
+ <h3>OpenTelemetry-native</h3>
4
+ <h1>AI Observability, Monitoring and Evaluation Framework</h1>
4
5
 
5
- **[Documentation](https://docs.openlit.io/) | [Quickstart](#-getting-started) | [Typescript SDK](https://github.com/openlit/openlit/tree/main/sdk/typescript)**
6
+ **[Documentation](https://docs.openlit.io/) | [Quickstart](#-getting-started-with-llm-observability) | [Roadmap](#️-roadmap) | [Feature Request](https://github.com/openlit/openlit/issues/new?assignees=&labels=%3Araised_hand%3A+Up+for+Grabs%2C+%3Arocket%3A+Feature&projects=&template=feature-request.md&title=%5BFeat%5D%3A) | [Report a Bug](https://github.com/openlit/openlit/issues/new?assignees=&labels=%3Abug%3A+Bug%2C+%3Araised_hand%3A+Up+for+Grabs&projects=&template=bug.md&title=%5BBug%5D%3A)**
6
7
 
7
8
  [![OpenLIT](https://img.shields.io/badge/OpenLIT-orange)](https://github.com/openlit/openlit)
8
9
  [![License](https://img.shields.io/github/license/openlit/openlit?label=License&logo=github&color=f80&logoColor=white)](https://github.com/openlit/openlit/blob/main/LICENSE)
@@ -11,18 +12,23 @@ OpenTelemetry Auto-Instrumentation for GenAI & LLM Applications</h1>
11
12
  [![GitHub Contributors](https://img.shields.io/github/contributors/openlit/openlit)](https://github.com/openlit/openlit/graphs/contributors)
12
13
 
13
14
  [![Slack](https://img.shields.io/badge/Slack-4A154B?logo=slack&logoColor=white)](https://join.slack.com/t/openlit/shared_invite/zt-2etnfttwg-TjP_7BZXfYg84oAukY8QRQ)
14
- [![Discord](https://img.shields.io/badge/Discord-7289DA?logo=discord&logoColor=white)](https://discord.gg/CQnXwNT3)
15
15
  [![X](https://img.shields.io/badge/follow-%40openlit__io-1DA1F2?logo=x&style=social)](https://twitter.com/openlit_io)
16
16
 
17
- ![OpenLIT Connections Banner](https://github.com/openlit/.github/blob/main/profile/assets/github-readme-connections-banner.png?raw=true)
17
+ ![OpenLIT Connections Banner](https://github.com/openlit/.github/blob/main/profile/assets/openlit-integrations-banner.png?raw=true)
18
18
 
19
19
  </div>
20
20
 
21
- OpenLIT Typescript SDK is an **OpenTelemetry-native** Auto instrumentation library for monitoring LLM Applications, facilitating the integration of observability into your GenAI-driven projects. Designed with simplicity and efficiency, OpenLIT offers the ability to embed observability into your GenAI-driven projects effortlessly using just **a single line of code**.
21
+ OpenLIT SDK is a monitoring framework built on top of **OpenTelemetry** that gives your complete Observability for your AI stack, from LLMs to vector databases, with just one line of code with tracing and metrics. It also allows you to send the generated traces and metrics to your existing monitoring tools like Grafana, New Relic, and more.
22
22
 
23
- Whether you're directly using LLM Libraries like OpenAI or Anthropic, OpenLIT seamlessly integrates observability into your applications, ensuring enhanced performance and reliability across diverse scenarios.
23
+ This project proudly follows and maintains the [Semantic Conventions](https://github.com/open-telemetry/semantic-conventions/tree/main/docs/gen-ai) with the OpenTelemetry community, consistently updating to align with the latest standards in Observability.
24
+
25
+ ## ⚡ Features
26
+
27
+ - 🔎 **Auto Instrumentation**: Works with 30+ LLM providers and vector databases with just one line of code.
28
+ - 🔭 **OpenTelemetry-Native Observability SDKs**: Vendor-neutral SDKs that can send traces and metrics to your existing observability tool like Prometheus and Jaeger.
29
+ - 💲 **Cost Tracking for Custom and Fine-Tuned Models**: Pass custom pricing files for accurate budgeting of custom and fine-tuned models.
30
+ - 🚀 **Suppport for OpenLIT Features**: Includes suppprt for prompt management and secrets management features available in OpenLIT.
24
31
 
25
- This project adheres to the [Semantic Conventions](https://github.com/open-telemetry/semantic-conventions/tree/main/docs/gen-ai) proposed by the OpenTelemetry community. You can check out the current definitions [here](src/semantic-convention.ts).
26
32
 
27
33
  ## Auto Instrumentation Capabilities
28
34
 
@@ -30,6 +36,7 @@ This project adheres to the [Semantic Conventions](https://github.com/open-telem
30
36
  | --------------------------------------------------------------------- |
31
37
  | [✅ OpenAI](https://docs.openlit.io/latest/integrations/openai) | [✅ ChromaDB](https://docs.openlit.io/latest/integrations/chromadb) | [✅ LiteLLM](https://docs.openlit.io/latest/integrations/litellm) | |
32
38
  | [✅ Anthropic](https://docs.openlit.io/latest/integrations/anthropic) |
39
+ | [✅ Cohere](https://docs.openlit.io/latest/integrations/cohere) |
33
40
 
34
41
  ## Supported Destinations
35
42
 
@@ -65,7 +72,7 @@ npm install openlit
65
72
 
66
73
  ### Step 2: Initialize OpenLIT in your Application
67
74
 
68
- Integrating the OpenLIT into LLM applications is straightforward. Start monitoring for your LLM Application with just **two lines of code**:
75
+ Integrate OpenLIT into your AI applications by adding the following lines to your code.
69
76
 
70
77
  ```typescript
71
78
  import Openlit from 'openlit';
@@ -73,11 +80,14 @@ import Openlit from 'openlit';
73
80
  Openlit.init();
74
81
  ```
75
82
 
76
- To forward telemetry data to an HTTP OTLP endpoint, such as the OpenTelemetry Collector, set the `otlpEndpoint` parameter with the desired endpoint. Alternatively, you can configure the endpoint by setting the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable as recommended in the OpenTelemetry documentation.
83
+ Configure the telemetry data destination as follows:
77
84
 
78
- > 💡 Info: If you dont provide `otlpEndpoint` function argument or set the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable, OpenLIT directs the trace directly to your console, which can be useful during development.
85
+ | Purpose | Parameter/Environment Variable | For Sending to OpenLIT |
86
+ |-------------------------------------------|--------------------------------------------------|--------------------------------|
87
+ | Send data to an HTTP OTLP endpoint | `otlpEndpoint` or `OTEL_EXPORTER_OTLP_ENDPOINT` | `"http://127.0.0.1:4318"` |
88
+ | Authenticate telemetry backends | `otlpHeaders` or `OTEL_EXPORTER_OTLP_HEADERS` | Not required by default |
79
89
 
80
- To send telemetry to OpenTelemetry backends requiring authentication, set the `otlpHeaders` parameter with its desired value. Alternatively, you can configure the endpoint by setting the `OTEL_EXPORTER_OTLP_HEADERS` environment variable as recommended in the OpenTelemetry documentation.
90
+ > 💡 Info: If the `otlp_endpoint` or `OTEL_EXPORTER_OTLP_ENDPOINT` is not provided, the OpenLIT SDK will output traces directly to your console, which is recommended during the development phase.
81
91
 
82
92
  #### Example
83
93
 
@@ -129,16 +139,17 @@ export OTEL_EXPORTER_OTLP_HEADERS = "YOUR_OTEL_ENDPOINT_AUTH"
129
139
  ---
130
140
 
131
141
  ### Step 3: Visualize and Optimize!
142
+ Now that your LLM observability data is being collected and sent to configured OpenTelemetry destination, the next step is to visualize and analyze this data. This will help you understand your LLM application's performance and behavior and identify where it can be improved.
132
143
 
133
- With the LLM Observability data now being collected and sent to OpenLIT, the next step is to visualize and analyze this data to get insights into your LLM application’s performance, behavior, and identify areas of improvement.
144
+ If you want to use OpenLIT's Observability Dashboard to monitor LLM usage—like cost, tokens, and user interactions—please check out our [Quickstart Guide](https://docs.openlit.io/latest/quickstart).
134
145
 
135
- To begin exploring your LLM Application's performance data within the OpenLIT, please see the [Quickstart Guide](https://docs.openlit.io/latest/quickstart).
136
-
137
- If you want to integrate and send metrics and traces to your existing observability tools, refer to our [Connections Guide](https://docs.openlit.io/latest/connections/intro) for detailed instructions.
146
+ If you're sending metrics and traces to other observability tools, take a look at our [Connections Guide](https://docs.openlit.io/latest/connections/intro) to start using a pre-built dashboard we have created for these tools.
138
147
 
139
148
  ![](https://github.com/openlit/.github/blob/main/profile/assets/openlit-client-1.png?raw=true)
140
149
 
141
- ### Configuration
150
+ ## Configuration
151
+
152
+ ### Observability - `Openlit.init()`
142
153
 
143
154
  Below is a detailed overview of the configuration options available, allowing you to adjust OpenLIT's behavior and functionality to align with your specific observability needs:
144
155
 
@@ -155,6 +166,36 @@ Below is a detailed overview of the configuration options available, allowing yo
155
166
  | `instrumentations` | Object of instrumentation modules for manual patching | `undefined` | No |
156
167
  | `pricing_json` | URL or file path of the pricing JSON file. | `https://github.com/openlit/openlit/blob/main/assets/pricing.json` | No |
157
168
 
169
+ ### OpenLIT Prompt Hub - `Openlit.getPrompt()`
170
+
171
+ Below are the parameters for use with the SDK for OpenLIT Prompt Hub for prompt management:
172
+
173
+ | Parameter | Description |
174
+ |------------------|------------------------------------------------------------------------------------------------------------------------------------|
175
+ | `url` | Sets the OpenLIT URL. Defaults to the `OPENLIT_URL` environment variable or `http://127.0.0.1:3000` if not set. |
176
+ | `apiKey` | Sets the OpenLIT API Key. Can also be provided via the `OPENLIT_API_KEY` environment variable. |
177
+ | `name` | Sets the name to fetch a unique prompt. Use this or `promptId`. |
178
+ | `promptId` | Sets the ID to fetch a unique prompt. Use this or `name`. Optional |
179
+ | `version` | Sets the version to retrieve a specific prompt. Optional |
180
+ | `shouldCompile` | Boolean value that compiles the prompt using the provided variables. Optional |
181
+ | `variables` | Sets the variables for prompt compilation. Optional |
182
+ | `metaProperties` | Sets the meta-properties for storing in the prompt's access history metadata. |
183
+
184
+
185
+ ### OpenLIT Vault - `Openlit.getSecrets()`
186
+
187
+ Below are the parameters for use with the SDK for OpenLIT Vault for secret management:
188
+
189
+ | Parameter | Description |
190
+ |------------------|------------------------------------------------------------------------------------------------------------------------------------|
191
+ | `url` | Sets the Openlit URL. Defaults to the `OPENLIT_URL` environment variable or `http://127.0.0.1:3000` if not set. |
192
+ | `apiKey` | Sets the OpenLIT API Key. Can also be provided via the `OPENLIT_API_KEY` environment variable. |
193
+ | `key` | Sets the key to fetch a specific secret. Optional |
194
+ | `tags` | Sets the tags for fetching only the secrets that have the mentioned tags assigned. Optional |
195
+ | `shouldSetEnv` | Boolean value that sets all the secrets as environment variables for the application. Optional |
196
+
197
+
198
+
158
199
  ## 🌱 Contributing
159
200
 
160
201
  Whether it's big or small, we love contributions 💚. Check out our [Contribution guide](../../CONTRIBUTING.md) to get started
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openlit",
3
- "version": "1.3.0",
3
+ "version": "1.4.0-beta.1",
4
4
  "homepage": "https://github.com/openlit/openlit#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/openlit/openlit/issues",
@@ -10,8 +10,21 @@
10
10
  "type": "git",
11
11
  "url": "https://github.com/openlit/openlit"
12
12
  },
13
+ "scripts": {
14
+ "build": "tsc --build"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE",
20
+ "package.json",
21
+ "tsconfig.json",
22
+ "eslint.config.mjs",
23
+ ".prettierrc.json"
24
+ ],
13
25
  "description": "OpenTelemetry-native Auto instrumentation library for monitoring LLM Applications, facilitating the integration of observability into your GenAI-driven projects",
14
- "main": "src/index.ts",
26
+ "main": "dist/index.js",
27
+ "types": "dist/index.d.ts",
15
28
  "keywords": [
16
29
  "OpenTelemetry",
17
30
  "otel",
package/tsconfig.json CHANGED
@@ -1,15 +1,22 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "target": "es2016",
4
- "module": "commonjs",
5
- "resolveJsonModule": true,
6
- "outDir": "./dist",
7
- "esModuleInterop": true,
8
- "forceConsistentCasingInFileNames": true,
9
- "paths": {
10
- "@/*": ["./src/*"]
11
- },
12
- "strict": true,
13
- "skipLibCheck": true
14
- }
3
+ "target": "ES2020",
4
+ "module": "CommonJS",
5
+ "outDir": "./dist",
6
+ "strict": true,
7
+ "esModuleInterop": true,
8
+ "declaration": true,
9
+ "skipLibCheck": true,
10
+ "sourceMap": true,
11
+ "forceConsistentCasingInFileNames": true,
12
+ "baseUrl": "./src",
13
+ "rootDir": "./src",
14
+ },
15
+ "include": [
16
+ "src/**/*"
17
+ ],
18
+ "exclude": [
19
+ "node_modules",
20
+ "**/*.spec.ts"
21
+ ]
15
22
  }
package/src/config.ts DELETED
@@ -1,45 +0,0 @@
1
- import { Tracer } from '@opentelemetry/api';
2
- import OpenLitHelper from './helpers';
3
- import { OpenlitConfigInterface, PricingObject } from './types';
4
-
5
- export default class OpenlitConfig {
6
- static environment: OpenlitConfigInterface['environment'];
7
- static applicationName: OpenlitConfigInterface['applicationName'];
8
- static pricingInfo: PricingObject;
9
- static tracer: OpenlitConfigInterface['tracer'];
10
- static otlpEndpoint?: OpenlitConfigInterface['otlpEndpoint'];
11
- static otlpHeaders?: OpenlitConfigInterface['otlpHeaders'];
12
- static disableBatch?: OpenlitConfigInterface['disableBatch'];
13
- static traceContent?: OpenlitConfigInterface['traceContent'];
14
- static pricing_json?: OpenlitConfigInterface['pricing_json'];
15
-
16
- static async updatePricingJson(pricing_json: any) {
17
- try {
18
- const response = await OpenLitHelper.fetchPricingInfo(pricing_json);
19
- this.pricingInfo = response;
20
- } catch (e) {
21
- this.pricingInfo = {};
22
- }
23
- return this.pricingInfo;
24
- }
25
-
26
- static updateConfig({
27
- environment = 'default',
28
- applicationName = 'default',
29
- tracer,
30
- otlpEndpoint,
31
- otlpHeaders,
32
- disableBatch = true,
33
- traceContent = true,
34
- pricing_json,
35
- }: OpenlitConfigInterface) {
36
- this.environment = environment;
37
- this.applicationName = applicationName;
38
- this.tracer = tracer;
39
- this.otlpEndpoint = otlpEndpoint;
40
- this.otlpHeaders = otlpHeaders;
41
- this.disableBatch = disableBatch;
42
- this.traceContent = traceContent;
43
- this.pricing_json = pricing_json;
44
- }
45
- }
package/src/constant.ts DELETED
@@ -1,6 +0,0 @@
1
- export const SDK_NAME = 'openlit';
2
- export const DEFAULT_ENVIRONMENT = 'default';
3
- export const DEFAULT_APPLICATION_NAME = 'default';
4
- export const INSTRUMENTATION_PREFIX = '@openlit';
5
- export const TELEMETRY_SDK_NAME = 'opentelemetry';
6
- export const OPENLIT_URL = 'http://127.0.0.1:3000';
@@ -1,7 +0,0 @@
1
- import PromptHub from './prompt-hub';
2
- import Vault from './vault';
3
-
4
- export default class BaseOpenlit {
5
- static getPrompts = PromptHub.getPrompts;
6
- static getSecrets = Vault.getSecrets;
7
- }
@@ -1,64 +0,0 @@
1
- import OpenlitConfig from '../config';
2
- import { OPENLIT_URL } from '../constant';
3
- import { PromptHubOptions } from '../types';
4
-
5
- export default class PromptHub {
6
- static async getPrompts(options: PromptHubOptions) {
7
- const url = process.env.OPENLIT_URL || options.url || OPENLIT_URL;
8
- const apiKey = process.env.OPENLIT_API_KEY || options.apiKey || '';
9
- let metaProperties = {
10
- applicationName: OpenlitConfig.applicationName,
11
- environment: OpenlitConfig.environment,
12
- };
13
- if (
14
- options.metaProperties &&
15
- typeof options.metaProperties === 'object' &&
16
- !Array.isArray(options.metaProperties)
17
- ) {
18
- metaProperties = {
19
- ...metaProperties,
20
- ...options.metaProperties,
21
- };
22
- }
23
-
24
- try {
25
- return await fetch(`${url}/api/prompt/get-compiled`, {
26
- method: 'POST',
27
- body: JSON.stringify({
28
- name: options.name,
29
- version: options.version,
30
- shouldCompile: !!options.shouldCompile,
31
- variables: options.variables || {},
32
- id: options.promptId,
33
- metaProperties,
34
- source: 'ts-sdk',
35
- }),
36
- headers: {
37
- Authorization: `Bearer ${apiKey}`,
38
- },
39
- })
40
- .then(async (response) => {
41
- if (!response.ok) {
42
- return {
43
- err: `Openlit Error : HTTP error! Status: ${response.status}`,
44
- };
45
- }
46
- return response.json();
47
- })
48
- .then((resp: any) => {
49
- return resp;
50
- });
51
- } catch (e: any) {
52
- if (e && typeof e.toString === 'function') {
53
- return {
54
- err: `Openlit Error : ${e.toString()}`,
55
- data: null,
56
- };
57
- }
58
-
59
- return {
60
- err: `Openlit Error : ${e}`,
61
- };
62
- }
63
- }
64
- }
@@ -1,54 +0,0 @@
1
- import { OPENLIT_URL } from '../constant';
2
- import { VaultOptions } from '../types';
3
-
4
- export default class Vault {
5
- static async getSecrets(options: VaultOptions) {
6
- const url = process.env.OPENLIT_URL || options.url || OPENLIT_URL;
7
- const apiKey = process.env.OPENLIT_API_KEY || options.apiKey || '';
8
-
9
- try {
10
- const vaultResponse = await fetch(`${url}/api/vault/get-secrets`, {
11
- method: 'POST',
12
- body: JSON.stringify({
13
- key: options.key,
14
- tags: options.tags,
15
- }),
16
- headers: {
17
- Authorization: `Bearer ${apiKey}`,
18
- },
19
- })
20
- .then(async (response) => {
21
- if (!response.ok) {
22
- return {
23
- err: `Openlit Error : HTTP error! Status: ${response.status}`,
24
- };
25
- }
26
- return response.json();
27
- })
28
- .then((resp: any) => {
29
- return resp;
30
- });
31
-
32
- const { res = {} } = vaultResponse;
33
- if (!!options.shouldSetEnv) {
34
- Object.entries(res).forEach(([key, value]: [string, unknown]) => {
35
- process.env[key] = value as string;
36
- });
37
- }
38
-
39
- return vaultResponse;
40
- } catch (e: any) {
41
- console.log(e);
42
- if (e && typeof e.toString === 'function') {
43
- return {
44
- err: `Openlit Error : ${e.toString()}`,
45
- data: null,
46
- };
47
- }
48
-
49
- return {
50
- err: `Openlit Error : ${e}`,
51
- };
52
- }
53
- }
54
- }
package/src/helpers.ts DELETED
@@ -1,122 +0,0 @@
1
- import { encodingForModel, TiktokenModel } from 'js-tiktoken';
2
- import { Span, SpanStatusCode } from '@opentelemetry/api';
3
-
4
- export default class OpenLitHelper {
5
- static readonly PROMPT_TOKEN_FACTOR = 1000;
6
-
7
- static openaiTokens(text: string, model: string): number {
8
- try {
9
- const encoding = encodingForModel(model as TiktokenModel);
10
- return encoding.encode(text).length;
11
- } catch (error) {
12
- console.error(`Error in openaiTokens: ${error}`);
13
- throw error;
14
- }
15
- }
16
-
17
- static generalTokens(text: string): number {
18
- const encoding = encodingForModel('gpt2');
19
- return encoding.encode(text).length;
20
- }
21
-
22
- static getChatModelCost(
23
- model: string,
24
- pricingInfo: any,
25
- promptTokens: number,
26
- completionTokens: number
27
- ): number {
28
- try {
29
- return (
30
- (promptTokens / OpenLitHelper.PROMPT_TOKEN_FACTOR) * pricingInfo.chat[model].promptPrice +
31
- (completionTokens / OpenLitHelper.PROMPT_TOKEN_FACTOR) *
32
- pricingInfo.chat[model].completionPrice
33
- );
34
- } catch (error) {
35
- console.error(`Error in getChatModelCost: ${error}`);
36
- return 0;
37
- }
38
- }
39
-
40
- static getEmbedModelCost(model: string, pricingInfo: any, promptTokens: number): number {
41
- try {
42
- return (promptTokens / OpenLitHelper.PROMPT_TOKEN_FACTOR) * pricingInfo.embeddings[model];
43
- } catch (error) {
44
- console.error(`Error in getEmbedModelCost: ${error}`);
45
- return 0;
46
- }
47
- }
48
-
49
- static getImageModelCost(model: string, pricingInfo: any, size: string, quality: number): number {
50
- try {
51
- return pricingInfo.images[model][quality][size];
52
- } catch (error) {
53
- console.error(`Error in getImageModelCost: ${error}`);
54
- return 0;
55
- }
56
- }
57
-
58
- static getAudioModelCost(model: string, pricingInfo: any, prompt: string): number {
59
- try {
60
- return (prompt.length / OpenLitHelper.PROMPT_TOKEN_FACTOR) * pricingInfo.audio[model];
61
- } catch (error) {
62
- console.error(`Error in getAudioModelCost: ${error}`);
63
- return 0;
64
- }
65
- }
66
-
67
- static async fetchPricingInfo(pricingJson: any) {
68
- let pricingUrl = 'https://raw.githubusercontent.com/openlit/openlit/main/assets/pricing.json';
69
- if (pricingJson) {
70
- let isUrl = false;
71
- try {
72
- isUrl = !!new URL(pricingJson);
73
- } catch {
74
- isUrl = false;
75
- }
76
-
77
- if (isUrl) {
78
- pricingUrl = pricingJson;
79
- } else {
80
- try {
81
- if (typeof pricingJson === 'string') {
82
- const json = JSON.parse(pricingJson);
83
- return json;
84
- } else {
85
- const json = JSON.parse(JSON.stringify(pricingJson));
86
- return json;
87
- }
88
- } catch {
89
- return {};
90
- }
91
- }
92
- }
93
-
94
- try {
95
- const response = await fetch(pricingUrl);
96
- if (response.ok) {
97
- return response.json();
98
- } else {
99
- throw new Error(`HTTP error occurred while fetching pricing info: ${response.status}`);
100
- }
101
- } catch (error) {
102
- console.error(`Unexpected error occurred while fetching pricing info: ${error}`);
103
- return {};
104
- }
105
- }
106
-
107
- static handleException(span: Span, error: Error): void {
108
- span.recordException(error);
109
- span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
110
- }
111
-
112
- static async createStreamProxy (stream: any, generatorFuncResponse: any): Promise<any> {
113
- return new Proxy(stream, {
114
- get (target, prop, receiver) {
115
- if (prop === Symbol.asyncIterator) {
116
- return () => generatorFuncResponse
117
- }
118
- return Reflect.get(target, prop, receiver)
119
- }
120
- })
121
- }
122
- }
package/src/index.ts DELETED
@@ -1,73 +0,0 @@
1
- import { Resource } from '@opentelemetry/resources';
2
- import {
3
- SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,
4
- SEMRESATTRS_SERVICE_NAME,
5
- SEMRESATTRS_TELEMETRY_SDK_NAME,
6
- } from '@opentelemetry/semantic-conventions';
7
- import { NodeSDK } from '@opentelemetry/sdk-node';
8
- import { OpenlitOptions } from './types';
9
- import Tracing from './tracing';
10
- import { DEFAULT_APPLICATION_NAME, DEFAULT_ENVIRONMENT, SDK_NAME } from './constant';
11
- import { SpanExporter } from '@opentelemetry/sdk-trace-base';
12
- import BaseOpenlit from './features/base';
13
-
14
- export default class Openlit extends BaseOpenlit {
15
- static resource: Resource;
16
- static options: OpenlitOptions;
17
- static _sdk: NodeSDK;
18
- static init(options?: OpenlitOptions) {
19
- try {
20
- const { environment = DEFAULT_ENVIRONMENT, applicationName = DEFAULT_APPLICATION_NAME } =
21
- options || {};
22
-
23
- const otlpEndpoint =
24
- options?.otlpEndpoint || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || undefined;
25
- let otlpHeaders = options?.otlpHeaders;
26
- if (!otlpHeaders) {
27
- if (process.env.OTEL_EXPORTER_OTLP_HEADERS) {
28
- otlpHeaders = process.env.OTEL_EXPORTER_OTLP_HEADERS.split(',').reduce(
29
- (acc: Record<string, any>, items: string) => {
30
- const keyVal: string[] = items.split('=');
31
- acc[keyVal[0]] = keyVal[1];
32
- return acc;
33
- },
34
- {}
35
- );
36
- } else {
37
- otlpHeaders = {};
38
- }
39
- }
40
-
41
- this.options = options || {};
42
- this.options.otlpEndpoint = otlpEndpoint;
43
- this.options.otlpHeaders = otlpHeaders;
44
- this.options.disableBatch =
45
- options?.disableBatch === undefined ? true : !!options.disableBatch;
46
-
47
- this.resource = new Resource({
48
- [SEMRESATTRS_SERVICE_NAME]: applicationName,
49
- [SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]: environment,
50
- [SEMRESATTRS_TELEMETRY_SDK_NAME]: SDK_NAME,
51
- });
52
-
53
- Tracing.setup({
54
- ...this.options,
55
- environment,
56
- applicationName,
57
- otlpEndpoint,
58
- otlpHeaders,
59
- resource: this.resource,
60
- });
61
-
62
- this._sdk = new NodeSDK({
63
- resource: this.resource,
64
- traceExporter: Tracing.traceExporter as SpanExporter,
65
- });
66
-
67
- // This was causing the traceProvider initilization with multiple instances.
68
- // this._sdk.start();
69
- } catch (e) {
70
- console.log('Connection time out', e);
71
- }
72
- }
73
- }
@@ -1,59 +0,0 @@
1
- import {
2
- InstrumentationBase,
3
- InstrumentationModuleDefinition,
4
- InstrumentationNodeModuleDefinition,
5
- isWrapped,
6
- } from '@opentelemetry/instrumentation';
7
- import { InstrumentationConfig } from '@opentelemetry/instrumentation';
8
- import { INSTRUMENTATION_PREFIX } from '../../constant';
9
- import Anthropic from '@anthropic-ai/sdk';
10
- import AnthropicWrapper from './wrapper';
11
-
12
- export interface AnthropicInstrumentationConfig extends InstrumentationConfig {}
13
-
14
- export default class OpenlitAnthropicInstrumentation extends InstrumentationBase {
15
- constructor(config: AnthropicInstrumentationConfig = {}) {
16
- super(`${INSTRUMENTATION_PREFIX}/instrumentation-anthropic`, '1.0.0', config);
17
- }
18
-
19
- protected init(): void | InstrumentationModuleDefinition | InstrumentationModuleDefinition[] {
20
- const module = new InstrumentationNodeModuleDefinition(
21
- '@anthropic-ai/sdk',
22
- ['>= 0.21.0'],
23
- (moduleExports) => {
24
- this._patch(moduleExports);
25
- return moduleExports;
26
- },
27
- (moduleExports) => {
28
- if (moduleExports !== undefined) {
29
- this._unpatch(moduleExports);
30
- }
31
- }
32
- );
33
- return [module];
34
- }
35
-
36
- public manualPatch(anthropic: any): void {
37
- this._patch(anthropic);
38
- }
39
-
40
- protected _patch(moduleExports: typeof Anthropic) {
41
- try {
42
- if (isWrapped(moduleExports.Anthropic.Messages.prototype.create)) {
43
- this._unwrap(moduleExports.Anthropic.Messages.prototype, 'create');
44
- }
45
-
46
- this._wrap(
47
- moduleExports.Anthropic.Messages.prototype,
48
- 'create',
49
- AnthropicWrapper._patchMessageCreate(this.tracer)
50
- );
51
- } catch (e) {
52
- console.error('Error in _patch method:', e);
53
- }
54
- }
55
-
56
- protected _unpatch(moduleExports: typeof Anthropic) {
57
- this._unwrap(moduleExports.Anthropic.Messages.prototype, 'create');
58
- }
59
- }