agenta 0.15.0a0__py3-none-any.whl → 0.15.0a1__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.

Potentially problematic release.


This version of agenta might be problematic. Click here for more details.

@@ -0,0 +1,506 @@
1
+ """The code for the Agenta SDK"""
2
+
3
+ import os
4
+ import sys
5
+ import time
6
+ import inspect
7
+ import argparse
8
+ import asyncio
9
+ import traceback
10
+ import functools
11
+ from pathlib import Path
12
+ from tempfile import NamedTemporaryFile
13
+ from typing import Any, Callable, Dict, Optional, Tuple, List
14
+
15
+ from fastapi.middleware.cors import CORSMiddleware
16
+ from fastapi import Body, FastAPI, UploadFile, HTTPException
17
+
18
+ import agenta
19
+ from agenta.sdk.context import save_context
20
+ from agenta.sdk.router import router as router
21
+ from agenta.sdk.tracing.llm_tracing import Tracing
22
+ from agenta.sdk.decorators.base import BaseDecorator
23
+ from agenta.sdk.types import (
24
+ Context,
25
+ DictInput,
26
+ FloatParam,
27
+ InFile,
28
+ IntParam,
29
+ MultipleChoiceParam,
30
+ GroupedMultipleChoiceParam,
31
+ TextParam,
32
+ MessagesInput,
33
+ FileInputURL,
34
+ FuncResponse,
35
+ BinaryParam,
36
+ )
37
+
38
+ app = FastAPI()
39
+
40
+ origins = [
41
+ "*",
42
+ ]
43
+
44
+ app.add_middleware(
45
+ CORSMiddleware,
46
+ allow_origins=origins,
47
+ allow_credentials=True,
48
+ allow_methods=["*"],
49
+ allow_headers=["*"],
50
+ )
51
+
52
+ app.include_router(router, prefix="")
53
+
54
+
55
+ class entrypoint(BaseDecorator):
56
+ """Decorator class to wrap a function for HTTP POST, terminal exposure and enable tracing.
57
+
58
+ Args:
59
+ BaseDecorator (object): base decorator class
60
+
61
+ Example:
62
+ ```python
63
+ import agenta as ag
64
+
65
+ @ag.entrypoint(enable_tracing=True) # Defaults to False
66
+ async def chain_of_prompts_llm(prompt: str):
67
+ return ...
68
+ ```
69
+ """
70
+
71
+ def __call__(self, func: Callable[..., Any]):
72
+ endpoint_name = "generate"
73
+ func_signature = inspect.signature(func)
74
+ config_params = agenta.config.all()
75
+ ingestible_files = self.extract_ingestible_files(func_signature)
76
+
77
+ @functools.wraps(func)
78
+ async def wrapper(*args, **kwargs) -> Any:
79
+ func_params, api_config_params = self.split_kwargs(kwargs, config_params)
80
+ self.ingest_files(func_params, ingestible_files)
81
+ agenta.config.set(**api_config_params)
82
+
83
+ # Set the configuration and environment of the LLM app parent span at run-time
84
+ agenta.tracing.set_span_attribute(
85
+ {"config": config_params, "environment": "playground"}
86
+ )
87
+
88
+ llm_result = await self.execute_function(
89
+ func, *args, params=func_params, config_params=config_params
90
+ )
91
+ return llm_result
92
+
93
+ @functools.wraps(func)
94
+ async def wrapper_deployed(*args, **kwargs) -> Any:
95
+ func_params = {
96
+ k: v for k, v in kwargs.items() if k not in ["config", "environment"]
97
+ }
98
+
99
+ if "environment" in kwargs and kwargs["environment"] is not None:
100
+ agenta.config.pull(environment_name=kwargs["environment"])
101
+ elif "config" in kwargs and kwargs["config"] is not None:
102
+ agenta.config.pull(config_name=kwargs["config"])
103
+ else:
104
+ agenta.config.pull(config_name="default")
105
+
106
+ # Set the configuration and environment of the LLM app parent span at run-time
107
+ agenta.tracing.set_span_attribute(
108
+ {"config": config_params, "environment": kwargs["environment"]}
109
+ )
110
+
111
+ llm_result = await self.execute_function(
112
+ func, *args, params=func_params, config_params=config_params
113
+ )
114
+ return llm_result
115
+
116
+ self.update_function_signature(
117
+ wrapper, func_signature, config_params, ingestible_files
118
+ )
119
+ route = f"/{endpoint_name}"
120
+ app.post(route, response_model=FuncResponse)(wrapper)
121
+
122
+ self.update_deployed_function_signature(
123
+ wrapper_deployed,
124
+ func_signature,
125
+ ingestible_files,
126
+ )
127
+ route_deployed = f"/{endpoint_name}_deployed"
128
+ app.post(route_deployed, response_model=FuncResponse)(wrapper_deployed)
129
+ self.override_schema(
130
+ openapi_schema=app.openapi(),
131
+ func_name=func.__name__,
132
+ endpoint=endpoint_name,
133
+ params={**config_params, **func_signature.parameters},
134
+ )
135
+
136
+ if self.is_main_script(func):
137
+ result = self.handle_terminal_run(
138
+ func,
139
+ func_signature.parameters, # type: ignore
140
+ config_params,
141
+ ingestible_files,
142
+ )
143
+ return result
144
+
145
+ def extract_ingestible_files(
146
+ self,
147
+ func_signature: inspect.Signature,
148
+ ) -> Dict[str, inspect.Parameter]:
149
+ """Extract parameters annotated as InFile from function signature."""
150
+
151
+ return {
152
+ name: param
153
+ for name, param in func_signature.parameters.items()
154
+ if param.annotation is InFile
155
+ }
156
+
157
+ def split_kwargs(
158
+ self, kwargs: Dict[str, Any], config_params: Dict[str, Any]
159
+ ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
160
+ """Split keyword arguments into function parameters and API configuration parameters."""
161
+
162
+ func_params = {k: v for k, v in kwargs.items() if k not in config_params}
163
+ api_config_params = {k: v for k, v in kwargs.items() if k in config_params}
164
+ return func_params, api_config_params
165
+
166
+ def ingest_file(self, upfile: UploadFile):
167
+ temp_file = NamedTemporaryFile(delete=False)
168
+ temp_file.write(upfile.file.read())
169
+ temp_file.close()
170
+ return InFile(file_name=upfile.filename, file_path=temp_file.name)
171
+
172
+ def ingest_files(
173
+ self,
174
+ func_params: Dict[str, Any],
175
+ ingestible_files: Dict[str, inspect.Parameter],
176
+ ) -> None:
177
+ """Ingest files specified in function parameters."""
178
+
179
+ for name in ingestible_files:
180
+ if name in func_params and func_params[name] is not None:
181
+ func_params[name] = self.ingest_file(func_params[name])
182
+
183
+ async def execute_function(self, func: Callable[..., Any], *args, **func_params):
184
+ """Execute the function and handle any exceptions."""
185
+
186
+ try:
187
+ """Note: The following block is for backward compatibility.
188
+ It allows functions to work seamlessly whether they are synchronous or asynchronous.
189
+ For synchronous functions, it calls them directly, while for asynchronous functions,
190
+ it awaits their execution.
191
+ """
192
+ is_coroutine_function = inspect.iscoroutinefunction(func)
193
+ start_time = time.perf_counter()
194
+ if is_coroutine_function:
195
+ result = await func(*args, **func_params["params"])
196
+ else:
197
+ result = func(*args, **func_params["params"])
198
+
199
+ end_time = time.perf_counter()
200
+ latency = end_time - start_time
201
+
202
+ if isinstance(result, Context):
203
+ save_context(result)
204
+ if isinstance(result, Dict):
205
+ return FuncResponse(**result, latency=round(latency, 4))
206
+ if isinstance(result, str):
207
+ return FuncResponse(message=result, latency=round(latency, 4)) # type: ignore
208
+ except Exception as e:
209
+ self.handle_exception(e)
210
+ return FuncResponse(message="Unexpected error occurred", latency=0) # type: ignore
211
+
212
+ def handle_exception(self, e: Exception):
213
+ """Handle exceptions."""
214
+
215
+ status_code: int = e.status_code if hasattr(e, "status_code") else 500
216
+ traceback_str = traceback.format_exception(e, value=e, tb=e.__traceback__) # type: ignore
217
+ raise HTTPException(
218
+ status_code=status_code,
219
+ detail={"error": str(e), "traceback": "".join(traceback_str)},
220
+ )
221
+
222
+ def update_wrapper_signature(
223
+ self, wrapper: Callable[..., Any], updated_params: List
224
+ ):
225
+ """
226
+ Updates the signature of a wrapper function with a new list of parameters.
227
+
228
+ Args:
229
+ wrapper (callable): A callable object, such as a function or a method, that requires a signature update.
230
+ updated_params (List[inspect.Parameter]): A list of `inspect.Parameter` objects representing the updated parameters
231
+ for the wrapper function.
232
+ """
233
+
234
+ wrapper_signature = inspect.signature(wrapper)
235
+ wrapper_signature = wrapper_signature.replace(parameters=updated_params)
236
+ wrapper.__signature__ = wrapper_signature
237
+
238
+ def update_function_signature(
239
+ self,
240
+ wrapper: Callable[..., Any],
241
+ func_signature: inspect.Signature,
242
+ config_params: Dict[str, Any],
243
+ ingestible_files: Dict[str, inspect.Parameter],
244
+ ) -> None:
245
+ """Update the function signature to include new parameters."""
246
+
247
+ updated_params = []
248
+ self.add_config_params_to_parser(updated_params, config_params)
249
+ self.add_func_params_to_parser(updated_params, func_signature, ingestible_files)
250
+ self.update_wrapper_signature(wrapper, updated_params)
251
+
252
+ def update_deployed_function_signature(
253
+ self,
254
+ wrapper: Callable[..., Any],
255
+ func_signature: inspect.Signature,
256
+ ingestible_files: Dict[str, inspect.Parameter],
257
+ ) -> None:
258
+ """Update the function signature to include new parameters."""
259
+ updated_params = []
260
+ self.add_func_params_to_parser(updated_params, func_signature, ingestible_files)
261
+ for param in [
262
+ "config",
263
+ "environment",
264
+ ]: # we add the config and environment parameters
265
+ updated_params.append(
266
+ inspect.Parameter(
267
+ param,
268
+ inspect.Parameter.KEYWORD_ONLY,
269
+ default=Body(None),
270
+ annotation=str,
271
+ )
272
+ )
273
+ self.update_wrapper_signature(wrapper, updated_params)
274
+
275
+ def add_config_params_to_parser(
276
+ self, updated_params: list, config_params: Dict[str, Any]
277
+ ) -> None:
278
+ """Add configuration parameters to function signature."""
279
+ for name, param in config_params.items():
280
+ updated_params.append(
281
+ inspect.Parameter(
282
+ name,
283
+ inspect.Parameter.KEYWORD_ONLY,
284
+ default=Body(param),
285
+ annotation=Optional[type(param)],
286
+ )
287
+ )
288
+
289
+ def add_func_params_to_parser(
290
+ self,
291
+ updated_params: list,
292
+ func_signature: inspect.Signature,
293
+ ingestible_files: Dict[str, inspect.Parameter],
294
+ ) -> None:
295
+ """Add function parameters to function signature."""
296
+ for name, param in func_signature.parameters.items():
297
+ if name in ingestible_files:
298
+ updated_params.append(
299
+ inspect.Parameter(name, param.kind, annotation=UploadFile)
300
+ )
301
+ else:
302
+ updated_params.append(
303
+ inspect.Parameter(
304
+ name,
305
+ inspect.Parameter.KEYWORD_ONLY,
306
+ default=Body(..., embed=True),
307
+ annotation=param.annotation,
308
+ )
309
+ )
310
+
311
+ def is_main_script(self, func: Callable) -> bool:
312
+ """
313
+ Check if the script containing the function is the main script being run.
314
+
315
+ Args:
316
+ func (Callable): The function object to check.
317
+
318
+ Returns:
319
+ bool: True if the script containing the function is the main script, False otherwise.
320
+
321
+ Example:
322
+ if is_main_script(my_function):
323
+ print("This is the main script.")
324
+ """
325
+
326
+ # this ensures that when we call main.py, it starts the fastapi server
327
+ if os.path.splitext(os.path.basename(sys.argv[0]))[0] == "main":
328
+ return False
329
+
330
+ # the function that gets passed to entrypoint will always be called from sdk/decorators/tracing.py
331
+ if os.path.splitext(os.path.basename(inspect.getfile(func)))[0] == "tracing":
332
+ return True
333
+
334
+ # same behaviour as the first single-line comment above
335
+ return False
336
+
337
+ def handle_terminal_run(
338
+ self,
339
+ func: Callable,
340
+ func_params: Dict[str, inspect.Parameter],
341
+ config_params: Dict[str, Any],
342
+ ingestible_files: Dict,
343
+ ):
344
+ """
345
+ Parses command line arguments and sets configuration when script is run from the terminal.
346
+
347
+ Args:
348
+ func_params (dict): A dictionary containing the function parameters and their annotations.
349
+ config_params (dict): A dictionary containing the configuration parameters.
350
+ ingestible_files (dict): A dictionary containing the files that should be ingested.
351
+ """
352
+
353
+ # For required parameters, we add them as arguments
354
+ parser = argparse.ArgumentParser()
355
+ for name, param in func_params.items():
356
+ if name in ingestible_files:
357
+ parser.add_argument(name, type=str)
358
+ else:
359
+ parser.add_argument(name, type=param.annotation)
360
+
361
+ for name, param in config_params.items():
362
+ if type(param) is MultipleChoiceParam:
363
+ parser.add_argument(
364
+ f"--{name}",
365
+ type=str,
366
+ default=param.default,
367
+ choices=param.choices,
368
+ )
369
+ else:
370
+ parser.add_argument(
371
+ f"--{name}",
372
+ type=type(param),
373
+ default=param,
374
+ )
375
+
376
+ args = parser.parse_args()
377
+
378
+ # split the arg list into the arg in the app_param and
379
+ # the args from the sig.parameter
380
+ args_config_params = {k: v for k, v in vars(args).items() if k in config_params}
381
+ args_func_params = {
382
+ k: v for k, v in vars(args).items() if k not in config_params
383
+ }
384
+ for name in ingestible_files:
385
+ args_func_params[name] = InFile(
386
+ file_name=Path(args_func_params[name]).stem,
387
+ file_path=args_func_params[name],
388
+ )
389
+
390
+ agenta.config.set(**args_config_params)
391
+
392
+ # Set the configuration and environment of the LLM app parent span at run-time
393
+ agenta.tracing.set_span_attribute(
394
+ {"config": agenta.config.all(), "environment": "bash"}
395
+ )
396
+
397
+ loop = asyncio.get_event_loop()
398
+ result = loop.run_until_complete(
399
+ self.execute_function(
400
+ func,
401
+ **{"params": args_func_params, "config_params": args_config_params},
402
+ )
403
+ )
404
+ print(
405
+ f"\n========== Result ==========\n\nMessage: {result.message}\nCost: {result.cost}\nToken Usage: {result.usage}"
406
+ )
407
+ return result
408
+
409
+ def override_schema(
410
+ self, openapi_schema: dict, func_name: str, endpoint: str, params: dict
411
+ ):
412
+ """
413
+ Overrides the default openai schema generated by fastapi with additional information about:
414
+ - The choices available for each MultipleChoiceParam instance
415
+ - The min and max values for each FloatParam instance
416
+ - The min and max values for each IntParam instance
417
+ - The default value for DictInput instance
418
+ - The default value for MessagesParam instance
419
+ - The default value for FileInputURL instance
420
+ - The default value for BinaryParam instance
421
+ - ... [PLEASE ADD AT EACH CHANGE]
422
+
423
+ Args:
424
+ openapi_schema (dict): The openapi schema generated by fastapi
425
+ func_name (str): The name of the function to override
426
+ endpoint (str): The name of the endpoint to override
427
+ params (dict(param_name, param_val)): The dictionary of the parameters for the function
428
+ """
429
+
430
+ def find_in_schema(schema: dict, param_name: str, xparam: str):
431
+ """Finds a parameter in the schema based on its name and x-parameter value"""
432
+ for _, value in schema.items():
433
+ value_title_lower = str(value.get("title")).lower()
434
+ value_title = (
435
+ "_".join(value_title_lower.split())
436
+ if len(value_title_lower.split()) >= 2
437
+ else value_title_lower
438
+ )
439
+
440
+ if (
441
+ isinstance(value, dict)
442
+ and value.get("x-parameter") == xparam
443
+ and value_title == param_name
444
+ ):
445
+ return value
446
+
447
+ schema_to_override = openapi_schema["components"]["schemas"][
448
+ f"Body_{func_name}_{endpoint}_post"
449
+ ]["properties"]
450
+ for param_name, param_val in params.items():
451
+ if isinstance(param_val, GroupedMultipleChoiceParam):
452
+ subschema = find_in_schema(
453
+ schema_to_override, param_name, "grouped_choice"
454
+ )
455
+ assert (
456
+ subschema
457
+ ), f"GroupedMultipleChoiceParam '{param_name}' is in the parameters but could not be found in the openapi.json"
458
+ subschema["choices"] = param_val.choices
459
+ subschema["default"] = param_val.default
460
+ if isinstance(param_val, MultipleChoiceParam):
461
+ subschema = find_in_schema(schema_to_override, param_name, "choice")
462
+ default = str(param_val)
463
+ param_choices = param_val.choices
464
+ choices = (
465
+ [default] + param_choices
466
+ if param_val not in param_choices
467
+ else param_choices
468
+ )
469
+ subschema["enum"] = choices
470
+ subschema["default"] = (
471
+ default if default in param_choices else choices[0]
472
+ )
473
+ if isinstance(param_val, FloatParam):
474
+ subschema = find_in_schema(schema_to_override, param_name, "float")
475
+ subschema["minimum"] = param_val.minval
476
+ subschema["maximum"] = param_val.maxval
477
+ subschema["default"] = param_val
478
+ if isinstance(param_val, IntParam):
479
+ subschema = find_in_schema(schema_to_override, param_name, "int")
480
+ subschema["minimum"] = param_val.minval
481
+ subschema["maximum"] = param_val.maxval
482
+ subschema["default"] = param_val
483
+ if (
484
+ isinstance(param_val, inspect.Parameter)
485
+ and param_val.annotation is DictInput
486
+ ):
487
+ subschema = find_in_schema(schema_to_override, param_name, "dict")
488
+ subschema["default"] = param_val.default["default_keys"]
489
+ if isinstance(param_val, TextParam):
490
+ subschema = find_in_schema(schema_to_override, param_name, "text")
491
+ subschema["default"] = param_val
492
+ if (
493
+ isinstance(param_val, inspect.Parameter)
494
+ and param_val.annotation is MessagesInput
495
+ ):
496
+ subschema = find_in_schema(schema_to_override, param_name, "messages")
497
+ subschema["default"] = param_val.default
498
+ if (
499
+ isinstance(param_val, inspect.Parameter)
500
+ and param_val.annotation is FileInputURL
501
+ ):
502
+ subschema = find_in_schema(schema_to_override, param_name, "file_url")
503
+ subschema["default"] = "https://example.com"
504
+ if isinstance(param_val, BinaryParam):
505
+ subschema = find_in_schema(schema_to_override, param_name, "bool")
506
+ subschema["default"] = param_val.default
@@ -0,0 +1,90 @@
1
+ # Stdlib Imports
2
+ import inspect
3
+ from functools import wraps
4
+ from typing import Any, Callable, Optional
5
+
6
+ # Own Imports
7
+ import agenta as ag
8
+ from agenta.sdk.decorators.base import BaseDecorator
9
+
10
+
11
+ class instrument(BaseDecorator):
12
+ """Decorator class for monitoring llm apps functions.
13
+
14
+ Args:
15
+ BaseDecorator (object): base decorator class
16
+
17
+ Example:
18
+ ```python
19
+ import agenta as ag
20
+
21
+ prompt_config = {"system_prompt": ..., "temperature": 0.5, "max_tokens": ...}
22
+
23
+ @ag.instrument(spankind="llm")
24
+ async def litellm_openai_call(prompt:str) -> str:
25
+ return "do something"
26
+
27
+ @ag.instrument(config=prompt_config) # spankind for parent span defaults to workflow
28
+ async def generate(prompt: str):
29
+ return ...
30
+ ```
31
+ """
32
+
33
+ def __init__(
34
+ self, config: Optional[dict] = None, spankind: str = "workflow"
35
+ ) -> None:
36
+ self.config = config
37
+ self.spankind = spankind
38
+ self.tracing = ag.tracing
39
+
40
+ def __call__(self, func: Callable[..., Any]):
41
+ is_coroutine_function = inspect.iscoroutinefunction(func)
42
+
43
+ @wraps(func)
44
+ async def async_wrapper(*args, **kwargs):
45
+ result = None
46
+ span = self.tracing.start_span(
47
+ name=func.__name__,
48
+ input=kwargs,
49
+ spankind=self.spankind,
50
+ config=self.config,
51
+ )
52
+
53
+ try:
54
+ result = await func(*args, **kwargs)
55
+ self.tracing.update_span_status(span=span, value="OK")
56
+ except Exception as e:
57
+ result = str(e)
58
+ self.tracing.update_span_status(span=span, value="ERROR")
59
+ finally:
60
+ self.tracing.end_span(
61
+ outputs=(
62
+ {"message": result} if not isinstance(result, dict) else result
63
+ )
64
+ )
65
+ return result
66
+
67
+ @wraps(func)
68
+ def sync_wrapper(*args, **kwargs):
69
+ result = None
70
+ span = self.tracing.start_span(
71
+ name=func.__name__,
72
+ input=kwargs,
73
+ spankind=self.spankind,
74
+ config=self.config,
75
+ )
76
+
77
+ try:
78
+ result = func(*args, **kwargs)
79
+ self.tracing.update_span_status(span=span, value="OK")
80
+ except Exception as e:
81
+ result = str(e)
82
+ self.tracing.update_span_status(span=span, value="ERROR")
83
+ finally:
84
+ self.tracing.end_span(
85
+ outputs=(
86
+ {"message": result} if not isinstance(result, dict) else result
87
+ )
88
+ )
89
+
90
+ return async_wrapper if is_coroutine_function else sync_wrapper