agenta 0.14.12a2__py3-none-any.whl → 0.14.13__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.

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