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]: Add OpenTelemetry Instrumentation for LiteLLM and CrewAI (#505)

Patcherce9b73e8c79c
diff --git a/docs/images/docs-crewai-banner.gif b/docs/images/docs-crewai-banner.gif
new file mode 100644
index 00000000..f36caa36
Binary files /dev/null and b/docs/images/docs-crewai-banner.gif differ
diff --git a/docs/latest/integrations/crewai.mdx b/docs/latest/integrations/crewai.mdx
new file mode 100644
index 00000000..980676d7
--- /dev/null
+++ b/docs/latest/integrations/crewai.mdx
@@ -0,0 +1,75 @@
+---
+title: 'Monitor CrewAI using OpenTelemetry'
+sidebarTitle: 'CrewAI'
+---
+
+<Frame>
+ <img src="/images/docs-crewai-banner.gif" />
+</Frame>
+
+OpenLIT uses OpenTelemetry Auto-Instrumentation to help you monitor LLM applications built using Haystack. This includes tracking performance and operation stats.
+
+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.
+
+## Get Started
+
+<Steps>
+ <Step title="Install OpenLIT">
+ Open your command line or terminal and run:
+ ```shell
+ pip install openlit
+ ```
+ </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:
+
+ ```python
+ import openlit
+
+ openlit.init(
+ 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>
+ <Tab title="Setup using Environment Variables">
+
+ Add the following two lines to your application code:
+
+ ```python
+ import openlit
+
+ openlit.init()
+ ```
+
+ 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).
+ </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 f52dffc8..8bf6b0c8 100644
--- a/docs/latest/integrations/introduction.mdx
+++ b/docs/latest/integrations/introduction.mdx
@@ -766,6 +766,18 @@ Start integrating and monitoring your applications with OpenLIT effortlessly. Ch
}
>
</Card>
+ <Card
+ title="CrewAI"
+ href="/latest/integrations/crewai"
+ iconType="duotone"
+ icon={
+ <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 480">
+ <path d="M0 0 C0 0.66 0 1.32 0 2 C0.59530518 2.114646 1.19061035 2.22929199 1.80395508 2.34741211 C5.41745308 3.42121757 7.92082804 6.10133181 10.6875 8.5625 C11.61199951 9.37243408 11.61199951 9.37243408 12.55517578 10.19873047 C13.79408156 11.28564311 15.03045095 12.37545423 16.26416016 13.46826172 C17.80375153 14.8268266 19.35972378 16.1667777 20.91796875 17.50390625 C21.72878906 18.20386719 22.53960937 18.90382812 23.375 19.625 C24.43847656 20.54152344 24.43847656 20.54152344 25.5234375 21.4765625 C27 23 27 23 27 25 C27.66 25 28.32 25 29 25 C51.14784149 48.7266082 60.15767166 76.02286571 59.14794922 108.03759766 C58.43392079 122.33466189 54.67505428 135.54901965 50 149 C49.55817207 150.30584699 49.11674168 151.61182857 48.67578125 152.91796875 C46.42706687 159.42292484 43.90061106 165.68672899 40.91796875 171.890625 C39.86698782 173.92223453 39.86698782 173.92223453 40 176 C40.96679688 176.15855469 41.93359375 176.31710938 42.9296875 176.48046875 C57.89687839 179.09225802 70.93771718 185.16176601 80 198 C92.12243583 215.9229562 94.12688849 240.39783923 90.74609375 261.2421875 C88.03744265 274.88471296 83.71763921 286.83152944 77 299 C76.61465088 299.71824951 76.22930176 300.43649902 75.83227539 301.17651367 C72.99444104 306.40941961 69.88442682 311.33605681 66.4375 316.1875 C65.92590332 316.91146973 65.41430664 317.63543945 64.88720703 318.38134766 C60.39535279 324.63927686 55.50303836 330.47943263 50.3984375 336.2421875 C47.94354618 338.94659536 47.94354618 338.94659536 46 342 C45.34 342 44.68 342 44 342 C43.75507813 342.57105469 43.51015625 343.14210938 43.2578125 343.73046875 C39.22636498 351.00460232 31.28609429 356.66674527 25 362 C24.41863281 362.50917969 23.83726562 363.01835937 23.23828125 363.54296875 C19.23897059 367 19.23897059 367 17 367 C17 367.66 17 368.32 17 369 C15.64575195 370.20166016 15.64575195 370.20166016 13.73828125 371.5390625 C12.68761475 372.280354 12.68761475 372.280354 11.61572266 373.03662109 C10.85565918 373.56078613 10.0955957 374.08495117 9.3125 374.625 C8.5395459 375.16334473 7.7665918 375.70168945 6.97021484 376.25634766 C-48.18941549 414.37719893 -115.02623708 434.65626241 -182 423 C-201.21934969 419.22351264 -219.47414821 412.60576769 -236 402 C-236.78375 401.50886719 -237.5675 401.01773437 -238.375 400.51171875 C-273.69459747 377.76246413 -296.37566879 342.92622436 -305.36572266 302.24511719 C-317.69554878 239.16272733 -299.44411241 174.32663078 -267 120 C-266.20212371 118.5241736 -265.40959071 117.04543208 -264.625 115.5625 C-254.88107482 98.03673697 -243.03549908 81.19432154 -229.7734375 66.17578125 C-227.38315718 63.46835705 -225.15429687 60.66454498 -222.9375 57.8125 C-218.33715241 52.13474759 -213.21085075 46.99235665 -208.0625 41.8125 C-207.20841553 40.94923096 -206.35433105 40.08596191 -205.47436523 39.1965332 C-204.66942627 38.39562256 -203.8644873 37.59471191 -203.03515625 36.76953125 C-202.3069165 36.04354736 -201.57867676 35.31756348 -200.82836914 34.56958008 C-199 33 -199 33 -197 33 C-197 32.34 -197 31.68 -197 31 C-195.49576101 29.60126876 -193.91734851 28.28204731 -192.3125 27 C-191.31605469 26.20207031 -190.31960937 25.40414062 -189.29296875 24.58203125 C-184.87348531 21.10320362 -180.41696227 17.67313706 -175.9453125 14.26171875 C-174.1215078 12.8612109 -172.31936003 11.43135031 -170.5546875 9.95703125 C-167.53408805 7.6430858 -164.32245616 5.83091649 -161 4 C-159.69302607 3.2478015 -158.38707097 2.49383056 -157.08203125 1.73828125 C-107.65240613 -26.50721882 -48.68782437 -36.43631301 0 0 Z " fill="#471A18" transform="translate(337,29)"/>
+ <path d="M0 0 C0.721875 0.53109375 1.44375 1.0621875 2.1875 1.609375 C19.24357464 14.51987594 36.30198529 31.29541865 41 53 C42.52534709 73.86258815 38.88679649 91.3205145 31.01708984 110.50976562 C29.98034388 113.04812589 28.98076317 115.5994332 27.98046875 118.15234375 C26.27139554 122.42606965 24.35139538 126.53230269 22.25 130.625 C21.91000977 131.29740723 21.57001953 131.96981445 21.21972656 132.66259766 C19.79200851 135.48591339 18.3545929 138.30425544 16.91796875 141.12304688 C12.92415127 148.9727136 9.10518559 156.74803043 6 165 C5.0085224 167.58705222 4.00856322 170.16967028 3 172.75 C2.76265137 173.37656494 2.52530273 174.00312988 2.28076172 174.64868164 C-0.36139195 181.40135107 -3.3754848 186.6877424 -10 190 C-21.81932831 191.37892164 -30.77356081 185.80531685 -40 179 C-41.00740234 178.27296875 -41.00740234 178.27296875 -42.03515625 177.53125 C-51.6418685 170.00343903 -59.74845378 157.26742087 -61.71484375 145.14453125 C-62.9242655 131.80775715 -62.34138592 119.76693691 -58 107 C-57.52034721 105.50275981 -57.04120713 104.00535531 -56.5625 102.5078125 C-50.94003364 85.3759905 -43.60294234 68.79131808 -35.31665039 52.7890625 C-32.79765676 47.45307451 -31.43942421 42.94210337 -32 37 C-32.98048938 34.93597315 -32.98048938 34.93597315 -35 34 C-40.32156806 33.40871466 -43.13235539 34.88374351 -47.5625 37.75 C-48.65691406 38.44609375 -49.75132812 39.1421875 -50.87890625 39.859375 C-58.743425 45.25331276 -64.78650662 51.82144039 -71.01171875 58.98828125 C-71.99591797 59.98408203 -71.99591797 59.98408203 -73 61 C-73.66 61 -74.32 61 -75 61 C-75.25007812 61.57234375 -75.50015625 62.1446875 -75.7578125 62.734375 C-77.17579905 65.32063978 -78.83810894 67.11611413 -80.875 69.25 C-87.13613114 76.08397941 -92.54006944 83.52136296 -98 91 C-98.45584473 91.61987793 -98.91168945 92.23975586 -99.38134766 92.87841797 C-104.91075518 100.40778063 -110.06485802 108.06439996 -114.8515625 116.09472656 C-116.15119525 118.25083497 -117.48118702 120.38675136 -118.8125 122.5234375 C-125.6609158 133.60130234 -131.56383607 144.88719026 -136.95849609 156.73779297 C-137.84500909 158.66335074 -138.77187598 160.57024655 -139.70703125 162.47265625 C-142.90106516 169.00399208 -145.40708841 175.68947464 -147.75 182.5625 C-148.19122192 183.83867187 -148.19122192 183.83867187 -148.64135742 185.140625 C-152.37391307 196.43449742 -153.33087246 207.46928586 -153.26074219 219.2902832 C-153.25003031 221.43144142 -153.26069704 223.5717578 -153.2734375 225.71289062 C-153.29173635 243.130391 -151.18212626 258.71230407 -139 272 C-122.99420501 284.37485076 -103.03302724 281.48077443 -84.20898438 279.26025391 C-82.41692616 279.04912061 -80.62277185 278.85583203 -78.828125 278.66796875 C-33.59577577 272.7197841 6.33698333 242.64429973 33.90625 207.84375 C36.05858494 204.92042942 38.06279143 201.9268796 40.06738281 198.90161133 C49.52358888 184.69957586 49.52358888 184.69957586 58.625 181.875 C63.01796601 182.03770244 64.72484977 183.08875535 68 186 C73.01359074 192.805333 74.37000514 199.89608067 74.3125 208.1875 C74.30686035 209.03610596 74.3012207 209.88471191 74.29541016 210.7590332 C74.16954421 217.27602277 73.27239189 222.86882944 71 229 C70.58621094 230.24136719 70.17242187 231.48273438 69.74609375 232.76171875 C66.60122729 241.94922937 62.52924094 249.966759 57 258 C56.33355469 258.97195313 55.66710937 259.94390625 54.98046875 260.9453125 C48.72866128 269.64448802 41.42483281 277.3044349 34 285 C32.75669922 286.30517578 32.75669922 286.30517578 31.48828125 287.63671875 C26.03491675 293.24673285 20.1357022 298.15559169 14 303 C13.05898438 303.76957031 12.11796875 304.53914063 11.1484375 305.33203125 C-16.53843332 327.47437367 -48.66263437 341.15680711 -83 349 C-84.19471924 349.27336182 -84.19471924 349.27336182 -85.41357422 349.55224609 C-97.17516016 352.09481307 -108.95623795 352.27903628 -120.9375 352.3125 C-122.05989075 352.31814972 -122.05989075 352.31814972 -123.20495605 352.32391357 C-132.66160522 352.34805225 -141.67519733 351.74793029 -151 350 C-152.25554687 349.78859375 -153.51109375 349.5771875 -154.8046875 349.359375 C-181.68657771 344.02403801 -206.34900888 328.62818955 -223 307 C-223.6084375 306.23042969 -224.216875 305.46085937 -224.84375 304.66796875 C-236.23255854 289.47426281 -244.03171238 268.83932433 -246 250 C-246.16435547 248.49759766 -246.16435547 248.49759766 -246.33203125 246.96484375 C-246.6586023 243.31160225 -246.85779771 239.66399578 -247 236 C-247.03399902 235.19723633 -247.06799805 234.39447266 -247.10302734 233.56738281 C-248.17571588 204.32709133 -242.64525344 174.85015965 -230.87597656 148.015625 C-229.83700741 145.6249535 -228.83677483 143.21937899 -227.8359375 140.8125 C-223.98585976 131.6069227 -220.05486937 122.61920034 -215 114 C-214.03050857 112.27446484 -213.06102802 110.54892356 -212.09179688 108.82324219 C-208.27962393 102.07056013 -204.2121575 95.50969796 -200 89 C-199.4121875 88.0615625 -198.824375 87.123125 -198.21875 86.15625 C-194.71251919 80.55858326 -191.06696322 75.20213756 -187 70 C-185.79537109 68.44152344 -185.79537109 68.44152344 -184.56640625 66.8515625 C-179.78861592 60.69561324 -174.92649197 54.61129171 -169.9375 48.625 C-169.47255127 48.05950439 -169.00760254 47.49400879 -168.52856445 46.91137695 C-167.39740956 45.56832759 -166.20391653 44.27823236 -165 43 C-164.34 43 -163.68 43 -163 43 C-162.62875 42.071875 -162.62875 42.071875 -162.25 41.125 C-160.76259631 38.59641373 -159.56321991 38.28160996 -157 37 C-156.71511719 36.401875 -156.43023437 35.80375 -156.13671875 35.1875 C-149.24983248 21.93438553 -128.54505975 10.54905096 -116 3 C-115.43458496 2.65485352 -114.86916992 2.30970703 -114.28662109 1.95410156 C-77.44586536 -20.42137882 -36.22485271 -26.88563287 0 0 Z " fill="#FDFDFD" transform="translate(315,63)"/>
+ </svg>
+ }
+ >
+ </Card>
</CardGroup>
### GPUs
diff --git a/sdk/python/README.md b/sdk/python/README.md
index 5114a6a9..7b1ec0a8 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -32,16 +32,16 @@ This project proudly follows and maintains the [Semantic Conventions](https://gi
## Auto Instrumentation Capabilities
-| LLMs | Vector DBs | Frameworks | GPUs |
-|--------------------------------------------------------------------------|----------------------------------------------|----------------------------------------------|---------------|
-| [✅ OpenAI](https://docs.openlit.io/latest/integrations/openai) | [✅ ChromaDB](https://docs.openlit.io/latest/integrations/chromadb) | [✅ Langchain](https://docs.openlit.io/latest/integrations/langchain) | [✅ NVIDIA](https://docs.openlit.io/latest/integrations/nvidia-gpu) |
-| [✅ Ollama](https://docs.openlit.io/latest/integrations/ollama) | [✅ Pinecone](https://docs.openlit.io/latest/integrations/pinecone) | [✅ LiteLLM](https://docs.openlit.io/latest/integrations/litellm) | [✅ AMD](#) |
-| [✅ Anthropic](https://docs.openlit.io/latest/integrations/anthropic) | [✅ Qdrant](https://docs.openlit.io/latest/integrations/qdrant) | [✅ LlamaIndex](https://docs.openlit.io/latest/integrations/llama-index) | |
-| [✅ GPT4All](https://docs.openlit.io/latest/integrations/gpt4all) | [✅ Milvus](https://docs.openlit.io/latest/integrations/milvus) | [✅ Haystack](https://docs.openlit.io/latest/integrations/haystack) | |
-| [✅ Cohere](https://docs.openlit.io/latest/integrations/cohere) | | [✅ EmbedChain](https://docs.openlit.io/latest/integrations/embedchain) | |
-| [✅ Mistral](https://docs.openlit.io/latest/integrations/mistral) | | [✅ Guardrails](https://docs.openlit.io/latest/integrations/guardrails) | |
-| [✅ Azure OpenAI](https://docs.openlit.io/latest/integrations/azure-openai) | | | |
-| [✅ Azure AI Inference](https://docs.openlit.io/latest/integrations/azure-ai-inference) | | | |
+| LLMs | Vector DBs | Frameworks | GPUs |
+|--------------------------------------------------------------------------|----------------------------------------------|-------------------------------------------------|---------------|
+| [✅ OpenAI](https://docs.openlit.io/latest/integrations/openai) | [✅ ChromaDB](https://docs.openlit.io/latest/integrations/chromadb) | [✅ Langchain](https://docs.openlit.io/latest/integrations/langchain) | [✅ NVIDIA](https://docs.openlit.io/latest/integrations/nvidia-gpu) |
+| [✅ Ollama](https://docs.openlit.io/latest/integrations/ollama) | [✅ Pinecone](https://docs.openlit.io/latest/integrations/pinecone) | [✅ LiteLLM](https://docs.openlit.io/latest/integrations/litellm) | [✅ AMD](#) |
+| [✅ Anthropic](https://docs.openlit.io/latest/integrations/anthropic) | [✅ Qdrant](https://docs.openlit.io/latest/integrations/qdrant) | [✅ LlamaIndex](https://docs.openlit.io/latest/integrations/llama-index) | |
+| [✅ GPT4All](https://docs.openlit.io/latest/integrations/gpt4all) | [✅ Milvus](https://docs.openlit.io/latest/integrations/milvus) | [✅ Haystack](https://docs.openlit.io/latest/integrations/haystack) | |
+| [✅ Cohere](https://docs.openlit.io/latest/integrations/cohere) | | [✅ EmbedChain](https://docs.openlit.io/latest/integrations/embedchain) | |
+| [✅ Mistral](https://docs.openlit.io/latest/integrations/mistral) | | [✅ Guardrails](https://docs.openlit.io/latest/integrations/guardrails) | |
+| [✅ Azure OpenAI](https://docs.openlit.io/latest/integrations/azure-openai) | | [✅ CrewAI](https://docs.openlit.io/latest/integrations/crewai) | |
+| [✅ Azure AI Inference](https://docs.openlit.io/latest/integrations/azure-ai-inference) | |
| [✅ GitHub AI Models](https://docs.openlit.io/latest/integrations/github-models) | | | |
| [✅ HuggingFace Transformers](https://docs.openlit.io/latest/integrations/huggingface) | | | |
| [✅ Amazon Bedrock](https://docs.openlit.io/latest/integrations/bedrock) | | | |
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
index 6fdec26c..c1b6d413 100644
--- a/sdk/python/pyproject.toml
+++ b/sdk/python/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "openlit"
-version = "1.29.4"
+version = "1.30.0"
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 2a2beacd..224e058a 100644
--- a/sdk/python/src/openlit/__init__.py
+++ b/sdk/python/src/openlit/__init__.py
@@ -46,6 +46,8 @@ from openlit.instrumentation.pinecone import PineconeInstrumentor
from openlit.instrumentation.qdrant import QdrantInstrumentor
from openlit.instrumentation.milvus import MilvusInstrumentor
from openlit.instrumentation.transformers import TransformersInstrumentor
+from openlit.instrumentation.litellm import LiteLLMInstrumentor
+from openlit.instrumentation.crewai import CrewAIInstrumentor
from openlit.instrumentation.gpu import GPUInstrumentor
import openlit.guard
import openlit.evals
@@ -228,6 +230,8 @@ def init(environment="default", application_name="default", tracer=None, otlp_en
"qdrant": "qdrant_client",
"milvus": "pymilvus",
"transformers": "transformers",
+ "litellm": "litellm",
+ "crewai": "crewai",
}
invalid_instrumentors = [
@@ -305,6 +309,8 @@ def init(environment="default", application_name="default", tracer=None, otlp_en
"qdrant": QdrantInstrumentor(),
"milvus": MilvusInstrumentor(),
"transformers": TransformersInstrumentor(),
+ "litellm": LiteLLMInstrumentor(),
+ "crewai": CrewAIInstrumentor(),
}
# Initialize and instrument only the enabled instrumentors
diff --git a/sdk/python/src/openlit/instrumentation/crewai/__init__.py b/sdk/python/src/openlit/instrumentation/crewai/__init__.py
new file mode 100644
index 00000000..83b34340
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/crewai/__init__.py
@@ -0,0 +1,50 @@
+# pylint: disable=useless-return, bad-staticmethod-argument, disable=duplicate-code
+"""Initializer of Auto Instrumentation of CrewAI Functions"""
+
+from typing import Collection
+import importlib.metadata
+from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
+from wrapt import wrap_function_wrapper
+
+from openlit.instrumentation.crewai.crewai import (
+ crew_wrap
+)
+
+_instruments = ("crewai >= 0.80.0",)
+
+class CrewAIInstrumentor(BaseInstrumentor):
+ """
+ An instrumentor for CrewAI'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("crewai")
+
+ wrap_function_wrapper(
+ "crewai.agent",
+ "Agent.execute_task",
+ crew_wrap("crewai.agent_execute_task", version, environment, application_name,
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
+ )
+
+ wrap_function_wrapper(
+ "crewai.task",
+ "Task._execute_core",
+ crew_wrap("crewai.task_execute_core", 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/crewai/crewai.py b/sdk/python/src/openlit/instrumentation/crewai/crewai.py
new file mode 100644
index 00000000..03701b46
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/crewai/crewai.py
@@ -0,0 +1,149 @@
+# pylint: disable=duplicate-code, broad-exception-caught, too-many-statements, unused-argument, too-many-branches
+"""
+Module for monitoring LiteLLM calls.
+"""
+
+import logging
+import json
+from opentelemetry.trace import SpanKind, Status, StatusCode
+from opentelemetry.sdk.resources import TELEMETRY_SDK_NAME
+from openlit.__helpers import (
+ handle_exception,
+)
+from openlit.semcov import SemanticConvetion
+
+# Initialize logger for logging potential issues and operations
+logger = logging.getLogger(__name__)
+
+def _parse_tools(tools):
+ result = []
+ for tool in tools:
+ res = {}
+ if hasattr(tool, "name") and tool.name is not None:
+ res["name"] = tool.name
+ if hasattr(tool, "description") and tool.description is not None:
+ res["description"] = tool.description
+ if res:
+ result.append(res)
+ return json.dumps(result)
+
+def crew_wrap(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 OpenAI API.
+ tracer: OpenTelemetry tracer for creating spans.
+ pricing_info: Information used for calculating the cost of OpenAI 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.
+ """
+
+ # pylint: disable=line-too-long
+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:
+ response = wrapped(*args, **kwargs)
+
+ try:
+ # Set base span attribues
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,
+ SemanticConvetion.GEN_AI_SYSTEM_OPENAI)
+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,
+ SemanticConvetion.GEN_AI_TYPE_CHAT)
+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,
+ gen_ai_endpoint)
+
+ instance_class = instance.__class__.__name__
+
+ if instance_class == "Task":
+ task = {}
+ for key, value in instance.__dict__.items():
+ if value is None:
+ continue
+ if key == "tools":
+ value = _parse_tools(value)
+ task[key] = value
+ elif key == "agent":
+ task[key] = value.role
+ else:
+ task[key] = str(value)
+
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_TASK_ID,
+ task.get('id', ''))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_TASK,
+ task.get('description', ''))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_EXPECTED_OUTPUT,
+ task.get('expected_output', ''))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_ACTUAL_OUTPUT,
+ task.get('output', ''))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_HUMAN_INPUT,
+ task.get('human_input', ''))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_TASK_ASSOCIATION,
+ str(task.get('processed_by_agents', '')))
+
+ elif instance_class == "Agent":
+ agent = {}
+ for key, value in instance.__dict__.items():
+ if key == "tools":
+ value = _parse_tools(value)
+ if value is None:
+ continue
+ agent[key] = str(value)
+
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_ID,
+ agent.get('id', ''))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_ROLE,
+ agent.get('role', ''))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_GOAL,
+ agent.get('goal', ''))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_CONTEXT,
+ agent.get('backstory', ''))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_ENABLE_CACHE,
+ agent.get('cache', ''))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_ALLOW_DELEGATION,
+ agent.get('allow_delegation', ''))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_ALLOW_CODE_EXECUTION,
+ agent.get('allow_code_execution', ''))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_MAX_RETRY_LIMIT,
+ agent.get('max_retry_limit', ''))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_TOOLS,
+ str(agent.get('tools', '')))
+ span.set_attribute(SemanticConvetion.GEN_AI_AGENT_TOOL_RESULTS,
+ str(agent.get('tools_results', '')))
+
+ span.set_status(Status(StatusCode.OK))
+
+ # 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/litellm/__init__.py b/sdk/python/src/openlit/instrumentation/litellm/__init__.py
new file mode 100644
index 00000000..e3278a66
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/litellm/__init__.py
@@ -0,0 +1,54 @@
+# pylint: disable=useless-return, bad-staticmethod-argument, disable=duplicate-code
+"""Initializer of Auto Instrumentation of LiteLLM Functions"""
+
+from typing import Collection
+import importlib.metadata
+from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
+from wrapt import wrap_function_wrapper
+
+from openlit.instrumentation.litellm.litellm import (
+ completion
+)
+from openlit.instrumentation.litellm.async_litellm import (
+ acompletion
+)
+
+_instruments = ("litellm >= 1.52.6",)
+
+class LiteLLMInstrumentor(BaseInstrumentor):
+ """
+ An instrumentor for LiteLLM'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("litellm")
+
+ # completion
+ wrap_function_wrapper(
+ "litellm",
+ "completion",
+ completion("litellm.completion", version, environment, application_name,
+ tracer, pricing_info, trace_content, metrics, disable_metrics),
+ )
+
+ wrap_function_wrapper(
+ "litellm",
+ "acompletion",
+ acompletion("litellm.completion", 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/litellm/async_litellm.py b/sdk/python/src/openlit/instrumentation/litellm/async_litellm.py
new file mode 100644
index 00000000..549f7b25
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/litellm/async_litellm.py
@@ -0,0 +1,407 @@
+# pylint: disable=duplicate-code, broad-exception-caught, too-many-statements, unused-argument, too-many-branches
+"""
+Module for monitoring LiteLLM 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,
+ openai_tokens,
+ handle_exception,
+ response_as_dict,
+)
+from openlit.semcov import SemanticConvetion
+
+# Initialize logger for logging potential issues and operations
+logger = logging.getLogger(__name__)
+
+def acompletion(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 OpenAI API.
+ tracer: OpenTelemetry tracer for creating spans.
+ pricing_info: Information used for calculating the cost of OpenAI 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.
+ Wraps the 'openai.AsyncStream' response to collect message IDs and aggregated response.
+
+ 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._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
+ 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 tokens using input prompt and aggregated response
+ prompt_tokens = openai_tokens(prompt,
+ self._kwargs.get("model", "gpt-3.5-turbo"))
+ completion_tokens = openai_tokens(self._llmresponse,
+ self._kwargs.get("model", "gpt-3.5-turbo"))
+
+ # Calculate cost of the operation
+ cost = get_chat_model_cost(self._kwargs.get("model", "gpt-3.5-turbo"),
+ pricing_info, prompt_tokens,
+ 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_OPENAI)
+ 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", "gpt-3.5-turbo"))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
+ self._kwargs.get("user", ""))
+ 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_PRESENCE_PENALTY,
+ self._kwargs.get("presence_penalty", 0.0))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_FREQUENCY_PENALTY,
+ self._kwargs.get("frequency_penalty", 0.0))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
+ self._kwargs.get("seed", ""))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
+ True)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
+ prompt_tokens)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
+ completion_tokens)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
+ prompt_tokens + 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_OPENAI,
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
+ environment,
+ SemanticConvetion.GEN_AI_TYPE:
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
+ self._kwargs.get("model", "gpt-3.5-turbo")
+ }
+
+ 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)
+
+ 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_OPENAI)
+ 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", "gpt-3.5-turbo"))
+ 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_USER,
+ kwargs.get("user", ""))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
+ kwargs.get("temperature", 1.0))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_PRESENCE_PENALTY,
+ kwargs.get("presence_penalty", 0.0))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_FREQUENCY_PENALTY,
+ kwargs.get("frequency_penalty", 0.0))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
+ kwargs.get("seed", ""))
+ 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", "gpt-3.5-turbo"),
+ 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", "gpt-3.5-turbo"),
+ 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_OPENAI,
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
+ environment,
+ SemanticConvetion.GEN_AI_TYPE:
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
+ kwargs.get("model", "gpt-3.5-turbo")
+ }
+
+ 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
diff --git a/sdk/python/src/openlit/instrumentation/litellm/litellm.py b/sdk/python/src/openlit/instrumentation/litellm/litellm.py
new file mode 100644
index 00000000..bfeeb192
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/litellm/litellm.py
@@ -0,0 +1,407 @@
+# pylint: disable=duplicate-code, broad-exception-caught, too-many-statements, unused-argument, too-many-branches
+"""
+Module for monitoring LiteLLM 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,
+ openai_tokens,
+ handle_exception,
+ response_as_dict,
+)
+from openlit.semcov import SemanticConvetion
+
+# Initialize logger for logging potential issues and operations
+logger = logging.getLogger(__name__)
+
+def completion(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 OpenAI API.
+ tracer: OpenTelemetry tracer for creating spans.
+ pricing_info: Information used for calculating the cost of OpenAI 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.
+ Wraps the 'openai.AsyncStream' response to collect message IDs and aggregated response.
+
+ 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._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
+ 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 tokens using input prompt and aggregated response
+ prompt_tokens = openai_tokens(prompt,
+ self._kwargs.get("model", "gpt-3.5-turbo"))
+ completion_tokens = openai_tokens(self._llmresponse,
+ self._kwargs.get("model", "gpt-3.5-turbo"))
+
+ # Calculate cost of the operation
+ cost = get_chat_model_cost(self._kwargs.get("model", "gpt-3.5-turbo"),
+ pricing_info, prompt_tokens,
+ 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_OPENAI)
+ 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", "gpt-3.5-turbo"))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
+ self._kwargs.get("user", ""))
+ 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_PRESENCE_PENALTY,
+ self._kwargs.get("presence_penalty", 0.0))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_FREQUENCY_PENALTY,
+ self._kwargs.get("frequency_penalty", 0.0))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
+ self._kwargs.get("seed", ""))
+ self._span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_IS_STREAM,
+ True)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
+ prompt_tokens)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_COMPLETION_TOKENS,
+ completion_tokens)
+ self._span.set_attribute(SemanticConvetion.GEN_AI_USAGE_TOTAL_TOKENS,
+ prompt_tokens + 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_OPENAI,
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
+ environment,
+ SemanticConvetion.GEN_AI_TYPE:
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
+ self._kwargs.get("model", "gpt-3.5-turbo")
+ }
+
+ 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)
+
+ 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_OPENAI)
+ 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", "gpt-3.5-turbo"))
+ 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_USER,
+ kwargs.get("user", ""))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_TEMPERATURE,
+ kwargs.get("temperature", 1.0))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_PRESENCE_PENALTY,
+ kwargs.get("presence_penalty", 0.0))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_FREQUENCY_PENALTY,
+ kwargs.get("frequency_penalty", 0.0))
+ span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_SEED,
+ kwargs.get("seed", ""))
+ 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", "gpt-3.5-turbo"),
+ 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", "gpt-3.5-turbo"),
+ 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_OPENAI,
+ SemanticConvetion.GEN_AI_ENVIRONMENT:
+ environment,
+ SemanticConvetion.GEN_AI_TYPE:
+ SemanticConvetion.GEN_AI_TYPE_CHAT,
+ SemanticConvetion.GEN_AI_REQUEST_MODEL:
+ kwargs.get("model", "gpt-3.5-turbo")
+ }
+
+ 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
diff --git a/sdk/python/src/openlit/instrumentation/openai/async_openai.py b/sdk/python/src/openlit/instrumentation/openai/async_openai.py
index b83291a4..dc1e536f 100644
--- a/sdk/python/src/openlit/instrumentation/openai/async_openai.py
+++ b/sdk/python/src/openlit/instrumentation/openai/async_openai.py
@@ -468,8 +468,8 @@ def async_embedding(gen_ai_endpoint, version, environment, application_name,
kwargs.get("model", "text-embedding-ada-002"))
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_FORMAT,
kwargs.get("encoding_format", "float"))
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_DIMENSION,
- kwargs.get("dimensions", ""))
+ # span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_DIMENSION,
+ # kwargs.get("dimensions", "null"))
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
kwargs.get("user", ""))
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
diff --git a/sdk/python/src/openlit/instrumentation/openai/openai.py b/sdk/python/src/openlit/instrumentation/openai/openai.py
index 09241126..4f874b2b 100644
--- a/sdk/python/src/openlit/instrumentation/openai/openai.py
+++ b/sdk/python/src/openlit/instrumentation/openai/openai.py
@@ -468,8 +468,8 @@ def embedding(gen_ai_endpoint, version, environment, application_name,
kwargs.get("model", "text-embedding-ada-002"))
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_FORMAT,
kwargs.get("encoding_format", "float"))
- span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_DIMENSION,
- kwargs.get("dimensions", ""))
+ # span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_EMBEDDING_DIMENSION,
+ # kwargs.get("dimensions", "null"))
span.set_attribute(SemanticConvetion.GEN_AI_REQUEST_USER,
kwargs.get("user", ""))
span.set_attribute(SemanticConvetion.GEN_AI_USAGE_PROMPT_TOKENS,
diff --git a/sdk/python/src/openlit/semcov/__init__.py b/sdk/python/src/openlit/semcov/__init__.py
index ce838a8d..9438c503 100644
--- a/sdk/python/src/openlit/semcov/__init__.py
+++ b/sdk/python/src/openlit/semcov/__init__.py
@@ -154,6 +154,24 @@ class SemanticConvetion:
DB_SYSTEM_QDRANT = "qdrant"
DB_SYSTEM_MILVUS = "milvus"
+ # Agents
+ GEN_AI_AGENT_ID = "gen_ai.agent.id"
+ GEN_AI_AGENT_TASK_ID = "gen_ai.agent.task.id"
+ GEN_AI_AGENT_ROLE = "gen_ai.agent.role"
+ GEN_AI_AGENT_GOAL = "gen_ai.agent.goal"
+ GEN_AI_AGENT_CONTEXT = "gen_ai.agent.context"
+ GEN_AI_AGENT_ENABLE_CACHE = "gen_ai.agent.enable_cache"
+ GEN_AI_AGENT_ALLOW_DELEGATION = "gen_ai.agent.allow_delegation"
+ GEN_AI_AGENT_ALLOW_CODE_EXECUTION = "gen_ai.agent.allow_code_execution"
+ GEN_AI_AGENT_MAX_RETRY_LIMIT = "gen_ai.agent.max_retry_limit"
+ GEN_AI_AGENT_TOOLS = "gen_ai.agent.tools"
+ GEN_AI_AGENT_TOOL_RESULTS = "gen_ai.agent.tool_results"
+ GEN_AI_AGENT_TASK = "gen_ai.agent.task"
+ GEN_AI_AGENT_EXPECTED_OUTPUT = "gen_ai.agent.expected_output"
+ GEN_AI_AGENT_ACTUAL_OUTPUT = "gen_ai.agent.actual_output"
+ GEN_AI_AGENT_HUMAN_INPUT = "gen_ai.agent.human_input"
+ GEN_AI_AGENT_TASK_ASSOCIATION = "gen_ai.agent.task_associations"
+
# GPU
GPU_INDEX = "gpu.index"
GPU_UUID = "gpu.uuid"