Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

[Feat]: OpenTelemetry Instrumentation for monitoring AI21 (#527)

Patchercdc6c6b7aa21
diff --git a/assets/pricing.json b/assets/pricing.json
index 083d8733..a0509d17 100644
--- a/assets/pricing.json
+++ b/assets/pricing.json
@@ -421,6 +421,14 @@
"grok-vision-beta": {
"promptPrice": 0.0005,
"completionPrice": 0.0015
+ },
+ "jamba-1.5-mini": {
+ "promptPrice": 0.0002,
+ "completionPrice": 0.0004
+ },
+ "jamba-1.5-large": {
+ "promptPrice": 0.002,
+ "completionPrice": 0.008
}
}
}
\ No newline at end of file
diff --git a/docs/images/docs-ai21-banner.gif b/docs/images/docs-ai21-banner.gif
new file mode 100644
index 00000000..50998287
Binary files /dev/null and b/docs/images/docs-ai21-banner.gif differ
diff --git a/docs/latest/integrations/ai21.mdx b/docs/latest/integrations/ai21.mdx
new file mode 100644
index 00000000..7fc04506
--- /dev/null
+++ b/docs/latest/integrations/ai21.mdx
@@ -0,0 +1,102 @@
+---
+title: 'Monitor AI21 using OpenTelemetry'
+sidebarTitle: 'AI21'
+---
+
+<Frame>
+ <img src="/images/docs-ai21-banner.gif" />
+</Frame>
+
+OpenLIT uses OpenTelemetry Auto-Instrumentation to help you monitor LLM applications built using AI21 models. This includes tracking performance, token usage, costs, and how users interact with the application.
+
+Auto-instrumentation means you don't have to set up monitoring manually for different LLMs, frameworks, or databases. By simply adding OpenLIT in your application, all the necessary monitoring configurations are automatically set up.
+
+The integration is compatible with
+- AI21 Python SDK client `>= 3.0.0`
+
+## Get Started
+
+<Steps>
+ <Step title="Install OpenLIT">
+ Open your command line or terminal and run:
+ <Tabs>
+ <Tab title="Python">
+ ```shell
+ pip install openlit
+ ```
+ </Tab>
+ <Tab title="Typescript">
+ ```shell
+ npm install openlit
+ ```
+ </Tab>
+ </Tabs>
+ </Step>
+ <Step title="Initialize OpenLIT in your Application">
+ You can set up OpenLIT in your application using either function arguments directly in your code or by using environment variables.
+ <Tabs>
+ <Tab title="Setup using function arguments">
+
+ Add the following two lines to your application code:
+
+ <Tabs>
+ <Tab title="Python">
+ ```python
+ import openlit
+
+ openlit.init(otlp_endpoint="YOUR_OTEL_ENDPOINT")
+ ```
+
+ </Tab>
+ </Tabs>
+
+ Replace:
+ 1. `YOUR_OTEL_ENDPOINT` with the URL of your OpenTelemetry backend, such as `http://127.0.0.1:4318` if you are using OpenLIT and a local OTel Collector.
+ </Tab>
+ <Tab title="Setup using Environment Variables">
+
+ Add the following two lines to your application code:
+
+ <Tabs>
+ <Tab title="Python">
+ ```python
+ import openlit
+
+ openlit.init()
+ ```
+
+ </Tab>
+ <Tab title="Typescript">
+ ```typescript
+ import openlit from "openlit"
+
+ openlit.init()
+ ```
+ </Tab>
+ </Tabs>
+
+ Then, configure the your OTLP endpoint using environment variable:
+ ```shell
+ export OTEL_EXPORTER_OTLP_ENDPOINT = "YOUR_OTEL_ENDPOINT"
+ ```
+
+ Replace:
+ 1. `YOUR_OTEL_ENDPOINT` with the URL of your OpenTelemetry backend, such as `http://127.0.0.1:4318` if you are using OpenLIT and a local OTel Collector.
+ </Tab>
+ </Tabs>
+ To send metrics and traces to other Observability tools, refer to the [Connections Guide](/latest/connections/intro).
+
+ For more advanced configurations and application use cases, visit the [OpenLIT Python repository](https://github.com/openlit/openlit/tree/main/sdk/python) or [OpenLIT Typescript repository](https://github.com/openlit/openlit/tree/main/sdk/typescript).
+ </Step>
+</Steps>
+
+---
+
+<CardGroup cols={2}>
+<Card title="Connections" href="/latest/connections/intro" icon='link'>
+Connect to your existing Observablity Stack
+</Card>
+<Card title="SDK configuration" href="/latest/sdk-configuration" icon='file-code'>
+Documentation of the configuration options for the OpenLIT SDK.
+</Card>
+</CardGroup>
\ No newline at end of file
diff --git a/docs/latest/integrations/introduction.mdx b/docs/latest/integrations/introduction.mdx
index ecc03f0e..9295e235 100644
--- a/docs/latest/integrations/introduction.mdx
+++ b/docs/latest/integrations/introduction.mdx
@@ -386,6 +386,20 @@ Start integrating and monitoring your applications with OpenLIT in just one line
iconType="duotone"
>
</Card>
+ <Card
+ title="AI21"
+ href="/latest/integrations/ai21"
+ icon={
+ <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 925 925">
+ <path d="M0 0 C0.77251602 0.00359528 1.54503204 0.00719055 2.34095764 0.01089478 C3.55549622 0.01067574 3.55549622 0.01067574 4.79457092 0.01045227 C7.48380671 0.01115163 10.17297412 0.01894507 12.86219788 0.02676392 C14.72164878 0.02862802 16.58110018 0.03005196 18.44055176 0.03105164 C23.34458258 0.03487746 28.24858398 0.04470829 33.15260315 0.05575562 C38.15280255 0.06596836 43.15300669 0.07054896 48.1532135 0.07559204 C57.97158583 0.0863305 67.78993629 0.10340769 77.60829163 0.12442017 C88.55141396 30.34688479 99.46133108 60.58114235 110.34217834 90.82608032 C113.72139573 100.21873682 117.1029341 109.61055775 120.48429871 119.00244141 C122.3590582 124.20973339 124.2336673 129.41707952 126.10829163 134.62442017 C126.85829091 136.70775376 127.60829091 138.79108709 128.35829163 140.87442017 C168.85829148 253.37441977 168.85829148 253.37441977 169.98323059 256.49925232 C170.7334326 258.58314566 171.48363605 260.66703848 172.23384094 262.75093079 C174.105762 267.95069175 175.97765822 273.15046166 177.84950256 278.35025024 C181.64875103 288.90408017 185.4484389 299.45775159 189.24891663 310.01113892 C192.63049207 319.40132638 196.01089647 328.79193457 199.39012146 338.18296814 C201.52961775 344.1284383 203.67066677 350.07334633 205.81288147 356.01783752 C207.14244355 359.70825215 208.47070308 363.39913458 209.79859924 367.09014893 C210.41725995 368.80891796 211.03647385 370.52748798 211.65626526 372.24584961 C212.49849812 374.58115524 213.33880116 376.91714609 214.17860413 379.25332642 C214.42762482 379.94232025 214.67664551 380.63131409 214.93321228 381.34118652 C216.60829163 386.01032737 216.60829163 386.01032737 216.60829163 387.12442017 C184.26829163 387.12442017 151.92829163 387.12442017 118.60829163 387.12442017 C113.50818269 371.82409337 108.46492644 356.50376376 103.60829163 341.12442017 C58.72829163 340.79442017 13.84829163 340.46442017 -32.39170837 340.12442017 C-33.38170837 344.08442017 -34.37170837 348.04442017 -35.39170837 352.12442017 C-36.25029914 354.99879859 -37.12377953 357.84949702 -38.05577087 360.69863892 C-38.29331085 361.4339534 -38.53085083 362.16926788 -38.77558899 362.92686462 C-39.26939257 364.45224695 -39.76512892 365.97700495 -40.26280212 367.50112915 C-41.02734957 369.84453641 -41.78411786 372.19036152 -42.54014587 374.53652954 C-43.02406942 376.02821253 -43.50842772 377.51975457 -43.99327087 379.01113892 C-44.21931 379.71204147 -44.44534912 380.41294403 -44.67823792 381.13508606 C-46.27634887 386.00906066 -46.27634887 386.00906066 -47.39170837 387.12442017 C-50.34417192 387.21968822 -53.27319259 387.24994469 -56.22593689 387.23794556 C-57.15267212 387.23809158 -58.07940735 387.23823761 -59.03422546 387.23838806 C-62.11304525 387.23768855 -65.19180535 387.22989438 -68.27061462 387.22207642 C-70.39910855 387.22021237 -72.5276029 387.21878841 -74.65609741 387.2177887 C-80.27033158 387.21396244 -85.88454005 387.20413125 -91.49876404 387.19308472 C-97.22284091 387.1828729 -102.94692191 387.17829157 -108.67100525 387.17324829 C-119.91125094 387.16250907 -131.15147752 387.14543137 -142.39170837 387.12442017 C-141.31343921 381.95948656 -140.12663307 376.95693365 -138.35484314 371.97695923 C-137.75519493 370.27935455 -137.75519493 370.27935455 -137.14343262 368.54745483 C-136.71102768 367.34050964 -136.27862274 366.13356445 -135.83311462 364.89004517 C-135.37233969 363.59212689 -134.91201905 362.29404725 -134.45211792 360.99581909 C-133.21647684 357.51211797 -131.97423607 354.03080443 -130.73066711 350.54992676 C-129.41856453 346.87363635 -128.11263458 343.19515349 -126.80577087 339.51699829 C-119.77896064 319.75110846 -112.69943998 300.00402543 -105.60557556 280.26211548 C-99.2508842 262.56864797 -92.96950581 244.84968367 -86.70420837 227.12442017 C-86.45804653 226.42804066 -86.21188469 225.73166115 -85.9582634 225.01417923 C-84.00968656 219.50173648 -82.06121229 213.98925746 -80.11295509 208.47670174 C-75.82149864 196.33436603 -71.51941633 184.19583691 -67.20420837 172.06192017 C-66.89245667 171.18524689 -66.58070496 170.30857361 -66.25950623 169.40533447 C-60.24806195 152.50460271 -54.20845028 135.61393596 -48.17127991 118.72238159 C-42.30342652 102.30258222 -36.45844439 85.87489586 -30.64170837 69.43692017 C-29.95430593 67.49501991 -29.26688743 65.55312534 -28.57945251 63.61123657 C-25.75805091 55.64030553 -22.9373709 47.6691217 -20.120224 39.69668579 C-18.23906189 34.37356174 -16.35505872 29.05145049 -14.46922302 23.72998047 C-13.75536278 21.71393385 -13.04254006 19.69751953 -12.33079529 17.6807251 C-11.35370395 14.91232865 -10.37313656 12.1451878 -9.39170837 9.37832642 C-8.95553192 8.13843964 -8.95553192 8.13843964 -8.51054382 6.87350464 C-6.06936345 0.01192332 -6.06936345 0.01192332 0 0 Z M35.60829163 113.12442017 C24.48961722 149.81508041 13.48869064 186.53855899 2.64076233 223.31021118 C2.42822972 224.03054566 2.21569712 224.75088015 1.99672413 225.49304295 C0.97067637 228.97073176 -0.05494149 232.44854606 -1.0796814 235.92662048 C-2.81178834 241.80191919 -4.55211246 247.67440454 -6.32676697 253.53701782 C-6.75604744 254.95583 -6.75604744 254.95583 -7.19400024 256.40330505 C-7.71076484 258.10632011 -8.22994872 259.80860391 -8.75213623 261.50996399 C-9.96163831 265.24929433 -9.96163831 265.24929433 -10.39170837 269.12442017 C19.96829163 269.12442017 50.32829163 269.12442017 81.60829163 269.12442017 C79.15118405 259.29598988 76.66700562 249.57503387 73.79969788 239.87442017 C73.24765105 237.99126748 72.69560456 236.10811469 72.14356995 234.22495842 C71.35785201 231.54771295 70.56914402 228.87135168 69.78054428 226.19495392 C68.09750593 220.4798698 66.42100653 214.76286007 64.74309731 209.04626846 C64.07954006 206.78600648 63.4155351 204.52587631 62.75152588 202.26574707 C59.64177298 191.67579149 56.55932066 181.07810007 53.48990822 170.47638702 C52.04696557 165.49393175 50.60136149 160.51224769 49.15606213 155.53047562 C47.98492738 151.49255944 46.81573537 147.45409894 45.65055847 143.41445923 C44.5532697 139.61034089 43.45119574 135.80764144 42.34553909 132.00594711 C41.9386423 130.60348443 41.53357389 129.20048983 41.13044357 127.79693985 C40.57892202 125.87754137 40.02042446 123.96015145 39.46156311 122.0428772 C39.15024948 120.96652008 38.83893585 119.89016296 38.51818848 118.78118896 C37.67321142 115.94534789 37.67321142 115.94534789 35.60829163 113.12442017 Z " fill="#E81D62" transform="translate(142.39170837402344,66.87557983398438)"/>
+ <path d="M0 0 C1.21798279 -0.0146228 1.21798279 -0.0146228 2.46057129 -0.02954102 C26.28806257 -0.25669666 48.73500657 0.9377322 71.3125 9.23828125 C72.83617187 9.78935547 72.83617187 9.78935547 74.390625 10.3515625 C87.01280261 15.26206208 99.27631005 22.10858588 109.3125 31.23828125 C110.27671875 32.1096875 111.2409375 32.98109375 112.234375 33.87890625 C132.01638043 52.36481663 143.2277347 79.05687894 144.43798828 106.03564453 C145.49229705 139.47153706 135.56080469 167.67763068 112.875 192.42578125 C111.03696911 194.37959109 109.17622546 196.3086532 107.3125 198.23828125 C106.05373047 199.59179688 106.05373047 199.59179688 104.76953125 200.97265625 C88.54048729 217.96282028 67.87983063 230.24679543 47.99584961 242.453125 C40.61072741 247.00661419 33.42311601 251.78590837 26.34423828 256.80078125 C24.92410345 257.80555821 23.50028924 258.8051459 22.07373047 259.80078125 C12.17236764 266.71324937 2.97477534 273.81514848 -5.6875 282.23828125 C-6.44546875 282.91117187 -7.2034375 283.5840625 -7.984375 284.27734375 C-19.17947395 294.50444542 -21.46361475 307.78302712 -23.6875 322.23828125 C30.7625 322.23828125 85.2125 322.23828125 141.3125 322.23828125 C141.3125 346.32828125 141.3125 370.41828125 141.3125 395.23828125 C52.8725 395.23828125 -35.5675 395.23828125 -126.6875 395.23828125 C-126.6875 372.73482648 -126.6875 372.73482648 -125.9375 362.67578125 C-125.85024658 361.49814209 -125.76299316 360.32050293 -125.6730957 359.10717773 C-121.72406154 310.00478858 -108.15519184 265.50125336 -72.6875 230.23828125 C-72.10709961 229.63282471 -71.52669922 229.02736816 -70.92871094 228.40356445 C-66.01706877 223.33927639 -60.80046554 219.04285304 -55.125 214.86328125 C-53.93680664 213.96996094 -53.93680664 213.96996094 -52.72460938 213.05859375 C-39.5984264 203.29412036 -25.78792424 194.78857677 -11.66699219 186.56103516 C29.39105952 163.18445727 29.39105952 163.18445727 54.05859375 124.74609375 C57.02014973 111.96034173 56.0376545 97.42509184 49.6875 85.80078125 C43.80520832 76.97734374 35.18549836 72.32189893 25.11328125 69.65625 C9.93922373 67.39178117 -4.33145325 69.09909626 -17.37109375 77.4921875 C-26.86529861 84.64886469 -31.62223012 94.14976381 -33.9375 105.67578125 C-34.76795432 111.83498409 -35.21083614 118.04165107 -35.6875 124.23828125 C-65.3875 124.23828125 -95.0875 124.23828125 -125.6875 124.23828125 C-124.51264421 103.0908771 -124.51264421 103.0908771 -123.0625 96.30078125 C-122.89065186 95.4806958 -122.71880371 94.66061035 -122.54174805 93.81567383 C-115.85370751 63.80126282 -98.36471809 38.12882365 -72.47314453 21.37011719 C-51.15542449 7.85781884 -25.24577073 0.25239058 0 0 Z " fill="#E81E62" transform="translate(601.6875,58.76171875)"/>
+ <path d="M0 0 C26.07 0 52.14 0 79 0 C79 127.71 79 255.42 79 387 C48.97 387 18.94 387 -12 387 C-12 302.52 -12 218.04 -12 131 C-38.4 131 -64.8 131 -92 131 C-92 110.21 -92 89.42 -92 68 C-75.5 66.6875 -75.5 66.6875 -70.40429688 66.2956543 C-50.10526887 64.6602305 -27.88897762 61.80945056 -13.125 46.25 C-2.59101876 33.0951239 -1.89627159 16.11830848 0 0 Z " fill="#E81E62" transform="translate(851,67)"/>
+ <path d="M0 0 C30.03 0 60.06 0 91 0 C91 127.71 91 255.42 91 387 C60.97 387 30.94 387 0 387 C0 259.29 0 131.58 0 0 Z " fill="#E81E62" transform="translate(368,67)"/>
+ </svg>
+ }
+ iconType="duotone"
+ >
+ </Card>
<Card
title="Reka AI"
href="/latest/integrations/reka"
diff --git a/docs/mint.json b/docs/mint.json
index bd3375ad..8b9338cc 100644
--- a/docs/mint.json
+++ b/docs/mint.json
@@ -102,6 +102,7 @@
"latest/integrations/nvidia-nim",
"latest/integrations/xai",
"latest/integrations/elevenlabs",
+ "latest/integrations/ai21",
"latest/integrations/reka",
"latest/integrations/krutrim",
"latest/integrations/titan-ml",
diff --git a/sdk/python/README.md b/sdk/python/README.md
index 07413ecb..42e22c09 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -45,19 +45,18 @@ This project proudly follows and maintains the [Semantic Conventions](https://gi
| [✅ GitHub AI Models](https://docs.openlit.io/latest/integrations/github-models) | | [✅ AG2](https://docs.openlit.io/latest/integrations/ag2) | |
| [✅ HuggingFace Transformers](https://docs.openlit.io/latest/integrations/huggingface) | | [✅ Dynamiq](https://docs.openlit.io/latest/integrations/dynamiq) | |
| [✅ Amazon Bedrock](https://docs.openlit.io/latest/integrations/bedrock) | | [✅ Phidata](https://docs.openlit.io/latest/integrations/phidata) | |
-| | | [✅ mem0](https://docs.openlit.io/latest/integrations/mem0) | |
-| [✅ Vertex AI](https://docs.openlit.io/latest/integrations/vertexai) | | [✅ MultiOn](https://docs.openlit.io/latest/integrations/multion) | |
-| [✅ Groq](https://docs.openlit.io/latest/integrations/groq) | | [✅ Julep AI](https://docs.openlit.io/latest/integrations/julep-ai) | |
-| [✅ ElevenLabs](https://docs.openlit.io/latest/integrations/elevenlabs) | | | |
-| [✅ vLLM](https://docs.openlit.io/latest/integrations/vllm) | | | |
-| [✅ OLA Krutrim](https://docs.openlit.io/latest/integrations/krutrim) | | | |
-| [✅ Google AI Studio](https://docs.openlit.io/latest/integrations/google-ai-studio) | | | |
-| [✅ NVIDIA NIM](https://docs.openlit.io/latest/integrations/nvidia-nim) | | | |
-| [✅ Titan ML](https://docs.openlit.io/latest/integrations/titan-ml) | | | |
-| [✅ Reka AI](https://docs.openlit.io/latest/integrations/reka) | | | |
-| [✅ xAI](https://docs.openlit.io/latest/integrations/xai) | | | |
-| [✅ Prem AI](https://docs.openlit.io/latest/integrations/premai) | | | |
-
+| [✅ AI21](https://docs.openlit.io/latest/integrations/ai21) | | [✅ mem0](https://docs.openlit.io/latest/integrations/mem0) | |
+| [✅ Vertex AI](https://docs.openlit.io/latest/integrations/vertexai) | | [✅ MultiOn](https://docs.openlit.io/latest/integrations/multion) | |
+| [✅ Groq](https://docs.openlit.io/latest/integrations/groq) | | [✅ Julep AI](https://docs.openlit.io/latest/integrations/julep-ai) | |
+| [✅ ElevenLabs](https://docs.openlit.io/latest/integrations/elevenlabs) | | | |
+| [✅ vLLM](https://docs.openlit.io/latest/integrations/vllm) | | | |
+| [✅ OLA Krutrim](https://docs.openlit.io/latest/integrations/krutrim) | | | |
+| [✅ Google AI Studio](https://docs.openlit.io/latest/integrations/google-ai-studio) | | | |
+| [✅ NVIDIA NIM](https://docs.openlit.io/latest/integrations/nvidia-nim) | | | |
+| [✅ Titan ML](https://docs.openlit.io/latest/integrations/titan-ml) | | | |
+| [✅ Reka AI](https://docs.openlit.io/latest/integrations/reka) | | | |
+| [✅ xAI](https://docs.openlit.io/latest/integrations/xai) | | | |
+| [✅ Prem AI](https://docs.openlit.io/latest/integrations/premai) | | | |
## Supported Destinations
- [✅ OpenTelemetry Collector](https://docs.openlit.io/latest/connections/otelcol)
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
index fa78a031..df6ac8a1 100644
--- a/sdk/python/pyproject.toml
+++ b/sdk/python/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "openlit"
-version = "1.32.3"
+version = "1.32.4"
description = "OpenTelemetry-native Auto instrumentation library for monitoring LLM Applications and GPUs, facilitating the integration of observability into your GenAI-driven projects"
authors = ["OpenLIT"]
repository = "https://github.com/openlit/openlit/tree/main/openlit/python"
diff --git a/sdk/python/src/openlit/__init__.py b/sdk/python/src/openlit/__init__.py
index cd29518d..b488a218 100644
--- a/sdk/python/src/openlit/__init__.py
+++ b/sdk/python/src/openlit/__init__.py
@@ -57,6 +57,7 @@ from openlit.instrumentation.multion import MultiOnInstrumentor
from openlit.instrumentation.dynamiq import DynamiqInstrumentor
from openlit.instrumentation.phidata import PhidataInstrumentor
from openlit.instrumentation.julep import JulepInstrumentor
+from openlit.instrumentation.ai21 import AI21Instrumentor
from openlit.instrumentation.gpu import GPUInstrumentor
import openlit.guard
import openlit.evals
@@ -252,6 +253,7 @@ def init(environment="default", application_name="default", tracer=None, otlp_en
"premai": "premai",
"julep": "julep",
"astra": "astrapy",
+ "ai21": "ai21",
}
invalid_instrumentors = [
@@ -342,6 +344,7 @@ def init(environment="default", application_name="default", tracer=None, otlp_en
"premai": PremAIInstrumentor(),
"julep": JulepInstrumentor(),
"astra": AstraInstrumentor(),
+ "ai21": AI21Instrumentor(),
}
# Initialize and instrument only the enabled instrumentors
diff --git a/sdk/python/src/openlit/instrumentation/ai21/__init__.py b/sdk/python/src/openlit/instrumentation/ai21/__init__.py
new file mode 100644
index 00000000..9c461e42
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/ai21/__init__.py
@@ -0,0 +1,66 @@
+# pylint: disable=useless-return, bad-staticmethod-argument, disable=duplicate-code
+"""Initializer of Auto Instrumentation of AI21 Functions"""
+
+from typing import Collection
+import importlib.metadata
+from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
+from wrapt import wrap_function_wrapper
+
+from openlit.instrumentation.ai21.ai21 import (
+ chat, chat_rag
+)
+from openlit.instrumentation.ai21.async_ai21 import (
+ async_chat, async_chat_rag
+)
+
+_instruments = ("ai21 >= 3.0.0",)
+
+class AI21Instrumentor(BaseInstrumentor):
+ """
+ An instrumentor for AI21's client library.
+ """
+
+ def instrumentation_dependencies(self) -> Collection[str]:
+ return _instruments
+
+ def _instrument(self, **kwargs):
+ application_name = kwargs.get("application_name", "default_application")
+ environment = kwargs.get("environment", "default_environment")
+ tracer = kwargs.get("tracer")
+ metrics = kwargs.get("metrics_dict")
+ pricing_info = kwargs.get("pricing_info", {})
+ trace_content = kwargs.get("trace_content", False)
+ disable_metrics = kwargs.get("disable_metrics")
+ version = importlib.metadata.version("ai21")
+
+ #sync
+ wrap_function_wrapper(
+ "ai21.clients.studio.resources.chat.chat_completions",
+ "ChatCompletions.create",
+ chat("ai21.chat.completions", version, environment, application_name,
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
+ )
+ wrap_function_wrapper(
+ "ai21.clients.studio.resources.studio_conversational_rag",
+ "StudioConversationalRag.create",
+ chat_rag("ai21.conversational_rag", version, environment, application_name,
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
+ )
+
+ #Async
+ wrap_function_wrapper(
+ "ai21.clients.studio.resources.chat.async_chat_completions",
+ "AsyncChatCompletions.create",
+ async_chat("ai21.chat.completions", version, environment, application_name,
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
+ )
+ wrap_function_wrapper(
+ "ai21.clients.studio.resources.studio_conversational_rag",
+ "AsyncStudioConversationalRag.create",
+ async_chat_rag("ai21.conversational_rag", version, environment, application_name,
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
+ )
+
+ def _uninstrument(self, **kwargs):
+ # Proper uninstrumentation logic to revert patched methods
+ pass
diff --git a/sdk/python/src/openlit/instrumentation/ai21/ai21.py b/sdk/python/src/openlit/instrumentation/ai21/ai21.py
new file mode 100644
index 00000000..560f0553
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/ai21/ai21.py
@@ -0,0 +1,604 @@
+# pylint: disable=duplicate-code, broad-exception-caught, too-many-statements, unused-argument, too-many-branches, too-many-instance-attributes, inconsistent-return-statements
+"""
+Module for monitoring AI21 calls.
+"""
+
+import logging
+from opentelemetry.trace import SpanKind, Status, StatusCode
+from opentelemetry.sdk.resources import TELEMETRY_SDK_NAME
+from openlit.__helpers import (
+ get_chat_model_cost,
+ handle_exception,
+ response_as_dict,
+ general_tokens
+)
+from openlit.semcov import SemanticConvetion
+
+# Initialize logger for logging potential issues and operations
+logger = logging.getLogger(__name__)
+
+def chat(gen_ai_endpoint, version, environment, application_name,
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
+ """
+ Generates a telemetry wrapper for chat completions to collect metrics.
+
+ Args:
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
+ version: Version of the monitoring package.
+ environment: Deployment environment (e.g., production, staging).
+ application_name: Name of the application using the AI21 SDK.
+ tracer: OpenTelemetry tracer for creating spans.
+ pricing_info: Information used for calculating the cost of AI21 usage.
+ trace_content: Flag indicating whether to trace the actual content.
+
+ Returns:
+ A function that wraps the chat completions method to add telemetry.
+ """
+
+ class TracedSyncStream:
+ """
+ Wrapper for streaming responses to collect metrics and trace data.
+
+ This class implements the '__aiter__' and '__anext__' methods that
+ handle asynchronous streaming responses.
+
+ This class also implements '__aenter__' and '__aexit__' methods that
+ handle asynchronous context management protocol.
+ """
+ def __init__(
+ self,
+ wrapped,
+ span,
+ kwargs,
+ **args,
+ ):
+ self.__wrapped__ = wrapped
+ self._span = span
+ # Placeholder for aggregating streaming response
+ self._llmresponse = ""
+ self._response_id = ""
+ self._prompt_tokens = 0
+ self._completion_tokens = 0
+
+ self._args = args
+ self._kwargs = kwargs
+
+ def __enter__(self):
+ self.__wrapped__.__enter__()
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.__wrapped__.__exit__(exc_type, exc_value, traceback)
+
+ def __iter__(self):
+ return self
+
+ def __getattr__(self, name):
+ """Delegate attribute access to the wrapped object."""
+ return getattr(self.__wrapped__, name)
+
+ def __next__(self):
+ try:
+ chunk = self.__wrapped__.__next__()
+ chunked = response_as_dict(chunk)
+ # Collect message IDs and aggregated response from events
+ if (len(chunked.get('choices')) > 0 and ('delta' in chunked.get('choices')[0] and
+ 'content' in chunked.get('choices')[0].get('delta'))):
+
+ content = chunked.get('choices')[0].get('delta').get('content')
+ if content:
+ self._llmresponse += content
+
+ if chunked.get('usage'):
+ self._prompt_tokens = chunked.get('usage').get("prompt_tokens")
+ self._completion_tokens = chunked.get('usage').get("completion_tokens")
+
+ self._response_id = chunked.get('id')
+ return chunk
+ except StopIteration:
+ # Handling exception ensure observability without disrupting operation
+ try:
+ # Format 'messages' into a single string
+ message_prompt = self._kwargs.get("messages", "")
+ formatted_messages = []
+ for message in message_prompt:
+ role = message.role
+ content = message.content
+
+ if isinstance(content, list):
+ content_str = ", ".join(
+ # pylint: disable=line-too-long
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
+ if "type" in item else f'text: {item["text"]}'
+ for item in content
+ )
+ formatted_messages.append(f"{role}: {content_str}")
+ else:
+ formatted_messages.append(f"{role}: {content}")
+ prompt = "\n".join(formatted_messages)
+
+ # Calculate cost of the operation
+ cost = get_chat_model_cost(self._kwargs.get("model", "jamba-1.5-mini"),
+ pricing_info, self._prompt_tokens,
+ self._completion_tokens)
+
+ # Set Span attributes
+ self._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
+ SemanticConvetion.GEN_AI_SYSTEM_AI21)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
+ gen_ai_endpoint)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
+ self._response_id)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
+ environment)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
+ application_name)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
+ self._kwargs.get("model", "jamba-1.5-mini"))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
+ self._kwargs.get("top_p", 1.0))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
+ self._kwargs.get("max_tokens", -1))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
+ self._kwargs.get("temperature", 1.0))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
+ True)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
+ self._prompt_tokens)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
+ self._completion_tokens)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
+ self._prompt_tokens + self._completion_tokens)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
+ cost)
+ if trace_content:
+ self._span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
+ },
+ )
+ self._span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: self._llmresponse,
+ },
+ )
+
+ self._span.set_status(Status(StatusCode.OK))
+
+ if disable_metrics is False:
+ attributes = {
+ TELEMETRY_SDK_NAME:
+ "openlit",
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
+ application_name,
+ SemanticConvetion.GEN_AI_SYSTEM:
+ SemanticConvetion.GEN_AI_SYSTEM_AI21,
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
+ environment,
+ SemanticConvetion.GEN_AI_TYPE:
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
+ self._kwargs.get("model", "jamba-1.5-mini")
+ }
+
+ metrics["genai_requests"].add(1, attributes)
+ metrics["genai_total_tokens"].add(
+ self._prompt_tokens + self._completion_tokens, attributes
+ )
+ metrics["genai_completion_tokens"].add(self._completion_tokens, attributes)
+ metrics["genai_prompt_tokens"].add(self._prompt_tokens, attributes)
+ metrics["genai_cost"].record(cost, attributes)
+
+ except Exception as e:
+ handle_exception(self._span, e)
+ logger.error("Error in trace creation: %s", e)
+ finally:
+ self._span.end()
+ raise
+
+ def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the 'chat.completions' API call to add telemetry.
+
+ This collects metrics such as execution time, cost, and token usage, and handles errors
+ gracefully, adding details to the trace for observability.
+
+ Args:
+ wrapped: The original 'chat.completions' method to be wrapped.
+ instance: The instance of the class where the original method is defined.
+ args: Positional arguments for the 'chat.completions' method.
+ kwargs: Keyword arguments for the 'chat.completions' method.
+
+ Returns:
+ The response from the original 'chat.completions' method.
+ """
+
+ # Check if streaming is enabled for the API call
+ streaming = kwargs.get("stream", False)
+
+ # pylint: disable=no-else-return
+ if streaming:
+ # Special handling for streaming response to accommodate the nature of data flow
+ awaited_wrapped = wrapped(*args, **kwargs)
+ span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
+
+ return TracedSyncStream(awaited_wrapped, span, kwargs)
+
+ # Handling for non-streaming responses
+ else:
+ # pylint: disable=line-too-long
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
+ response = wrapped(*args, **kwargs)
+
+ response_dict = response_as_dict(response)
+
+ try:
+ # Format 'messages' into a single string
+ message_prompt = kwargs.get("messages", "")
+ formatted_messages = []
+ for message in message_prompt:
+ role = message.role
+ content = message.content
+
+ if isinstance(content, list):
+ content_str = ", ".join(
+ # pylint: disable=line-too-long
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
+ if "type" in item else f'text: {item["text"]}'
+ for item in content
+ )
+ formatted_messages.append(f"{role}: {content_str}")
+ else:
+ formatted_messages.append(f"{role}: {content}")
+ prompt = "\n".join(formatted_messages)
+
+ # Set base span attribues
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
+ SemanticConvetion.GEN_AI_SYSTEM_AI21)
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
+ gen_ai_endpoint)
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
+ response_dict.get("id"))
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
+ environment)
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
+ application_name)
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
+ kwargs.get("model", "jamba-1.5-mini"))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
+ kwargs.get("top_p", 1.0))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
+ kwargs.get("max_tokens", -1))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
+ kwargs.get("temperature", 1.0))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
+ False)
+ if trace_content:
+ span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
+ },
+ )
+
+ # Set span attributes when tools is not passed to the function call
+ if "tools" not in kwargs:
+ # Calculate cost of the operation
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
+ pricing_info, response_dict.get('usage', {}).get('prompt_tokens', None),
+ response_dict.get('usage', {}).get('completion_tokens', None))
+
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
+ response_dict.get('usage', {}).get('prompt_tokens', None))
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
+ response_dict.get('usage', {}).get('completion_tokens', None))
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
+ response_dict.get('usage', {}).get('total_tokens', None))
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
+ [response_dict.get('choices', [])[0].get('finish_reason', None)])
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
+ cost)
+
+ # Set span attributes for when n = 1 (default)
+ if "n" not in kwargs or kwargs["n"] == 1:
+ if trace_content:
+ span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices', [])[0].get("message").get("content"),
+ },
+ )
+
+ # Set span attributes for when n > 0
+ else:
+ i = 0
+ while i < kwargs["n"] and trace_content is True:
+ attribute_name = f"gen_ai.content.completion.{i}"
+ span.add_event(
+ name=attribute_name,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices')[i].get("message").get("content"),
+ },
+ )
+ i += 1
+
+ # Return original response
+ return response
+
+ # Set span attributes when tools is passed to the function call
+ elif "tools" in kwargs:
+ # Calculate cost of the operation
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
+ pricing_info, response_dict.get('usage').get('prompt_tokens'),
+ response_dict.get('usage').get('completion_tokens'))
+ span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: "Function called with tools",
+ },
+ )
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
+ response_dict.get('usage').get('prompt_tokens'))
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
+ response_dict.get('usage').get('completion_tokens'))
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
+ response_dict.get('usage').get('total_tokens'))
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
+ cost)
+
+ span.set_status(Status(StatusCode.OK))
+
+ if disable_metrics is False:
+ attributes = {
+ TELEMETRY_SDK_NAME:
+ "openlit",
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
+ application_name,
+ SemanticConvetion.GEN_AI_SYSTEM:
+ SemanticConvetion.GEN_AI_SYSTEM_AI21,
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
+ environment,
+ SemanticConvetion.GEN_AI_TYPE:
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
+ kwargs.get("model", "jamba-1.5-mini")
+ }
+
+ metrics["genai_requests"].add(1, attributes)
+ metrics["genai_total_tokens"].add(response_dict.get('usage').get('total_tokens'), attributes)
+ metrics["genai_completion_tokens"].add(response_dict.get('usage').get('completion_tokens'), attributes)
+ metrics["genai_prompt_tokens"].add(response_dict.get('usage').get('prompt_tokens'), attributes)
+ metrics["genai_cost"].record(cost, attributes)
+
+ # Return original response
+ return response
+
+ except Exception as e:
+ handle_exception(span, e)
+ logger.error("Error in trace creation: %s", e)
+
+ # Return original response
+ return response
+
+ return wrapper
+
+def chat_rag(gen_ai_endpoint, version, environment, application_name,
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
+ """
+ Generates a telemetry wrapper for chat completions to collect metrics.
+
+ Args:
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
+ version: Version of the monitoring package.
+ environment: Deployment environment (e.g., production, staging).
+ application_name: Name of the application using the AI21 SDK.
+ tracer: OpenTelemetry tracer for creating spans.
+ pricing_info: Information used for calculating the cost of AI21 usage.
+ trace_content: Flag indicating whether to trace the actual content.
+
+ Returns:
+ A function that wraps the chat completions method to add telemetry.
+ """
+
+ def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the 'chat.completions' API call to add telemetry.
+
+ This collects metrics such as execution time, cost, and token usage, and handles errors
+ gracefully, adding details to the trace for observability.
+
+ Args:
+ wrapped: The original 'chat.completions' method to be wrapped.
+ instance: The instance of the class where the original method is defined.
+ args: Positional arguments for the 'chat.completions' method.
+ kwargs: Keyword arguments for the 'chat.completions' method.
+
+ Returns:
+ The response from the original 'chat.completions' method.
+ """
+
+ # Check if streaming is enabled for the API call
+ streaming = kwargs.get("stream", False)
+
+ # pylint: disable=no-else-return
+ if streaming:
+ # # Special handling for streaming response to accommodate the nature of data flow
+ # awaited_wrapped = wrapped(*args, **kwargs)
+ # span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
+
+ # return TracedSyncStream(awaited_wrapped, span, kwargs)
+
+ return
+
+ # Handling for non-streaming responses
+ else:
+ # pylint: disable=line-too-long
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
+ response = wrapped(*args, **kwargs)
+
+ response_dict = response_as_dict(response)
+
+ try:
+ # Format 'messages' into a single string
+ message_prompt = kwargs.get("messages", "")
+ formatted_messages = []
+ for message in message_prompt:
+ role = message.role
+ content = message.content
+
+ if isinstance(content, list):
+ content_str = ", ".join(
+ # pylint: disable=line-too-long
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
+ if "type" in item else f'text: {item["text"]}'
+ for item in content
+ )
+ formatted_messages.append(f"{role}: {content_str}")
+ else:
+ formatted_messages.append(f"{role}: {content}")
+ prompt = "\n".join(formatted_messages)
+
+ # Set base span attribues
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
+ SemanticConvetion.GEN_AI_SYSTEM_AI21)
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
+ gen_ai_endpoint)
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
+ response_dict.get("id"))
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
+ environment)
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
+ application_name)
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
+ kwargs.get("model", "jamba-1.5-mini"))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
+ False)
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_MAX_SEGMENTS,
+ kwargs.get("max_segments", -1))
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_STRATEGY,
+ kwargs.get("retrieval_strategy", "segments"))
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_SIMILARITY_THRESHOLD,
+ kwargs.get("retrieval_similarity_threshold", -1))
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_MAX_NEIGHBORS,
+ kwargs.get("max_neighbors", -1))
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_FILE_IDS,
+ str(kwargs.get("file_ids", "")))
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_DOCUMENTS_PATH,
+ kwargs.get("path", ""))
+
+ if trace_content:
+ span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
+ },
+ )
+ prompt_tokens = general_tokens(prompt)
+
+
+ # Set span attributes when tools is not passed to the function call
+ if "tools" not in kwargs:
+ prompt_tokens = general_tokens(prompt)
+
+ # Set span attributes for when n = 1 (default)
+ if "n" not in kwargs or kwargs["n"] == 1:
+ completion_tokens = general_tokens(response_dict.get('choices', [])[0].get("content"))
+ if trace_content:
+ span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices', [])[0].get("content"),
+ },
+ )
+
+ # Set span attributes for when n > 0
+ else:
+ i = 0
+ completion_tokens = 0
+ while i < kwargs["n"] and trace_content is True:
+ completion_tokens += general_tokens(response_dict.get('choices')[i].get("message").get("content"))
+ attribute_name = f"gen_ai.content.completion.{i}"
+ span.add_event(
+ name=attribute_name,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices')[i].get("message").get("content"),
+ },
+ )
+ i += 1
+
+ # Return original response
+ return response
+
+ # Set span attributes when tools is passed to the function call
+ elif "tools" in kwargs:
+ completion_tokens = -1
+ # Calculate cost of the operation
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
+ pricing_info, response_dict.get('usage').get('prompt_tokens'),
+ response_dict.get('usage').get('completion_tokens'))
+ span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: "Function called with tools",
+ },
+ )
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
+ prompt_tokens)
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
+ completion_tokens)
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
+ prompt_tokens + completion_tokens)
+
+ # Calculate cost of the operation
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
+ pricing_info, prompt_tokens,
+ completion_tokens)
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
+ cost)
+
+ span.set_status(Status(StatusCode.OK))
+
+ if disable_metrics is False:
+ attributes = {
+ TELEMETRY_SDK_NAME:
+ "openlit",
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
+ application_name,
+ SemanticConvetion.GEN_AI_SYSTEM:
+ SemanticConvetion.GEN_AI_SYSTEM_AI21,
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
+ environment,
+ SemanticConvetion.GEN_AI_TYPE:
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
+ kwargs.get("model", "jamba-1.5-mini")
+ }
+
+ metrics["genai_requests"].add(1, attributes)
+ metrics["genai_total_tokens"].add(prompt_tokens + completion_tokens, attributes)
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
+ metrics["genai_cost"].record(cost, attributes)
+
+ # Return original response
+ return response
+
+ except Exception as e:
+ handle_exception(span, e)
+ logger.error("Error in trace creation: %s", e)
+
+ # Return original response
+ return response
+
+ return wrapper
diff --git a/sdk/python/src/openlit/instrumentation/ai21/async_ai21.py b/sdk/python/src/openlit/instrumentation/ai21/async_ai21.py
new file mode 100644
index 00000000..3b0a0dff
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/ai21/async_ai21.py
@@ -0,0 +1,603 @@
+# pylint: disable=duplicate-code, broad-exception-caught, too-many-statements, unused-argument, too-many-branches, too-many-instance-attributes, inconsistent-return-statements
+"""
+Module for monitoring AI21 calls.
+"""
+
+import logging
+from opentelemetry.trace import SpanKind, Status, StatusCode
+from opentelemetry.sdk.resources import TELEMETRY_SDK_NAME
+from openlit.__helpers import (
+ get_chat_model_cost,
+ handle_exception,
+ response_as_dict,
+ general_tokens
+)
+from openlit.semcov import SemanticConvetion
+
+# Initialize logger for logging potential issues and operations
+logger = logging.getLogger(__name__)
+
+def async_chat(gen_ai_endpoint, version, environment, application_name,
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
+ """
+ Generates a telemetry wrapper for chat completions to collect metrics.
+
+ Args:
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
+ version: Version of the monitoring package.
+ environment: Deployment environment (e.g., production, staging).
+ application_name: Name of the application using the AI21 SDK.
+ tracer: OpenTelemetry tracer for creating spans.
+ pricing_info: Information used for calculating the cost of AI21 usage.
+ trace_content: Flag indicating whether to trace the actual content.
+
+ Returns:
+ A function that wraps the chat completions method to add telemetry.
+ """
+
+ class TracedAsyncStream:
+ """
+ Wrapper for streaming responses to collect metrics and trace data.
+
+ This class implements the '__aiter__' and '__anext__' methods that
+ handle asynchronous streaming responses.
+
+ This class also implements '__aenter__' and '__aexit__' methods that
+ handle asynchronous context management protocol.
+ """
+ def __init__(
+ self,
+ wrapped,
+ span,
+ kwargs,
+ **args,
+ ):
+ self.__wrapped__ = wrapped
+ self._span = span
+ # Placeholder for aggregating streaming response
+ self._llmresponse = ""
+ self._response_id = ""
+ self._prompt_tokens = 0
+ self._completion_tokens = 0
+
+ self._args = args
+ self._kwargs = kwargs
+
+ async def __aenter__(self):
+ await self.__wrapped__.__aenter__()
+ return self
+
+ async def __aexit__(self, exc_type, exc_value, traceback):
+ await self.__wrapped__.__aexit__(exc_type, exc_value, traceback)
+
+ def __aiter__(self):
+ return self
+
+ async def __getattr__(self, name):
+ """Delegate attribute access to the wrapped object."""
+ return getattr(await self.__wrapped__, name)
+
+ async def __anext__(self):
+ try:
+ chunk = await self.__wrapped__.__anext__()
+ chunked = response_as_dict(chunk)
+ # Collect message IDs and aggregated response from events
+ if (len(chunked.get('choices')) > 0 and ('delta' in chunked.get('choices')[0] and
+ 'content' in chunked.get('choices')[0].get('delta'))):
+
+ content = chunked.get('choices')[0].get('delta').get('content')
+ if content:
+ self._llmresponse += content
+
+ if chunked.get('usage'):
+ self._prompt_tokens = chunked.get('usage').get("prompt_tokens")
+ self._completion_tokens = chunked.get('usage').get("completion_tokens")
+
+ self._response_id = chunked.get('id')
+ return chunk
+ except StopAsyncIteration:
+ # Handling exception ensure observability without disrupting operation
+ try:
+ # Format 'messages' into a single string
+ message_prompt = self._kwargs.get("messages", "")
+ formatted_messages = []
+ for message in message_prompt:
+ role = message.role
+ content = message.content
+
+ if isinstance(content, list):
+ content_str = ", ".join(
+ # pylint: disable=line-too-long
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
+ if "type" in item else f'text: {item["text"]}'
+ for item in content
+ )
+ formatted_messages.append(f"{role}: {content_str}")
+ else:
+ formatted_messages.append(f"{role}: {content}")
+ prompt = "\n".join(formatted_messages)
+
+ # Calculate cost of the operation
+ cost = get_chat_model_cost(self._kwargs.get("model", "jamba-1.5-mini"),
+ pricing_info, self._prompt_tokens,
+ self._completion_tokens)
+
+ # Set Span attributes
+ self._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
+ self._span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
+ SemanticConvetion.GEN_AI_SYSTEM_AI21)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
+ gen_ai_endpoint)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
+ self._response_id)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
+ environment)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
+ application_name)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
+ self._kwargs.get("model", "jamba-1.5-mini"))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
+ self._kwargs.get("top_p", 1.0))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
+ self._kwargs.get("max_tokens", -1))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
+ self._kwargs.get("temperature", 1.0))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
+ True)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
+ self._prompt_tokens)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
+ self._completion_tokens)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
+ self._prompt_tokens + self._completion_tokens)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
+ cost)
+ if trace_content:
+ self._span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
+ },
+ )
+ self._span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: self._llmresponse,
+ },
+ )
+
+ self._span.set_status(Status(StatusCode.OK))
+
+ if disable_metrics is False:
+ attributes = {
+ TELEMETRY_SDK_NAME:
+ "openlit",
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
+ application_name,
+ SemanticConvetion.GEN_AI_SYSTEM:
+ SemanticConvetion.GEN_AI_SYSTEM_AI21,
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
+ environment,
+ SemanticConvetion.GEN_AI_TYPE:
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
+ self._kwargs.get("model", "jamba-1.5-mini")
+ }
+
+ metrics["genai_requests"].add(1, attributes)
+ metrics["genai_total_tokens"].add(
+ self._prompt_tokens + self._completion_tokens, attributes
+ )
+ metrics["genai_completion_tokens"].add(self._completion_tokens, attributes)
+ metrics["genai_prompt_tokens"].add(self._prompt_tokens, attributes)
+ metrics["genai_cost"].record(cost, attributes)
+
+ except Exception as e:
+ handle_exception(self._span, e)
+ logger.error("Error in trace creation: %s", e)
+ finally:
+ self._span.end()
+ raise
+
+ async def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the 'chat.completions' API call to add telemetry.
+
+ This collects metrics such as execution time, cost, and token usage, and handles errors
+ gracefully, adding details to the trace for observability.
+
+ Args:
+ wrapped: The original 'chat.completions' method to be wrapped.
+ instance: The instance of the class where the original method is defined.
+ args: Positional arguments for the 'chat.completions' method.
+ kwargs: Keyword arguments for the 'chat.completions' method.
+
+ Returns:
+ The response from the original 'chat.completions' method.
+ """
+
+ # Check if streaming is enabled for the API call
+ streaming = kwargs.get("stream", False)
+ # pylint: disable=no-else-return
+ if streaming:
+ # Special handling for streaming response to accommodate the nature of data flow
+ awaited_wrapped = await wrapped(*args, **kwargs)
+ span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
+
+ return TracedAsyncStream(awaited_wrapped, span, kwargs)
+
+ # Handling for non-streaming responses
+ else:
+ # pylint: disable=line-too-long
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
+ response = await wrapped(*args, **kwargs)
+
+ response_dict = response_as_dict(response)
+
+ try:
+ # Format 'messages' into a single string
+ message_prompt = kwargs.get("messages", "")
+ formatted_messages = []
+ for message in message_prompt:
+ role = message.role
+ content = message.content
+
+ if isinstance(content, list):
+ content_str = ", ".join(
+ # pylint: disable=line-too-long
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
+ if "type" in item else f'text: {item["text"]}'
+ for item in content
+ )
+ formatted_messages.append(f"{role}: {content_str}")
+ else:
+ formatted_messages.append(f"{role}: {content}")
+ prompt = "\n".join(formatted_messages)
+
+ # Set base span attribues
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
+ SemanticConvetion.GEN_AI_SYSTEM_AI21)
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
+ gen_ai_endpoint)
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
+ response_dict.get("id"))
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
+ environment)
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
+ application_name)
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
+ kwargs.get("model", "jamba-1.5-mini"))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TOP_P,
+ kwargs.get("top_p", 1.0))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MAX_TOKENS,
+ kwargs.get("max_tokens", -1))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
+ kwargs.get("temperature", 1.0))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
+ False)
+ if trace_content:
+ span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
+ },
+ )
+
+ # Set span attributes when tools is not passed to the function call
+ if "tools" not in kwargs:
+ # Calculate cost of the operation
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
+ pricing_info, response_dict.get('usage', {}).get('prompt_tokens', None),
+ response_dict.get('usage', {}).get('completion_tokens', None))
+
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
+ response_dict.get('usage', {}).get('prompt_tokens', None))
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
+ response_dict.get('usage', {}).get('completion_tokens', None))
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
+ response_dict.get('usage', {}).get('total_tokens', None))
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_FINISH_REASON,
+ [response_dict.get('choices', [])[0].get('finish_reason', None)])
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
+ cost)
+
+ # Set span attributes for when n = 1 (default)
+ if "n" not in kwargs or kwargs["n"] == 1:
+ if trace_content:
+ span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices', [])[0].get("message").get("content"),
+ },
+ )
+
+ # Set span attributes for when n > 0
+ else:
+ i = 0
+ while i < kwargs["n"] and trace_content is True:
+ attribute_name = f"gen_ai.content.completion.{i}"
+ span.add_event(
+ name=attribute_name,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices')[i].get("message").get("content"),
+ },
+ )
+ i += 1
+
+ # Return original response
+ return response
+
+ # Set span attributes when tools is passed to the function call
+ elif "tools" in kwargs:
+ # Calculate cost of the operation
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
+ pricing_info, response_dict.get('usage').get('prompt_tokens'),
+ response_dict.get('usage').get('completion_tokens'))
+ span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: "Function called with tools",
+ },
+ )
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
+ response_dict.get('usage').get('prompt_tokens'))
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
+ response_dict.get('usage').get('completion_tokens'))
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
+ response_dict.get('usage').get('total_tokens'))
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
+ cost)
+
+ span.set_status(Status(StatusCode.OK))
+
+ if disable_metrics is False:
+ attributes = {
+ TELEMETRY_SDK_NAME:
+ "openlit",
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
+ application_name,
+ SemanticConvetion.GEN_AI_SYSTEM:
+ SemanticConvetion.GEN_AI_SYSTEM_AI21,
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
+ environment,
+ SemanticConvetion.GEN_AI_TYPE:
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
+ kwargs.get("model", "jamba-1.5-mini")
+ }
+
+ metrics["genai_requests"].add(1, attributes)
+ metrics["genai_total_tokens"].add(response_dict.get('usage').get('total_tokens'), attributes)
+ metrics["genai_completion_tokens"].add(response_dict.get('usage').get('completion_tokens'), attributes)
+ metrics["genai_prompt_tokens"].add(response_dict.get('usage').get('prompt_tokens'), attributes)
+ metrics["genai_cost"].record(cost, attributes)
+
+ # Return original response
+ return response
+
+ except Exception as e:
+ handle_exception(span, e)
+ logger.error("Error in trace creation: %s", e)
+
+ # Return original response
+ return response
+
+ return wrapper
+
+def async_chat_rag(gen_ai_endpoint, version, environment, application_name,
+ tracer, pricing_info, trace_content, metrics, disable_metrics):
+ """
+ Generates a telemetry wrapper for chat completions to collect metrics.
+
+ Args:
+ gen_ai_endpoint: Endpoint identifier for logging and tracing.
+ version: Version of the monitoring package.
+ environment: Deployment environment (e.g., production, staging).
+ application_name: Name of the application using the AI21 SDK.
+ tracer: OpenTelemetry tracer for creating spans.
+ pricing_info: Information used for calculating the cost of AI21 usage.
+ trace_content: Flag indicating whether to trace the actual content.
+
+ Returns:
+ A function that wraps the chat completions method to add telemetry.
+ """
+
+ async def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the 'chat.completions' API call to add telemetry.
+
+ This collects metrics such as execution time, cost, and token usage, and handles errors
+ gracefully, adding details to the trace for observability.
+
+ Args:
+ wrapped: The original 'chat.completions' method to be wrapped.
+ instance: The instance of the class where the original method is defined.
+ args: Positional arguments for the 'chat.completions' method.
+ kwargs: Keyword arguments for the 'chat.completions' method.
+
+ Returns:
+ The response from the original 'chat.completions' method.
+ """
+
+ # Check if streaming is enabled for the API call
+ streaming = kwargs.get("stream", False)
+
+ # pylint: disable=no-else-return
+ if streaming:
+ # # Special handling for streaming response to accommodate the nature of data flow
+ # awaited_wrapped = wrapped(*args, **kwargs)
+ # span = tracer.start_span(gen_ai_endpoint, kind=SpanKind.CLIENT)
+
+ # return TracedSyncStream(awaited_wrapped, span, kwargs)
+
+ return
+
+ # Handling for non-streaming responses
+ else:
+ # pylint: disable=line-too-long
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
+ response = await wrapped(*args, **kwargs)
+
+ response_dict = response_as_dict(response)
+
+ try:
+ # Format 'messages' into a single string
+ message_prompt = kwargs.get("messages", "")
+ formatted_messages = []
+ for message in message_prompt:
+ role = message.role
+ content = message.content
+
+ if isinstance(content, list):
+ content_str = ", ".join(
+ # pylint: disable=line-too-long
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
+ if "type" in item else f'text: {item["text"]}'
+ for item in content
+ )
+ formatted_messages.append(f"{role}: {content_str}")
+ else:
+ formatted_messages.append(f"{role}: {content}")
+ prompt = "\n".join(formatted_messages)
+
+ # Set base span attribues
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
+ SemanticConvetion.GEN_AI_SYSTEM_AI21)
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
+ gen_ai_endpoint)
+ span.set_attribute(SemanticConvetion.GEN_AI_RESPONSE_ID,
+ response_dict.get("id"))
+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,
+ environment)
+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,
+ application_name)
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_MODEL,
+ kwargs.get("model", "jamba-1.5-mini"))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
+ False)
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_MAX_SEGMENTS,
+ kwargs.get("max_segments", -1))
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_STRATEGY,
+ kwargs.get("retrieval_strategy", "segments"))
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_SIMILARITY_THRESHOLD,
+ kwargs.get("retrieval_similarity_threshold", -1))
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_MAX_NEIGHBORS,
+ kwargs.get("max_neighbors", -1))
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_FILE_IDS,
+ str(kwargs.get("file_ids", "")))
+ span.set_attribute(SemanticConvetion.GEN_AI_RAG_DOCUMENTS_PATH,
+ kwargs.get("path", ""))
+
+ if trace_content:
+ span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_PROMPT_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_PROMPT: prompt,
+ },
+ )
+ prompt_tokens = general_tokens(prompt)
+
+
+ # Set span attributes when tools is not passed to the function call
+ if "tools" not in kwargs:
+ prompt_tokens = general_tokens(prompt)
+
+ # Set span attributes for when n = 1 (default)
+ if "n" not in kwargs or kwargs["n"] == 1:
+ completion_tokens = general_tokens(response_dict.get('choices', [])[0].get("content"))
+ if trace_content:
+ span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices', [])[0].get("content"),
+ },
+ )
+
+ # Set span attributes for when n > 0
+ else:
+ i = 0
+ completion_tokens = 0
+ while i < kwargs["n"] and trace_content is True:
+ completion_tokens += general_tokens(response_dict.get('choices')[i].get("message").get("content"))
+ attribute_name = f"gen_ai.content.completion.{i}"
+ span.add_event(
+ name=attribute_name,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: response_dict.get('choices')[i].get("message").get("content"),
+ },
+ )
+ i += 1
+
+ # Return original response
+ return response
+
+ # Set span attributes when tools is passed to the function call
+ elif "tools" in kwargs:
+ completion_tokens = -1
+ # Calculate cost of the operation
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
+ pricing_info, response_dict.get('usage').get('prompt_tokens'),
+ response_dict.get('usage').get('completion_tokens'))
+ span.add_event(
+ name=SemanticConvetion.GEN_AI_CONTENT_COMPLETION_EVENT,
+ attributes={
+ SemanticConvetion.GEN_AI_CONTENT_COMPLETION: "Function called with tools",
+ },
+ )
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
+ prompt_tokens)
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
+ completion_tokens)
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
+ prompt_tokens + completion_tokens)
+
+ # Calculate cost of the operation
+ cost = get_chat_model_cost(kwargs.get("model", "jamba-1.5-mini"),
+ pricing_info, prompt_tokens,
+ completion_tokens)
+ span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COST,
+ cost)
+
+ span.set_status(Status(StatusCode.OK))
+
+ if disable_metrics is False:
+ attributes = {
+ TELEMETRY_SDK_NAME:
+ "openlit",
+ SemanticConvetion.GEN_AI_APPLICATION_NAME:
+ application_name,
+ SemanticConvetion.GEN_AI_SYSTEM:
+ SemanticConvetion.GEN_AI_SYSTEM_AI21,
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
+ environment,
+ SemanticConvetion.GEN_AI_TYPE:
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
+ kwargs.get("model", "jamba-1.5-mini")
+ }
+
+ metrics["genai_requests"].add(1, attributes)
+ metrics["genai_total_tokens"].add(prompt_tokens + completion_tokens, attributes)
+ metrics["genai_completion_tokens"].add(completion_tokens, attributes)
+ metrics["genai_prompt_tokens"].add(prompt_tokens, attributes)
+ metrics["genai_cost"].record(cost, attributes)
+
+ # Return original response
+ return response
+
+ except Exception as e:
+ handle_exception(span, e)
+ logger.error("Error in trace creation: %s", e)
+
+ # Return original response
+ return response
+
+ return wrapper
diff --git a/sdk/python/src/openlit/semcov/__init__.py b/sdk/python/src/openlit/semcov/__init__.py
index b540fbed..78674021 100644
--- a/sdk/python/src/openlit/semcov/__init__.py
+++ b/sdk/python/src/openlit/semcov/__init__.py
@@ -76,6 +76,14 @@ class SemanticConvetion:
GEN_AI_CONTENT_COMPLETION = "gen_ai.completion"
GEN_AI_CONTENT_REVISED_PROMPT = "gen_ai.content.revised_prompt"
+ # GenAI Rag
+ GEN_AI_RAG_MAX_SEGMENTS = "gen_ai.rag.max_segments"
+ GEN_AI_RAG_STRATEGY = "gen_ai.rag.strategy"
+ GEN_AI_RAG_SIMILARITY_THRESHOLD = "gen_ai.rag.similarity_threshold"
+ GEN_AI_RAG_MAX_NEIGHBORS = "gen_ai.rag.max_neighbors"
+ GEN_AI_RAG_DOCUMENTS_PATH = "gen_ai.rag.documents_path"
+ GEN_AI_RAG_FILE_IDS = "gen_ai.rag.file_ids"
+
# GenAI Evaluation Metrics
GEN_AI_EVAL_CONTEXT_RELEVANCY = "gen_ai.eval.context_relevancy"
GEN_AI_EVAL_ANSWER_RELEVANCY = "gen_ai.eval.answer_relevancy"
@@ -119,6 +127,7 @@ class SemanticConvetion:
GEN_AI_SYSTEM_DYNAMIQ = "dynamiq"
GEN_AI_SYSTEM_PHIDATA = "phidata"
GEN_AI_SYSTEM_JULEP = "julep"
+ GEN_AI_SYSTEM_AI21 = "ai21"
# Vector DB
DB_OPERATION_API_ENDPOINT = "db.operation.api_endpoint"
diff --git a/sdk/python/tests/requirements.txt b/sdk/python/tests/requirements.txt
index 37c3aef7..b26881e5 100644
--- a/sdk/python/tests/requirements.txt
+++ b/sdk/python/tests/requirements.txt
@@ -22,6 +22,7 @@ reka-api
multion
mem0ai
julep
+ai21
# Vector DBs
chromadb
diff --git a/sdk/python/tests/test_ai21.py b/sdk/python/tests/test_ai21.py
new file mode 100644
index 00000000..bd1ce73f
--- /dev/null
+++ b/sdk/python/tests/test_ai21.py
@@ -0,0 +1,120 @@
+# pylint: disable=duplicate-code, no-name-in-module, import-error
+"""
+This module contains tests for AI21 functionality using the AI21 Python library.
+
+Tests cover various API endpoints, including chat and embeddings.
+These tests validate integration with OpenLIT.
+
+Environment Variables:
+ - AI21_API_KEY: AI21 API key for authentication.
+
+Note: Ensure the environment is properly configured for AI21 access and OpenLIT monitoring
+prior to running these tests.
+"""
+
+import pytest
+from ai21 import AI21Client, AsyncAI21Client
+from ai21.models.chat import ChatMessage
+import openlit
+
+# Initialize synchronous AI21 client
+sync_client = AI21Client()
+
+# Initialize synchronous AI21 client
+async_client = AsyncAI21Client()
+
+# Initialize environment and application name for OpenLIT monitoring
+openlit.init(environment="openlit-python-testing", application_name="openlit-python-ai21-test")
+
+MESSAGES = [
+ ChatMessage(content="say hi", role="user"),
+]
+
+def test_sync_ai21_chat():
+ """
+ Tests synchronous chat.
+
+ Raises:
+ AssertionError: If the chat response object is not as expected.
+ """
+
+ response = sync_client.chat.completions.create(
+ messages=MESSAGES,
+ model="jamba-1.5-mini",
+ max_tokens=1,
+ )
+ assert isinstance(response.id, str)
+
+def test_sync_ai21_chat_stream():
+ """
+ Tests synchronous chat streaming.
+
+ Raises:
+ AssertionError: If the streaming chat response object is not as expected.
+ """
+
+ responses = sync_client.chat.completions.create(
+ messages=MESSAGES,
+ model="jamba-1.5-mini",
+ stream=True,
+ max_tokens=1,
+ )
+ for response in responses:
+ assert isinstance(response.id, str)
+ return
+
+def test_sync_ai21_chat_rag():
+ """
+ Tests synchronous chat rag.
+
+ Raises:
+ AssertionError: If the streaming chat rag response object is not as expected.
+ """
+
+ response = sync_client.beta.conversational_rag.create(
+ messages=MESSAGES,
+ file_ids=[],
+ max_segments=15,
+ retrieval_strategy="segments",
+ retrieval_similarity_threshold=0.8,
+ max_neighbors=1,
+ max_tokens=1,
+ )
+ assert isinstance(response.id, str)
+
+async def test_async_ai21_test():
+ """
+ Tests asynchronous chat stream and rag operations.
+
+ Raises:
+ AssertionError: If the response object is not as expected.
+ """
+
+ response = await async_client.chat.completions.create(
+ messages=MESSAGES,
+ model="jamba-1.5-mini",
+ max_tokens=1,
+ )
+ assert isinstance(response.id, str)
+
+ responses = await async_client.chat.completions.create(
+ messages=MESSAGES,
+ model="jamba-1.5-mini",
+ stream=True,
+ max_tokens=1,
+ )
+ async for text in responses:
+ assert isinstance(text.id, str)
+ return
+
+ response = await async_client.beta.conversational_rag.create(
+ messages=MESSAGES,
+ file_ids=[],
+ max_segments=15,
+ retrieval_strategy="segments",
+ retrieval_similarity_threshold=0.8,
+ max_neighbors=1,
+ max_tokens=1,
+ )
+ assert isinstance(response.id, str)