lmnr 0.4.17b1__py3-none-any.whl → 0.4.18b0__py3-none-any.whl

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.
lmnr/sdk/evaluations.py CHANGED
@@ -79,9 +79,13 @@ class EvaluationReporter:
79
79
  self.cli_progress.close()
80
80
  sys.stderr.write(f"\nError: {error}\n")
81
81
 
82
- def stop(self, average_scores: dict[str, Numeric], project_id: str, evaluation_id: str):
82
+ def stop(
83
+ self, average_scores: dict[str, Numeric], project_id: str, evaluation_id: str
84
+ ):
83
85
  self.cli_progress.close()
84
- print(f"\nCheck progress and results at {get_evaluation_url(project_id, evaluation_id)}\n")
86
+ print(
87
+ f"\nCheck progress and results at {get_evaluation_url(project_id, evaluation_id)}\n"
88
+ )
85
89
  print("Average scores:")
86
90
  for name, score in average_scores.items():
87
91
  print(f"{name}: {score}")
@@ -124,35 +128,41 @@ class Evaluation:
124
128
  Initializes an instance of the Evaluations class.
125
129
 
126
130
  Parameters:
127
- data (Union[List[Union[EvaluationDatapoint, dict]], EvaluationDataset]): List of data points to evaluate or an evaluation dataset.
131
+ data (Union[List[EvaluationDatapoint|dict], EvaluationDataset]):\
132
+ List of data points to evaluate or an evaluation dataset.
128
133
  `data` is the input to the executor function,
129
134
  `target` is the input to the evaluator function.
130
- executor (Callable[..., Any]): The executor function.
131
- Takes the data point + any additional arguments
135
+ executor (Callable[..., Any]): The executor function.\
136
+ Takes the data point + any additional arguments\
132
137
  and returns the output to evaluate.
133
- evaluators (List[Callable[..., Any]]): List of evaluator functions.
134
- Each evaluator function takes the output of the executor _and_
135
- the target data, and returns a score. The score can be a
136
- single number or a record of string keys and number values.
137
- If the score is a single number, it will be named after the
138
- evaluator function. If the function is anonymous, it will be
139
- named `evaluator_${index}`, where index is the index of the
138
+ evaluators (List[Callable[..., Any]]): List of evaluator functions.\
139
+ Each evaluator function takes the output of the executor _and_\
140
+ the target data, and returns a score. The score can be a\
141
+ single number or a record of string keys and number values.\
142
+ If the score is a single number, it will be named after the\
143
+ evaluator function. If the function is anonymous, it will be\
144
+ named `evaluator_${index}`, where index is the index of the\
140
145
  evaluator function in the list starting from 1.
141
146
  group_id (Optional[str], optional): Group id of the evaluation.
142
147
  Defaults to "default".
143
- name (Optional[str], optional): The name of the evaluation.
148
+ name (Optional[str], optional): The name of the evaluation.\
144
149
  It will be auto-generated if not provided.
145
150
  batch_size (int, optional): The batch size for evaluation.
146
151
  Defaults to DEFAULT_BATCH_SIZE.
147
152
  project_api_key (Optional[str], optional): The project API key.
148
153
  Defaults to an empty string.
149
- base_url (Optional[str], optional): The base URL for the Laminar API.
150
- Useful if self-hosted elsewhere.
154
+ base_url (Optional[str], optional): The base URL for Laminar API.\
155
+ Useful if self-hosted elsewhere. Do NOT include the\
156
+ port, use `http_port` and `grpc_port` instead.
151
157
  Defaults to "https://api.lmnr.ai".
