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