lmnr 0.2.14__tar.gz → 0.3.0b1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. lmnr-0.3.0b1/PKG-INFO +186 -0
  2. lmnr-0.3.0b1/README.md +164 -0
  3. {lmnr-0.2.14 → lmnr-0.3.0b1}/pyproject.toml +5 -8
  4. lmnr-0.3.0b1/src/lmnr/__init__.py +4 -0
  5. lmnr-0.3.0b1/src/lmnr/sdk/client.py +156 -0
  6. lmnr-0.3.0b1/src/lmnr/sdk/collector.py +177 -0
  7. lmnr-0.3.0b1/src/lmnr/sdk/constants.py +1 -0
  8. lmnr-0.3.0b1/src/lmnr/sdk/context.py +456 -0
  9. lmnr-0.3.0b1/src/lmnr/sdk/decorators.py +277 -0
  10. lmnr-0.3.0b1/src/lmnr/sdk/interface.py +339 -0
  11. lmnr-0.3.0b1/src/lmnr/sdk/providers/__init__.py +2 -0
  12. lmnr-0.3.0b1/src/lmnr/sdk/providers/base.py +28 -0
  13. lmnr-0.3.0b1/src/lmnr/sdk/providers/fallback.py +131 -0
  14. lmnr-0.3.0b1/src/lmnr/sdk/providers/openai.py +140 -0
  15. lmnr-0.3.0b1/src/lmnr/sdk/providers/utils.py +33 -0
  16. lmnr-0.3.0b1/src/lmnr/sdk/tracing_types.py +197 -0
  17. lmnr-0.3.0b1/src/lmnr/sdk/types.py +69 -0
  18. lmnr-0.3.0b1/src/lmnr/sdk/utils.py +102 -0
  19. lmnr-0.2.14/PKG-INFO +0 -187
  20. lmnr-0.2.14/README.md +0 -161
  21. lmnr-0.2.14/src/lmnr/__init__.py +0 -4
  22. lmnr-0.2.14/src/lmnr/cli/__main__.py +0 -4
  23. lmnr-0.2.14/src/lmnr/cli/cli.py +0 -232
  24. lmnr-0.2.14/src/lmnr/cli/parser/__init__.py +0 -0
  25. lmnr-0.2.14/src/lmnr/cli/parser/nodes/__init__.py +0 -45
  26. lmnr-0.2.14/src/lmnr/cli/parser/nodes/code.py +0 -36
  27. lmnr-0.2.14/src/lmnr/cli/parser/nodes/condition.py +0 -30
  28. lmnr-0.2.14/src/lmnr/cli/parser/nodes/input.py +0 -25
  29. lmnr-0.2.14/src/lmnr/cli/parser/nodes/json_extractor.py +0 -29
  30. lmnr-0.2.14/src/lmnr/cli/parser/nodes/llm.py +0 -56
  31. lmnr-0.2.14/src/lmnr/cli/parser/nodes/output.py +0 -27
  32. lmnr-0.2.14/src/lmnr/cli/parser/nodes/router.py +0 -37
  33. lmnr-0.2.14/src/lmnr/cli/parser/nodes/semantic_search.py +0 -53
  34. lmnr-0.2.14/src/lmnr/cli/parser/nodes/types.py +0 -153
  35. lmnr-0.2.14/src/lmnr/cli/parser/parser.py +0 -62
  36. lmnr-0.2.14/src/lmnr/cli/parser/utils.py +0 -49
  37. lmnr-0.2.14/src/lmnr/cli/zip.py +0 -16
  38. lmnr-0.2.14/src/lmnr/sdk/__init__.py +0 -0
  39. lmnr-0.2.14/src/lmnr/sdk/endpoint.py +0 -186
  40. lmnr-0.2.14/src/lmnr/sdk/registry.py +0 -29
  41. lmnr-0.2.14/src/lmnr/sdk/remote_debugger.py +0 -148
  42. lmnr-0.2.14/src/lmnr/types.py +0 -101
  43. {lmnr-0.2.14 → lmnr-0.3.0b1}/LICENSE +0 -0
  44. {lmnr-0.2.14/src/lmnr/cli → lmnr-0.3.0b1/src/lmnr/sdk}/__init__.py +0 -0
