Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
HamadaSalhab committed Oct 30, 2024
1 parent 74982fa commit 6fd1e0d
Show file tree
Hide file tree
Showing 8 changed files with 352 additions and 173 deletions.
66 changes: 49 additions & 17 deletions agents-api/agents_api/activities/execute_system.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
from typing import Any
from uuid import UUID

from ..models.developer.get_developer import get_developer

from ..routers.sessions.chat import chat

from ..autogen.Chat import ChatInput
from ..common.protocol.developers import Developer

from beartype import beartype
from box import Box, BoxList
from fastapi.background import BackgroundTasks
Expand Down Expand Up @@ -107,25 +114,40 @@ async def execute_system(
# The `search_agent_docs` function requires `x_developer_id` instead of `developer_id`.
arguments["x_developer_id"] = arguments.pop("developer_id")

if "text" in arguments and "vector" in arguments:
# Pop the arguments
text = arguments.pop("text", None)
vector = arguments.pop("vector", None)
alpha = arguments.pop("alpha", 0.75)
confidence = arguments.pop("confidence", 0.5)
metadata_filter = arguments.pop("metadata_filter", {})
mmr_strength = arguments.pop("mmr_strength", 0)
limit = arguments.get("limit", 10)

if text and vector:
search_params = HybridDocSearchRequest(
text=arguments.pop("text"),
vector=arguments.pop("vector"),
alpha=arguments.pop("alpha", 0.75),
confidence=arguments.pop("confidence", 0.5),
limit=arguments.get("limit", 10),
text=text,
vector=vector,
alpha=alpha,
confidence=confidence,
limit=limit,
metadata_filter=metadata_filter,
mmr_strength=mmr_strength,
)

elif "text" in arguments:
elif text:
search_params = TextOnlyDocSearchRequest(
text=arguments.pop("text"),
limit=arguments.get("limit", 10),
text=text,
limit=limit,
metadata_filter=metadata_filter,
mmr_strength=mmr_strength,
)
elif "vector" in arguments:
elif vector:
search_params = VectorDocSearchRequest(
vector=arguments.pop("vector"),
confidence=arguments.pop("confidence", 0.7),
limit=arguments.get("limit", 10),
vector=vector,
confidence=confidence,
limit=limit,
metadata_filter=metadata_filter,
mmr_strength=mmr_strength,
)

return await search_agent_docs(
Expand Down Expand Up @@ -225,10 +247,22 @@ async def execute_system(
return create_session_query(**arguments)
elif system.operation == "update":
return update_session_query(**arguments)
elif system.operation == "delete":
return update_session_query(**arguments)
elif system.operation == "delete":
return delete_session_query(**arguments)
elif system.operation == "chat":
developer: Developer = get_developer(
developer_id=arguments.pop("developer_id")
)
session_id = arguments.pop("session_id")
chat_input = ChatInput(**arguments)
return await chat(
developer=developer,
session_id=session_id,
chat_input=chat_input,
background_tasks=BackgroundTasks(),
x_custom_api_key=arguments.pop("x_custom_api_key", None),
)

# TASKS
elif system.resource == "task":
if system.operation == "list":
Expand All @@ -237,8 +271,6 @@ async def execute_system(
return get_task_query(**arguments)
elif system.operation == "create":
return create_task_query(**arguments)
elif system.operation == "update":
return update_task_query(**arguments)
elif system.operation == "delete":
return delete_task_query(**arguments)

Expand Down
46 changes: 16 additions & 30 deletions agents-api/agents_api/activities/task_steps/base_evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,22 @@ def __init__(self, error, expression, values):
super().__init__(message)


# Added recursive evaluation function
def _recursive_evaluate(expr, evaluator):
if isinstance(expr, str):
return evaluator.eval(expr)
elif isinstance(expr, list):
return [ _recursive_evaluate(e, evaluator) for e in expr ]
elif isinstance(expr, dict):
return {k: _recursive_evaluate(v, evaluator) for k, v in expr.items()}
else:
raise ValueError(f"Invalid expression: {expr}")


@auto_blob_store
@beartype
async def base_evaluate(
exprs: str | list[str] | dict[str, str] | dict[str, dict[str, str]],
exprs: Any,
values: dict[str, Any] = {},
extra_lambda_strs: dict[str, str] | None = None,
) -> Any | list[Any] | dict[str, Any]:
Expand Down Expand Up @@ -67,41 +79,15 @@ async def base_evaluate(

evaluator = get_evaluator(names=values, extra_functions=extra_lambdas)

chosen_expression = ""

try:
result = None
match exprs:
case str():
chosen_expression = exprs
result = evaluator.eval(exprs)
case list():
result = []
for expr in exprs:
chosen_expression = expr
result.append(evaluator.eval(expr))
case dict() as d if all(
isinstance(v, dict) or isinstance(v, str) for v in d.values()
):
result = {}
for k, v in d.items():
if isinstance(v, str):
chosen_expression = v
result[k] = evaluator.eval(v)
else:
result[k] = {}
for k1, v1 in v.items():
chosen_expression = v1
result[k][k1] = evaluator.eval(v1)
case _:
raise ValueError(f"Invalid expression: {exprs}")

# Replaced match-case logic with recursive evaluation
result = _recursive_evaluate(exprs, evaluator)
return result

except BaseException as e:
if activity.in_activity():
activity.logger.error(f"Error in base_evaluate: {e}")
newException = EvaluateError(e, chosen_expression, values)
newException = EvaluateError(e, exprs, values)
raise newException from e


Expand Down
34 changes: 29 additions & 5 deletions agents-api/agents_api/autogen/Tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ class EvaluateStep(BaseModel):
"""
The kind of step
"""
evaluate: dict[str, str]
evaluate: dict[str, list[str] | dict[str, str] | list[dict[str, str]] | str]
"""
The expression to evaluate
"""
Expand Down Expand Up @@ -712,7 +712,10 @@ class ReturnStep(BaseModel):
"""
The kind of step
"""
return_: Annotated[dict[str, str], Field(alias="return")]
return_: Annotated[
dict[str, list[str] | dict[str, str] | list[dict[str, str]] | str],
Field(alias="return"),
]
"""
The value to return
"""
Expand Down Expand Up @@ -886,7 +889,25 @@ class ToolCallStep(BaseModel):
"""
The tool to run
"""
arguments: dict[str, dict[str, str] | str] | Literal["_"] = "_"
arguments: (
dict[
str,
dict[str, list[str] | dict[str, str] | list[dict[str, str]] | str]
| list[dict[str, list[str] | dict[str, str] | list[dict[str, str]] | str]]
| str,
]
| list[
dict[
str,
dict[str, list[str] | dict[str, str] | list[dict[str, str]] | str]
| list[
dict[str, list[str] | dict[str, str] | list[dict[str, str]] | str]
]
| str,
]
]
| Literal["_"]
) = "_"
"""
The input parameters for the tool (defaults to last step output)
"""
Expand Down Expand Up @@ -990,7 +1011,7 @@ class WaitForInputInfo(BaseModel):
model_config = ConfigDict(
populate_by_name=True,
)
info: dict[str, str]
info: dict[str, list[str] | dict[str, str] | list[dict[str, str]] | str]
"""
Any additional info or data
"""
Expand Down Expand Up @@ -1027,7 +1048,10 @@ class YieldStep(BaseModel):
The subworkflow to run.
VALIDATION: Should resolve to a defined subworkflow.
"""
arguments: dict[str, str] | Literal["_"] = "_"
arguments: (
dict[str, list[str] | dict[str, str] | list[dict[str, str]] | str]
| Literal["_"]
) = "_"
"""
The input parameters for the subworkflow (defaults to last step output)
"""
15 changes: 7 additions & 8 deletions agents-api/agents_api/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@
# Initialize the Env object for environment variable parsing.
env: Any = Env()

# Debug
# -----
debug: bool = env.bool("AGENTS_API_DEBUG", default=False)
testing: bool = env.bool("AGENTS_API_TESTING", default=False)
sentry_dsn: str = env.str("SENTRY_DSN", default=None)

# App
# ---
multi_tenant_mode: bool = env.bool("AGENTS_API_MULTI_TENANT_MODE", default=False)
Expand All @@ -30,7 +36,7 @@
# ----------
use_blob_store_for_temporal: bool = env.bool(
"USE_BLOB_STORE_FOR_TEMPORAL", default=False
)
) if not testing else False

blob_store_bucket: str = env.str("BLOB_STORE_BUCKET", default="agents-api")
blob_store_cutoff_kb: int = env.int("BLOB_STORE_CUTOFF_KB", default=64)
Expand All @@ -39,13 +45,6 @@
s3_secret_key: str | None = env.str("S3_SECRET_KEY", default=None)


# Debug
# -----
debug: bool = env.bool("AGENTS_API_DEBUG", default=False)
testing: bool = env.bool("AGENTS_API_TESTING", default=False)
sentry_dsn: str = env.str("SENTRY_DSN", default=None)


# Cozo
# ----
cozo_host: str = env.str("COZO_HOST", default="http://127.0.0.1:9070")
Expand Down
Loading

0 comments on commit 6fd1e0d

Please sign in to comment.