152
- http_port (Optional[int], optional): The port for the Laminar API HTTP service.
153
- Defaults to 443.
154
- instruments (Optional[Set[Instruments]], optional): Set of modules to auto-instrument.
155
- Defaults to None. If None, all available instruments will be used.
158
+ http_port (Optional[int], optional): The port for Laminar API\
159
+ HTTP service. Defaults to 443 if not specified.
160
+ grpc_port (Optional[int], optional): The port for Laminar API\
161
+ gRPC service. Defaults to 8443 if not specified.
162
+ instruments (Optional[Set[Instruments]], optional): Set of modules\
163
+ to auto-instrument. If None, all available instruments will be\
164
+ used.
165
+ Defaults to None.
156
166
  """
157
167
 
158
168
  if not evaluators:
@@ -160,8 +170,12 @@ class Evaluation:
160
170
 
161
171
  # TODO: Compile regex once and then reuse it
162
172
  for evaluator_name in evaluators:
163
- if not re.match(r'^[\w\s-]+$', evaluator_name):
164
- raise ValueError(f'Invalid evaluator key: "{evaluator_name}". Keys must only contain letters, digits, hyphens, underscores, or spaces.')
173
+ if not re.match(r"^[\w\s-]+$", evaluator_name):
174
+ raise ValueError(
175
+ f'Invalid evaluator key: "{evaluator_name}". '
176
+ "Keys must only contain letters, digits, hyphens,"
177
+ "underscores, or spaces."
178
+ )
165
179
 
166
180
  self.is_finished = False
167
181
  self.reporter = EvaluationReporter()
@@ -207,7 +221,9 @@ class Evaluation:
207
221
  self.is_finished = True
208
222
  return
209
223
  else:
210
- evaluation = L.create_evaluation(data=result_datapoints, group_id=self.group_id, name=self.name)
224
+ evaluation = L.create_evaluation(
225
+ data=result_datapoints, group_id=self.group_id, name=self.name
226
+ )
211
227
  average_scores = get_average_scores(result_datapoints)
212
228
  self.reporter.stop(average_scores, evaluation.projectId, evaluation.id)
213
229
  self.is_finished = True
@@ -216,7 +232,7 @@ class Evaluation:
216
232
  result_datapoints = []
217
233
  for i in range(0, len(self.data), self.batch_size):
218
234
  batch = (
219
- self.data[i: i + self.batch_size]
235
+ self.data[i : i + self.batch_size]
220
236
  if isinstance(self.data, list)
221
237
  else self.data.slice(i, i + self.batch_size)
222
238
  )
@@ -294,43 +310,58 @@ def evaluate(
294
310
  instruments: Optional[Set[Instruments]] = None,
295
311
  ) -> Optional[Awaitable[None]]:
296
312
  """
297
- If added to the file which is called through lmnr eval command, then simply registers the evaluation.
298
- Otherwise, if there is no event loop, creates it and runs the evaluation until completion.
299
- If there is an event loop, schedules the evaluation as a task in the event loop and returns an awaitable handle.
313
+ If added to the file which is called through `lmnr eval` command, then
314
+ registers the evaluation; otherwise, runs the evaluation.
315
+
316
+ If there is no event loop, creates it and runs the evaluation until
317
+ completion.
318
+ If there is an event loop, schedules the evaluation as a task in the
319
+ event loop and returns an awaitable handle.
300
320
 
301
321
  Parameters:
302
- data (Union[List[Union[EvaluationDatapoint, dict]], EvaluationDataset]): List of data points to evaluate or an evaluation dataset.
322
+ data (Union[list[EvaluationDatapoint|dict]], EvaluationDataset]):\
323
+ List of data points to evaluate or an evaluation dataset.
303
324
  `data` is the input to the executor function,
304
325
  `target` is the input to the evaluator function.
305
- executor (Callable[..., Any]): The executor function.
306
- Takes the data point + any additional arguments
326
+ executor (Callable[..., Any]): The executor function.\
327
+ Takes the data point + any additional arguments\
307
328
  and returns the output to evaluate.
308
- evaluators (List[Callable[..., Any]]): List of evaluator functions.
309
- Each evaluator function takes the output of the executor _and_
310
- the target data, and returns a score. The score can be a
311
- single number or a record of string keys and number values.
312
- If the score is a single number, it will be named after the
313
- evaluator function. If the function is anonymous, it will be
314
- named `evaluator_${index}`, where index is the index of the
329
+ evaluators (List[Callable[..., Any]]): List of evaluator functions.\
330
+ Each evaluator function takes the output of the executor _and_\
331
+ the target data, and returns a score. The score can be a\
332
+ single number or a record of string keys and number values.\
333
+ If the score is a single number, it will be named after the\
334
+ evaluator function. If the function is anonymous, it will be\
335
+ named `evaluator_${index}`, where index is the index of the\
315
336
  evaluator function in the list starting from 1.