lmnr-0.3.0b1/PKG-INFO ADDED
@@ -0,0 +1,186 @@
1
+ Metadata-Version: 2.1
2
+ Name: lmnr
3
+ Version: 0.3.0b1
4
+ Summary: Python SDK for Laminar AI
5
+ License: Apache-2.0
6
+ Author: lmnr.ai
7
+ Requires-Python: >=3.9,<4.0
8
+ Classifier: License :: OSI Approved :: Apache Software License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Dist: backoff (>=2.2.1,<3.0.0)
15
+ Requires-Dist: black (>=24.4.2,<25.0.0)
16
+ Requires-Dist: openai (>=1.41.1,<2.0.0)
17
+ Requires-Dist: pydantic (>=2.7.4,<3.0.0)
18
+ Requires-Dist: python-dotenv (>=1.0.1,<2.0.0)
19
+ Requires-Dist: requests (>=2.32.3,<3.0.0)
20
+ Description-Content-Type: text/markdown
21
+
22
+ # Laminar AI
23
+
24
+ This repo provides core for code generation, Laminar CLI, and Laminar SDK.
25
+
26
+ ## Quickstart
27
+ ```sh
28
+ python3 -m venv .myenv
29
+ source .myenv/bin/activate # or use your favorite env management tool
30
+
31
+ pip install lmnr
32
+ ```
33
+
34
+
35
+ ## Decorator instrumentation example
36
+
37
+ For easy automatic instrumentation, we provide you two simple primitives:
38
+
39
+ - `observe` - a multi-purpose automatic decorator that starts traces and spans when functions are entered, and finishes them when functions return
40
+ - `wrap_llm_call` - a function that takes in your LLM call and return a "decorated" version of it. This does all the same things as `observe`, plus
41
+ a few utilities around LLM-specific things, such as counting tokens and recording model params.
42
+
43
+ You can also import `lmnr_context` in order to interact and have more control over the context of the current span.
44
+
45
+ ```python
46
+ import os
47
+ from openai import OpenAI
48
+
49
+ from lmnr import observe, wrap_llm_call, lmnr_context
50
+ client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
51
+
52
+ @observe() # annotate all functions you want to trace
53
+ def poem_writer(topic="turbulence"):
54
+ prompt = f"write a poem about {topic}"
55
+
56
+ # wrap the actual final call to LLM with `wrap_llm_call`
57
+ response = wrap_llm_call(client.chat.completions.create)(
58
+ model="gpt-4o",
59
+ messages=[
60
+ {"role": "system", "content": "You are a helpful assistant."},
61
+ {"role": "user", "content": prompt},
62
+ ],
63
+ )
64
+
65
+ poem = response.choices[0].message.content
66
+
67
+ if topic in poem:
68
+ lmnr_context.event("topic_alignment") # send an event with a pre-defined name
69
+
70
+ # to trigger an automatic check for a possible event do:
71
+ lmnr_context.check_span_event("excessive_wordiness")
72
+
73
+ return poem
74
+
75
+ if __name__ == "__main__":
76
+ print(poem_writer(topic="laminar flow"))
77
+ ```
78
+
79
+ This gives an advantage of quick instrumentation, but is somewhat limited in flexibility + doesn't really work as expected with threading.
80
+ This is due to the fact that we use `contextvars.ContextVar` for this, and how Python manages them between threads.
81
+
82
+ If you want to instrument your code manually, follow on to the next section
83
+
84
+ ## Manual instrumentation example
85
+
86
+ For manual instrumetation you will need to import the following:
87
+ - `trace` - this is a function to start a trace. It returns a `TraceContext`
88
+ - `TraceContext` - a pointer to the current trace that you can pass around functions as you want.
89
+ - `SpanContext` - a pointer to the current span that you can pass around functions as you want
90
+
91
+ Both `TraceContext` and `SpanContext` expose the following interfaces:
92
+ - `span(name: str, **kwargs)` - create a child span within the current context. Returns `SpanContext`
93
+ - `update(**kwargs)` - update the current trace or span and return it. Returns `TraceContext` or `SpanContext`. Useful when some metadata becomes known later during the program execution
94
+ - `end(**kwargs)` – update the current span, and terminate it
95
+
96
+ In addition, `SpanContext` allows you to:
97
+ - `event(name: str, value: str | int = None)` - emit a custom event at any point
98
+ - `evaluate_event(name: str, data: str)` - register a possible event for automatic checking by Laminar.
99
+
100
+ Example:
101
+
102
+ ```python
103
+ import os
104
+ from openai import OpenAI
105
+
106
+ from lmnr import trace, TraceContext, SpanContext
107
+ client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
108
+
109
+ def poem_writer(t: TraceContext, topic = "turbulence"):
110
+ span: SpanContext = t.span(name="poem_writer", input=None)
111
+
112
+ prompt = f"write a poem about {topic}"
113
+ messages = [
114
+ {"role": "system", "content": "You are a helpful assistant."},
115
+ {"role": "user", "content": prompt},
116
+ ]
117
+ # create a child span within the current `poem_writer` span.
118
+ llm_span = span.span(name="OpenAI completion", input=messages, span_type="LLM")
119
+
120
+ response = client.chat.completions.create(
121
+ model="gpt-4o-mini",
122
+ messages=[
123
+ {"role": "system", "content": "You are a helpful assistant."},
124
+ {"role": "user", "content": "Hello. What is the capital of France?"},
125
+ ],
126
+ )
127
+ poem = response.choices[0].message.content
128
+ if topic in poem:
129
+ llm_span.event("topic_alignment") # send an event with a pre-defined name
130
+
131
+ # note that you can register possible events here as well, not only `llm_span.check_span_event()`
132
+ llm_span.end(output=poem, check_event_names=["excessive_wordiness"])
133
+ span.end(output=poem)
134
+ return poem
135
+
136
+
137
+ t: TraceContext = trace(user_id="user", session_id="session", release="release")
138
+ main(t, topic="laminar flow")
139
+ t.end(success=True)
140
+ ```
141
+
142
+ ## Features
143
+
144
+ - Make Laminar endpoint calls from your Python code
145
+ - Make Laminar endpoint calls that can run your own functions as tools
146
+ - CLI to generate code from pipelines you build on Laminar or execute your own functions while you test your flows in workshop
147
+
148
+ ## Making Laminar pipeline calls
149
+
150
+ After you are ready to use your pipeline in your code, deploy it in Laminar by selecting the target version for the pipeline.
151
+
152
+ Once your pipeline target is set, you can call it from Python in just a few lines.
153
+
154
+ Example use:
155
+
156
+ ```python
157
+ from lmnr import Laminar
158
+
159
+ # for decorator instrumentation, do: `from lmnr inport lmnr_context`
160
+
161
+ l = Laminar('<YOUR_PROJECT_API_KEY>')
162
+ result = l.run( # lmnr_context.run( for decorator instrumentation
163
+ pipeline = 'my_pipeline_name',
164
+ inputs = {'input_node_name': 'some_value'},
165
+ # all environment variables
166
+ env = {'OPENAI_API_KEY': 'sk-some-key'},
167
+ # any metadata to attach to this run's trace
168
+ metadata = {'session_id': 'your_custom_session_id'}
169
+ )
170
+ ```
171
+
172
+ Resulting in:
173
+
174
+ ```python
175
+ >>> result
176
+ PipelineRunResponse(
177
+ outputs={'output': {'value': [ChatMessage(role='user', content='hello')]}},
178
+ # useful to locate your trace
179
+ run_id='53b012d5-5759-48a6-a9c5-0011610e3669'
180
+ )
181
+ ```
182
+
183
+ ## PROJECT_API_KEY
184
+
185
+ Read more [here](https://docs.lmnr.ai/api-reference/introduction#authentication) on how to get `PROJECT_API_KEY`.
186
+
lmnr-0.3.0b1/README.md ADDED
@@ -0,0 +1,164 @@
1
+ # Laminar AI
2
+
3
+ This repo provides core for code generation, Laminar CLI, and Laminar SDK.
4
+
5
+ ## Quickstart
6
+ ```sh
7
+ python3 -m venv .myenv
8
+ source .myenv/bin/activate # or use your favorite env management tool
9
+
10
+ pip install lmnr
11
+ ```
12
+
13
+
14
+ ## Decorator instrumentation example
15
+
16
+ For easy automatic instrumentation, we provide you two simple primitives:
17
+
18
+ - `observe` - a multi-purpose automatic decorator that starts traces and spans when functions are entered, and finishes them when functions return
19
+ - `wrap_llm_call` - a function that takes in your LLM call and return a "decorated" version of it. This does all the same things as `observe`, plus
20
+ a few utilities around LLM-specific things, such as counting tokens and recording model params.
21
+
22
+ You can also import `lmnr_context` in order to interact and have more control over the context of the current span.
23
+
24
+ ```python
25
+ import os
26
+ from openai import OpenAI
27
+
28
+ from lmnr import observe, wrap_llm_call, lmnr_context
29
+ client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
30
+
31
+ @observe() # annotate all functions you want to trace
32
+ def poem_writer(topic="turbulence"):
33
+ prompt = f"write a poem about {topic}"
34
+
35
+ # wrap the actual final call to LLM with `wrap_llm_call`
36
+ response = wrap_llm_call(client.chat.completions.create)(
37
+ model="gpt-4o",
38
+ messages=[
39
+ {"role": "system", "content": "You are a helpful assistant."},
40
+ {"role": "user", "content": prompt},
41
+ ],
42
+ )
43
+
44
+ poem = response.choices[0].message.content
45
+
46
+ if topic in poem:
47
+ lmnr_context.event("topic_alignment") # send an event with a pre-defined name
48
+
49
+ # to trigger an automatic check for a possible event do:
50
+ lmnr_context.check_span_event("excessive_wordiness")
51
+
52
+ return poem
53
+
54
+ if __name__ == "__main__":
55
+ print(poem_writer(topic="laminar flow"))
56
+ ```
57
+
58
+ This gives an advantage of quick instrumentation, but is somewhat limited in flexibility + doesn't really work as expected with threading.
59
+ This is due to the fact that we use `contextvars.ContextVar` for this, and how Python manages them between threads.
60
+
61
+ If you want to instrument your code manually, follow on to the next section
62
+
63
+ ## Manual instrumentation example
64
+
65
+ For manual instrumetation you will need to import the following:
66
+ - `trace` - this is a function to start a trace. It returns a `TraceContext`
67
+ - `TraceContext` - a pointer to the current trace that you can pass around functions as you want.
68
+ - `SpanContext` - a pointer to the current span that you can pass around functions as you want
69
+
70
+ Both `TraceContext` and `SpanContext` expose the following interfaces:
71
+ - `span(name: str, **kwargs)` - create a child span within the current context. Returns `SpanContext`
72
+ - `update(**kwargs)` - update the current trace or span and return it. Returns `TraceContext` or `SpanContext`. Useful when some metadata becomes known later during the program execution
73
+ - `end(**kwargs)` – update the current span, and terminate it
74
+
75
+ In addition, `SpanContext` allows you to:
76
+ - `event(name: str, value: str | int = None)` - emit a custom event at any point
77
+ - `evaluate_event(name: str, data: str)` - register a possible event for automatic checking by Laminar.
78
+
79
+ Example:
80
+
81
+ ```python
82
+ import os
83
+ from openai import OpenAI
84
+
85
+ from lmnr import trace, TraceContext, SpanContext
86
+ client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
87
+
88
+ def poem_writer(t: TraceContext, topic = "turbulence"):
89
+ span: SpanContext = t.span(name="poem_writer", input=None)
90
+
91
+ prompt = f"write a poem about {topic}"
92
+ messages = [
93
+ {"role": "system", "content": "You are a helpful assistant."},
94
+ {"role": "user", "content": prompt},
95
+ ]
96
+ # create a child span within the current `poem_writer` span.
97
+ llm_span = span.span(name="OpenAI completion", input=messages, span_type="LLM")
98
+
99
+ response = client.chat.completions.create(
100
+ model="gpt-4o-mini",
101
+ messages=[
102
+ {"role": "system", "content": "You are a helpful assistant."},
103
+ {"role": "user", "content": "Hello. What is the capital of France?"},
104
+ ],
105
+ )
106
+ poem = response.choices[0].message.content
107
+ if topic in poem:
108
+ llm_span.event("topic_alignment") # send an event with a pre-defined name
109
+
110
+ # note that you can register possible events here as well, not only `llm_span.check_span_event()`
111
+ llm_span.end(output=poem, check_event_names=["excessive_wordiness"])
112
+ span.end(output=poem)
113
+ return poem
114
+
115
+
116
+ t: TraceContext = trace(user_id="user", session_id="session", release="release")
117
+ main(t, topic="laminar flow")
118
+ t.end(success=True)
119
+ ```
120
+
121
+ ## Features
122
+
123
+ - Make Laminar endpoint calls from your Python code
124
+ - Make Laminar endpoint calls that can run your own functions as tools
125
+ - CLI to generate code from pipelines you build on Laminar or execute your own functions while you test your flows in workshop
126
+
127
+ ## Making Laminar pipeline calls
128
+
129
+ After you are ready to use your pipeline in your code, deploy it in Laminar by selecting the target version for the pipeline.
130
+
131
+ Once your pipeline target is set, you can call it from Python in just a few lines.
132
+
133
+ Example use:
134
+
135
+ ```python
136
+ from lmnr import Laminar
137
+
138
+ # for decorator instrumentation, do: `from lmnr inport lmnr_context`
139
+
140
+ l = Laminar('<YOUR_PROJECT_API_KEY>')
141
+ result = l.run( # lmnr_context.run( for decorator instrumentation
142
+ pipeline = 'my_pipeline_name',
143
+ inputs = {'input_node_name': 'some_value'},
144
+ # all environment variables
145
+ env = {'OPENAI_API_KEY': 'sk-some-key'},
146
+ # any metadata to attach to this run's trace
147
+ metadata = {'session_id': 'your_custom_session_id'}
148
+ )
149
+ ```
150
+
151
+ Resulting in:
152
+
153
+ ```python
154
+ >>> result
155
+ PipelineRunResponse(
156
+ outputs={'output': {'value': [ChatMessage(role='user', content='hello')]}},
157
+ # useful to locate your trace
158
+ run_id='53b012d5-5759-48a6-a9c5-0011610e3669'
159
+ )
160
+ ```
161
+
162
+ ## PROJECT_API_KEY
163
+
164
+ Read more [here](https://docs.lmnr.ai/api-reference/introduction#authentication) on how to get `PROJECT_API_KEY`.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "lmnr"
3
- version = "0.2.14"
3
+ version = "0.3.0b1"
4
4
  description = "Python SDK for Laminar AI"
5
5
  authors = [
6
6
  { name = "lmnr.ai", email = "founders@lmnr.ai" }
@@ -11,7 +11,7 @@ license = "Apache-2.0"
11
11
 
12
12
  [tool.poetry]
13
13
  name = "lmnr"
14
- version = "0.2.14"
14
+ version = "0.3.0b1"
15
15
  description = "Python SDK for Laminar AI"
16
16
  authors = ["lmnr.ai"]
17
17
  readme = "README.md"
@@ -21,14 +21,11 @@ license = "Apache-2.0"
21
21
  python = "^3.9"
22
22
  black = "^24.4.2"
23
23
  pydantic = "^2.7.4"
24
- click = "^8.1.7"
25
24
  requests = "^2.32.3"
26
- websockets = "^12.0"
27
- cookiecutter = "^2.6.0"
28
25
  python-dotenv = "^1.0.1"
29
- pystache = "^0.6.5"
30
- lmnr-baml = "^0.40.1"
31
- watchdog = "^4.0.2"
26
+
27
+ openai = "^1.41.1"
28
+ backoff = "^2.2.1"
32
29
 
33
30
  [build-system]
34
31
  requires = ["poetry-core"]
@@ -0,0 +1,4 @@
1
+ from .sdk.client import Laminar
2
+ from .sdk.decorators import observe, lmnr_context, wrap_llm_call
3
+ from .sdk.interface import trace, TraceContext, SpanContext
4
+ from .sdk.types import ChatMessage, PipelineRunError, PipelineRunResponse, NodeInput
@@ -0,0 +1,156 @@
1
+ from .tracing_types import Span, Trace
2
+
3
+ from pydantic.alias_generators import to_snake
4
+ from typing import Any, Optional, Union
5
+ import dotenv
6
+ import json
7
+ import logging
8
+ import os
9
+ import requests
10
+ import uuid
11
+
12
+ from .types import (
13
+ PipelineRunError,
14
+ PipelineRunResponse,
15
+ NodeInput,
16
+ PipelineRunRequest,
17
+ )
18
+
19
+
20
+ class APIError(Exception):
21
+ def __init__(self, status: Union[int, str], message: str, details: Any = None):
22
+ self.message = message
23
+ self.status = status
24
+ self.details = details
25
+
26
+ def __str__(self):
27
+ msg = "{0} ({1}): {2}"
28
+ return msg.format(self.message, self.status, self.details)
29
+
30
+
31
+ class Laminar:
32
+ _base_url = "https://api.lmnr.ai"
33
+
34
+ def __init__(self, project_api_key: Optional[str] = None):
35
+ self.project_api_key = project_api_key or os.environ.get("LMNR_PROJECT_API_KEY")
36
+ if not self.project_api_key:
37
+ dotenv_path = dotenv.find_dotenv(usecwd=True)
38
+ self.project_api_key = dotenv.get_key(
39
+ dotenv_path=dotenv_path, key_to_get="LMNR_PROJECT_API_KEY"
40
+ )
41
+
42
+ def run(
43
+ self,
44
+ pipeline: str,
45
+ inputs: dict[str, NodeInput],
46
+ env: dict[str, str] = {},
47
+ metadata: dict[str, str] = {},
48
+ parent_span_id: Optional[uuid.UUID] = None,
49
+ trace_id: Optional[uuid.UUID] = None,
50
+ ) -> PipelineRunResponse:
51
+ """Runs the pipeline with the given inputs
52
+
53
+ Args:
54
+ pipeline (str): name of the Laminar pipeline
55
+ inputs (dict[str, NodeInput]):
56
+ inputs to the endpoint's target pipeline.
57
+ Keys in the dictionary must match input node names
58
+ env (dict[str, str], optional):
59
+ Environment variables for the pipeline execution.
60
+ Defaults to {}.
61
+ metadata (dict[str, str], optional):
62
+ any custom metadata to be stored
63
+ with execution trace. Defaults to {}.
64
+ parent_span_id (Optional[uuid.UUID], optional):
65
+ parent span id for the resulting span.
66
+ Must usually be SpanContext.id()
67
+ Defaults to None.
68
+ trace_id (Optional[uuid.UUID], optional):
69
+ trace id for the resulting trace.
70
+ Must usually be TraceContext.id()
71
+ Defaults to None.
72
+
73
+ Returns:
74
+ PipelineRunResponse: response object containing the outputs
75
+
76
+ Raises:
77
+ ValueError: if project API key is not set
78
+ PipelineRunError: if the endpoint run fails
79
+ """
80
+ if self.project_api_key is None:
81
+ raise ValueError(
82
+ "Please initialize the Laminar object with your project API key or set "
83
+ "the LMNR_PROJECT_API_KEY environment variable"
84
+ )
85
+ try:
86
+ request = PipelineRunRequest(
87
+ inputs=inputs,
88
+ pipeline=pipeline,
89
+ env=env,
90
+ metadata=metadata,
91
+ parent_span_id=parent_span_id,
92
+ trace_id=trace_id,
93
+ )
94
+ except Exception as e:
95
+ raise ValueError(f"Invalid request: {e}")
96
+
97
+ response = requests.post(
98
+ self._base_url + "/v1/pipeline/run",
99
+ data=json.dumps(request.to_dict()),
100
+ headers=self._headers(),
101
+ )
102
+ if response.status_code != 200:
103
+ raise PipelineRunError(response)
104
+ try:
105
+ resp_json = response.json()
106
+ keys = list(resp_json.keys())
107
+ for key in keys:
108
+ value = resp_json[key]
109
+ del resp_json[key]
110
+ resp_json[to_snake(key)] = value
111
+ return PipelineRunResponse(**resp_json)
112
+ except Exception:
113
+ raise PipelineRunError(response)
114
+
115
+ def batch_post_traces(self, batch: list[Union[Span, Trace]]):
116
+ log = logging.getLogger("laminar.client")
117
+ url = self._base_url + "/v1/traces"
118
+ data = json.dumps({"traces": [item.to_dict() for item in batch]})
119
+ log.debug(f"making request to {url}")
120
+ headers = self._headers()
121
+ res = requests.post(url, data=data, headers=headers)
122
+
123
+ if res.status_code == 200:
124
+ log.debug("data uploaded successfully")
125
+
126
+ return self._process_response(
127
+ res, success_message="data uploaded successfully", return_json=False
128
+ )
129
+
130
+ def _process_response(
131
+ self, res: requests.Response, success_message: str, return_json: bool = True
132
+ ) -> Union[requests.Response, Any]:
133
+ log = logging.getLogger("laminar.client")
134
+ log.debug("received response: %s", res.text)
135
+ if res.status_code in (200, 201):
136
+ log.debug(success_message)
137
+ if return_json:
138
+ try:
139
+ return res.json()
140
+ except json.JSONDecodeError:
141
+ log.error("Response is not valid JSON.")
142
+ raise APIError(res.status_code, "Invalid JSON response received")
143
+ else:
144
+ return res
145
+ try:
146
+ payload = res.json()
147
+ log.error("received error response: %s", payload)
148
+ raise APIError(res.status_code, payload)
149
+ except (KeyError, ValueError):
150
+ raise APIError(res.status_code, res.text)
151
+
152
+ def _headers(self):
153
+ return {
154
+ "Authorization": "Bearer " + self.project_api_key,
155
+ "Content-Type": "application/json",
156
+ }