Skip to content

Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!

Python

refacto: Tool execution

Clémence Lesné3d6990707921
diff --git a/app/helpers/llm_utils.py b/app/helpers/llm_utils.py
index fb7def5..e37451b 100644
--- a/app/helpers/llm_utils.py
+++ b/app/helpers/llm_utils.py
@@ -5,7 +5,9 @@ See: https://github.com/microsoft/autogen/blob/2750391f847b7168d842dfcb815ac37bd
import asyncio
import inspect
+import json
from collections.abc import Awaitable, Callable
+from functools import cache
from inspect import getmembers, isfunction
from textwrap import dedent
from typing import Annotated, Any, ForwardRef, TypeVar
@@ -16,6 +18,7 @@ from azure.cognitiveservices.speech import (
)
from azure.communication.callautomation.aio import CallAutomationClient
from jinja2 import Environment
+from json_repair import repair_json
from openai.types.chat import ChatCompletionToolParam
from openai.types.shared_params.function_definition import FunctionDefinition
from pydantic import BaseModel, TypeAdapter
@@ -23,7 +26,9 @@ from pydantic._internal._typing_extra import eval_type_lenient
from pydantic.json_schema import JsonSchemaValue
from app.helpers.logging import logger
+from app.helpers.monitoring import SpanAttributes, span_attribute, tracer
from app.models.call import CallStateModel
+from app.models.message import ToolModel
T = TypeVar("T")
_jinja = Environment(
@@ -75,6 +80,88 @@ class AbstractPlugin:
]
)
+ @tracer.start_as_current_span("plugin_execute_tool")
+ async def execute_tool(self, tool: ToolModel) -> None:
+ functions = self._available_functions()
+ json_str = tool.function_arguments
+ name = tool.function_name
+
+ # Confirm the function name exists, this is a security measure to prevent arbitrary code execution, plus, Pydantic validator is not used on purpose to comply with older tools plugins
+ if name not in functions:
+ res = f"Invalid function names {name}, available are {functions}."
+ logger.warning(res)
+ # Update tool
+ tool.content = res
+ # Enrich span
+ span_attribute(SpanAttributes.TOOL_RESULT, tool.content)
+ return
+
+ # Try to fix JSON args to catch LLM hallucinations
+ # See: https://community.openai.com/t/gpt-4-1106-preview-messes-up-function-call-parameters-encoding/478500
+ args: dict[str, Any] | Any = repair_json(
+ json_str=json_str,
+ return_objects=True,
+ ) # pyright: ignore
+
+ # Confirm the args are a dictionary
+ if not isinstance(args, dict):
+ logger.warning(
+ "Error decoding JSON args for function %s: %s...%s",
+ name,
+ json_str[:20],
+ json_str[-20:],
+ )
+ # Update tool
+ tool.content = (
+ f"Bad arguments, available are {functions}. Please try again."
+ )
+ # Enrich span
+ span_attribute(SpanAttributes.TOOL_RESULT, tool.content)
+ return
+
+ # Enrich span
+ span_attribute(SpanAttributes.TOOL_ARGS, json.dumps(args))
+ span_attribute(SpanAttributes.TOOL_NAME, name)
+
+ # Execute the function
+ try:
+ res = await getattr(self, name)(**args)
+ res_log = f"{res[:20]}...{res[-20:]}"
+ logger.info("Executed function %s (%s): %s", name, args, res_log)
+
+ # Catch wrong arguments
+ except TypeError as e:
+ logger.warning(
+ "Wrong arguments for function %s: %s. Error: %s",
+ name,
+ args,
+ e,
+ )
+ res = "Wrong arguments, please fix them and try again."
+ res_log = res
+
+ # Catch execution errors
+ except Exception as e:
+ logger.exception(
+ "Error executing function %s with args %s",
+ tool.function_name,
+ args,
+ )
+ res = f"Error: {e}."
+ res_log = res
+
+ # Update tool
+ tool.content = res
+ # Enrich span
+ span_attribute(SpanAttributes.TOOL_RESULT, tool.content)
+
+ @cache
+ def _available_functions(self) -> list[str]:
+ """
+ List all available functions of the plugin, including the inherited ones.
+ """
+ return [name for name, _ in getmembers(self.__class__, isfunction)]
+
async def _function_schema(
f: Callable[..., Any], **kwargs: Any
diff --git a/app/models/message.py b/app/models/message.py
index 43f9cc5..09eab8d 100644
--- a/app/models/message.py
+++ b/app/models/message.py
@@ -15,7 +15,6 @@ from openai.types.chat import (
from openai.types.chat.chat_completion_chunk import ChoiceDeltaToolCall
from pydantic import BaseModel, Field, field_validator
-from app.helpers.llm_utils import AbstractPlugin
from app.helpers.monitoring import tracer
_FUNC_NAME_SANITIZER_R = r"[^a-zA-Z0-9_-]"
@@ -100,85 +99,6 @@ class ToolModel(BaseModel):
},
)
- # TODO: Move this to AbstractPlugin to avoid doing live imports
- async def execute_function(self, plugin: AbstractPlugin) -> None:
- from app.helpers.config import CONFIG
- from app.helpers.logging import logger
-
- db = CONFIG.database.instance()
-
- json_str = self.function_arguments
- name = self.function_name
-
- # Confirm the function name exists, this is a security measure to prevent arbitrary code execution, plus, Pydantic validator is not used on purpose to comply with older tools plugins
- if name not in ToolModel._available_function_names():
- res = f"Invalid function names {name}, available are {ToolModel._available_function_names()}."
- logger.warning(res)
- self.content = res
- return
-
- # Try to fix JSON args to catch LLM hallucinations
- # See: https://community.openai.com/t/gpt-4-1106-preview-messes-up-function-call-parameters-encoding/478500
- args: dict[str, Any] | Any = repair_json(
- json_str=json_str,
- return_objects=True,
- ) # pyright: ignore
-
- if not isinstance(args, dict):
- logger.warning(
- "Error decoding JSON args for function %s: %s...%s",
- name,
- self.function_arguments[:20],
- self.function_arguments[-20:],
- )
- self.content = f"Bad arguments, available are {ToolModel._available_function_names()}. Please try again."
- return
-
- with tracer.start_as_current_span(
- name="message_execute_function",
- attributes={
- "args": json.dumps(args),
- "name": name,
- },
- ) as span:
- try:
- # Persist the call if updating it
- async with db.call_transac(
- call=plugin.call,
- scheduler=plugin.scheduler,
- ):
- res = await getattr(plugin, name)(**args)
- # Format pretty logs
- res_log = f"{res[:20]}...{res[-20:]}"
- logger.info("Executing function %s (%s): %s", name, args, res_log)
- except TypeError as e:
- logger.warning(
- "Wrong arguments for function %s: %s. Error: %s",
- name,
- args,
- e,
- )
- res = "Wrong arguments, please fix them and try again."
- res_log = res
- except Exception as e:
- logger.exception(
- "Error executing function %s with args %s",
- self.function_name,
- args,
- )
- res = f"Error: {e}."
- res_log = res
- span.set_attribute("result", res_log)
- self.content = res
-
- @staticmethod
- def _available_function_names() -> list[str]:
- from app.helpers.llm_tools import (
- DefaultPlugin,
- )
-
- return [name for name, _ in getmembers(DefaultPlugin, isfunction)]
-
class MessageModel(BaseModel):
# Immutable fields