316
- group_id (Optional[str], optional): Group name which is same
317
- as the feature you are evaluating in your project or application.
318
- Defaults to "default".
319
- name (Optional[str], optional): Optional name of the evaluation. Used to easily
320
- identify the evaluation in the group.
337
+ group_id (Optional[str], optional): an identifier to group evaluations.\
338
+ It is practical to group evaluations that evaluate\
339
+ the same feature on the same dataset, to be able to\
340
+ view their comparisons in the same place. If not\
341
+ provided, defaults to "default".
342
+ Defaults to None
343
+ name (Optional[str], optional): Optional name of the evaluation.\
344
+ Used to identify the evaluation in the group.\
345
+ If not provided, a random name will be generated.
346
+ Defaults to None.
321
347
  batch_size (int, optional): The batch size for evaluation.
322
348
  Defaults to DEFAULT_BATCH_SIZE.
323
349
  project_api_key (Optional[str], optional): The project API key.
324
- Defaults to an empty string.
325
- base_url (Optional[str], optional): The base URL for the Laminar API.
326
- Useful if self-hosted elsewhere.
350
+ Defaults to None.
351
+ base_url (Optional[str], optional): The base URL for Laminar API.\
352
+ Useful if self-hosted elsewhere. Do NOT include the\
353
+ port, use `http_port` and `grpc_port` instead.
327
354
  Defaults to "https://api.lmnr.ai".
328
- http_port (Optional[int], optional): The port for the Laminar API HTTP service.
329
- Defaults to 443.
330
- grpc_port (Optional[int], optional): The port for the Laminar API gRPC service.
331
- Defaults to 8443.
332
- instruments (Optional[Set[Instruments]], optional): Set of modules to auto-instrument.
333
- Defaults to None. If None, all available instruments will be used.
355
+ http_port (Optional[int], optional): The port for Laminar API's HTTP\
356
+ service. 443 is used if not specified.
357
+ Defaults to None.
358
+ grpc_port (Optional[int], optional): The port for Laminar API's gRPC\
359
+ service. 8443 is used if not specified.
360
+ Defaults to None.
361
+ instruments (Optional[Set[Instruments]], optional): Set of modules to\
362
+ auto-instrument. If None, all available instruments\
363
+ will be used.
364
+ Defaults to None.
334
365
  """
335
366
 
336
367
  evaluation = Evaluation(
lmnr/sdk/laminar.py CHANGED
@@ -1,3 +1,4 @@
1
+ import re
1
2
  from lmnr.traceloop_sdk.instruments import Instruments
2
3
  from opentelemetry import context
3
4
  from opentelemetry.trace import (
@@ -72,23 +73,23 @@ class Laminar:
72
73
  decorators.
73
74
 
74
75
  Args:
75
- project_api_key (Optional[str], optional): Laminar project api key.
76
- You can generate one by going to the projects
77
- settings page on the Laminar dashboard.
78
- If not specified, it will try to read from the
79
- LMNR_PROJECT_API_KEY environment variable
76
+ project_api_key (Optional[str], optional): Laminar project api key.\
77
+ You can generate one by going to the projects\
78
+ settings page on the Laminar dashboard.\
79
+ If not specified, it will try to read from the\
80
+ LMNR_PROJECT_API_KEY environment variable\
80
81
  in os.environ or in .env file.
81
82
  Defaults to None.
82
- env (dict[str, str], optional): Default environment passed to
83
- `run` requests, unless
84
- overriden at request time. Usually, model
85
- provider keys are stored here.
83
+ env (dict[str, str], optional): Default environment passed to\
84
+ `run` requests, unless overriden at request time.\
85
+ Usually, model provider keys are stored here.
86
86
  Defaults to {}.
87
- base_url (Optional[str], optional): Laminar API url.
87
+ base_url (Optional[str], optional): Laminar API url. Do NOT include\
88
+ the port number, use `http_port` and `grpc_port`.\
88
89
  If not specified, defaults to https://api.lmnr.ai.
89
- http_port (Optional[int], optional): Laminar API http port.
90
+ http_port (Optional[int], optional): Laminar API http port.\
90
91
  If not specified, defaults to 443.
91
- grpc_port (Optional[int], optional): Laminar API grpc port.
92
+ grpc_port (Optional[int], optional): Laminar API grpc port.\
92
93
  If not specified, defaults to 8443.
93
94
 
94
95
  Raises:
@@ -108,9 +109,14 @@ class Laminar:
108
109
  " your project API key or set the LMNR_PROJECT_API_KEY"
109
110
  " environment variable in your environment or .env file"
110
111
  )
111
-
112
- cls.__base_http_url = f"{base_url or 'https://api.lmnr.ai'}:{http_port or 443}"
113
- cls.__base_grpc_url = f"{base_url or 'https://api.lmnr.ai'}:{grpc_port or 8443}"
112
+ if re.search(r":\d{1,5}$", base_url):
113
+ raise ValueError(
114
+ "Please provide the `base_url` without the port number. "
115
+ "Use the `http_port` and `grpc_port` arguments instead."
116
+ )
117
+ url = base_url or "https://api.lmnr.ai"
118
+ cls.__base_http_url = f"{url}:{http_port or 443}"
119
+ cls.__base_grpc_url = f"{url}:{grpc_port or 8443}"
114
120
 
115
121
  cls.__env = env
116
122
  cls.__initialized = True
@@ -153,22 +159,22 @@ class Laminar:
153
159
  """Runs the pipeline with the given inputs
154
160
 
155
161
  Args:
156
- pipeline (str): name of the Laminar pipeline.
162
+ pipeline (str): name of the Laminar pipeline.\
157
163
  The pipeline must have a target version set.
158
164
  inputs (dict[str, NodeInput]):
159
- inputs to the endpoint's target pipeline.
165
+ inputs to the endpoint's target pipeline.\
160
166
  Keys in the dictionary must match input node names
161
167
  env (dict[str, str], optional):
162
168
  Environment variables for the pipeline execution.
163
169
  Defaults to {}.
164
170
  metadata (dict[str, str], optional):
165
- any custom metadata to be stored
166
- with execution trace. Defaults to {}.
167
- parent_span_id (Optional[uuid.UUID], optional):
168
- parent span id for the resulting span.
171
+ any custom metadata to be stored with execution trace.
172
+ Defaults to {}.
173
+ parent_span_id (Optional[uuid.UUID], optional): parent span id for\
174
+ the resulting span.
169
175
  Defaults to None.
170
- trace_id (Optional[uuid.UUID], optional):
171
- trace id for the resulting trace.
176
+ trace_id (Optional[uuid.UUID], optional): trace id for the\
177
+ resulting trace.
172
178
  Defaults to None.
173
179
 
174
180
  Returns:
@@ -195,7 +201,7 @@ class Laminar:
195
201
  request = PipelineRunRequest(
196
202
  inputs=inputs,
197
203
  pipeline=pipeline,
198
- env=env,
204
+ env=env or cls.__env,
199
205
  metadata=metadata,
200
206
  parent_span_id=parent_span_id,
201
207
  trace_id=trace_id,
@@ -228,21 +234,23 @@ class Laminar:
228
234
  value: Optional[AttributeValue] = None,
229
235
  timestamp: Optional[Union[datetime.datetime, int]] = None,
230
236
  ):
231
- """Associate an event with the current span. If event with such name never
232
- existed, Laminar will create a new event and infer its type from the value.
233
- If the event already exists, Laminar will append the value to the event
234
- if and only if the value is of a matching type. Otherwise, the event won't
235
- be recorded Supported types are string, numeric, and boolean. If the value
237
+ """Associate an event with the current span. If event with such
238
+ name never existed, Laminar will create a new event and infer its type
239
+ from the value. If the event already exists, Laminar will append the
240
+ value to the event if and only if the value is of a matching type.
241
+ Otherwise, the event won't be recorded.
242
+ Supported types are string, numeric, and boolean. If the value
236
243
  is `None`, event is considered a boolean tag with the value of `True`.
237
244
 
238
245
  Args:
239
246
  name (str): event name
240
- value (Optional[AttributeValue]): event value. Must be a primitive type.
241
- Boolean true is assumed in the backend if value is None.
247
+ value (Optional[AttributeValue]): event value. Must be a primitive\
248
+ type. Boolean true is assumed in the backend if\
249
+ `value` is None.
242
250
  Defaults to None.
243
- timestamp (Optional[Union[datetime.datetime, int]], optional):
244
- If int, must be epoch nanoseconds. If not
245
- specified, relies on the underlying OpenTelemetry
251
+ timestamp (Optional[Union[datetime.datetime, int]], optional):\
252
+ If int, must be epoch nanoseconds. If not\
253
+ specified, relies on the underlying OpenTelemetry\
246
254
  implementation. Defaults to None.
247
255
  """
248
256
  if timestamp and isinstance(timestamp, datetime.datetime):
@@ -272,18 +280,18 @@ class Laminar:
272
280
  name: str,
273
281
  input: Any = None,
274
282
  ):
275
- """Start a new span as the current span. Useful for manual instrumentation.
276
- This is the preferred and more stable way to use manual instrumentation.
283
+ """Start a new span as the current span. Useful for manual
284
+ instrumentation.
277
285
 
278
286
  Usage example:
279
287
  ```python
280
- with Laminar.start_as_current_span("my_span", input="my_input"):
288
+ with Laminar.start_as_current_span("my_span", input="my_input") as span:
281
289
  await my_async_function()
282
290
  ```
283
291
 
284
292
  Args:
285
293
  name (str): name of the span
286
- input (Any, optional): input to the span. Will be sent as an
294
+ input (Any, optional): input to the span. Will be sent as an\
287
295
  attribute, so must be json serializable. Defaults to None.
288
296
  """
289
297
  with get_tracer() as tracer:
@@ -310,10 +318,11 @@ class Laminar:
310
318
 
311
319
  @classmethod
312
320
  def set_span_output(cls, output: Any = None):
313
- """Set the output of the current span. Useful for manual instrumentation.
321
+ """Set the output of the current span. Useful for manual
322
+ instrumentation.
314
323
 
315
324
  Args:
316
- output (Any, optional): output of the span. Will be sent as an
325
+ output (Any, optional): output of the span. Will be sent as an\
317
326
  attribute, so must be json serializable. Defaults to None.
318
327
  """
319
328
  span = get_current_span()
@@ -331,12 +340,12 @@ class Laminar:
331
340
  thread).
332
341
 
333
342
  Args:
334
- session_id (Optional[str], optional): Custom session id.
335
- Useful to debug and group long-running
343
+ session_id (Optional[str], optional): Custom session id.\
344
+ Useful to debug and group long-running\
336
345
  sessions/conversations.
337
346
  Defaults to None.
338
- user_id (Optional[str], optional): Custom user id.
339
- Useful for grouping spans or traces by user.
347
+ user_id (Optional[str], optional): Custom user id.\
348
+ Useful for grouping spans or traces by user.\
340
349
  Defaults to None.
341
350
  """
342
351
  association_properties = {}
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: lmnr
3
- Version: 0.4.17b1
3
+ Version: 0.4.18b0
4
4
  Summary: Python SDK for Laminar AI
5
5
  License: Apache-2.0
6
6
  Author: lmnr.ai
@@ -249,7 +249,7 @@ You can run evaluations locally by providing executor (part of the logic used in
249
249
 
250
250
  \* If you already have the outputs of executors you want to evaluate, you can specify the executor as an identity function, that takes in `data` and returns only needed value(s) from it.
251
251
 
252
- [Read docs](https://docs.lmnr.ai/evaluations/introduction) to learn more about evaluations.
252
+ Read the [docs](https://docs.lmnr.ai/evaluations/introduction) to learn more about evaluations.
253
253
 
254
254
  ## Laminar pipelines as prompt chain managers
255
255
 
@@ -2,8 +2,8 @@ lmnr/__init__.py,sha256=5Ks8UIicCzCBgwSz0MOX3I7jVruPMUO3SmxIwUoODzQ,231
2
2
  lmnr/cli.py,sha256=Ptvm5dsNLKUY5lwnN8XkT5GtCYjzpRNi2WvefknB3OQ,1079
3
3
  lmnr/sdk/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
4
  lmnr/sdk/decorators.py,sha256=ZSDaEZyjo-RUzRCltsNbe6x0t9SKl2xRQ2q4uaKvXtk,2250
5
- lmnr/sdk/evaluations.py,sha256=Tukl2pW_x13ittzG5XQpF1TweYo3fpD4eLInplQ4YYI,14152
6
- lmnr/sdk/laminar.py,sha256=-qvfWYUAT63pBSdN6LFj6oT7JUbqEGVRunu-5tckzaM,14698
5
+ lmnr/sdk/evaluations.py,sha256=C2lhrevH3PDvnTX-qfop1k-NTqTFX4MWaSkc9oG5kxc,15199
6
+ lmnr/sdk/laminar.py,sha256=Dy8RVgGIev4dTjnu-LSwFoI0Un09EoLJDv_Fx4q2vvQ,15018
7
7
  lmnr/sdk/log.py,sha256=EgAMY77Zn1bv1imCqrmflD3imoAJ2yveOkIcrIP3e98,1170
8
8
  lmnr/sdk/types.py,sha256=HvaZEqVRduCZbkF7Cp8rgS5oBbc1qPvOD3PP9tFrRu4,4826
9
9
  lmnr/sdk/utils.py,sha256=s81p6uJehgJSaLWy3sR5fTpEDH7vzn3i_UujUHChl6M,3346
@@ -44,8 +44,8 @@ lmnr/traceloop_sdk/utils/in_memory_span_exporter.py,sha256=H_4TRaThMO1H6vUQ0OpQv
44
44
  lmnr/traceloop_sdk/utils/json_encoder.py,sha256=dK6b_axr70IYL7Vv-bu4wntvDDuyntoqsHaddqX7P58,463
45
45
  lmnr/traceloop_sdk/utils/package_check.py,sha256=TZSngzJOpFhfUZLXIs38cpMxQiZSmp0D-sCrIyhz7BA,251
46
46
  lmnr/traceloop_sdk/version.py,sha256=OlatFEFA4ttqSSIiV8jdE-sq3KG5zu2hnC4B4mzWF3s,23
47
- lmnr-0.4.17b1.dist-info/LICENSE,sha256=67b_wJHVV1CBaWkrKFWU1wyqTPSdzH77Ls-59631COg,10411
48
- lmnr-0.4.17b1.dist-info/METADATA,sha256=rytnKog2_G-j17WbPrAaNsYUKT7J7kFCmU4xzDfByHA,10476
49
- lmnr-0.4.17b1.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
50
- lmnr-0.4.17b1.dist-info/entry_points.txt,sha256=K1jE20ww4jzHNZLnsfWBvU3YKDGBgbOiYG5Y7ivQcq4,37
51
- lmnr-0.4.17b1.dist-info/RECORD,,
47
+ lmnr-0.4.18b0.dist-info/LICENSE,sha256=67b_wJHVV1CBaWkrKFWU1wyqTPSdzH77Ls-59631COg,10411
48
+ lmnr-0.4.18b0.dist-info/METADATA,sha256=IGISzLTkZUs6hMecDq-Pmg31C-hYQ3MguS6DRpsr0qQ,10480
49
+ lmnr-0.4.18b0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
50
+ lmnr-0.4.18b0.dist-info/entry_points.txt,sha256=K1jE20ww4jzHNZLnsfWBvU3YKDGBgbOiYG5Y7ivQcq4,37
51
+ lmnr-0.4.18b0.dist-info/RECORD,,