Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
fix: Plugin result should be stored in the conversation and JSON parsed
Clémence Lesné85a2e555e408
diff --git a/models/message.py b/models/message.pyindex b43f7b4..ec7c278 100644--- a/models/message.py+++ b/models/message.py@@ -1,7 +1,7 @@from datetime import datetimefrom enum import Enumfrom pydantic import BaseModel, Field, validator-from typing import List, Union+from typing import Any, List, Unionfrom openai.types.chat import (ChatCompletionAssistantMessageParam,ChatCompletionMessageToolCallParam,@@ -12,6 +12,7 @@ from inspect import getmembers, isfunctionfrom openai.types.chat.chat_completion_chunk import ChoiceDeltaToolCallimport jsonimport re+from json_repair import repair_jsonFUNC_NAME_SANITIZER_R = r"[^a-zA-Z0-9_-]"@@ -84,46 +85,35 @@ class ToolModel(BaseModel):self.function_arguments += other.function.argumentsreturn self- async def execute_function(self, plugins: object) -> str:+ async def execute_function(self, plugins: object) -> None:from helpers.logging import build_loggerlogger = build_logger(__name__)name = self.function_name- # Parse args- try:- args: dict[str, Union[str, list[str], dict[str, str]]] = json.loads(- self.function_arguments- )- except json.JSONDecodeError:+ # Try to fix JSON args to catch some LLM hallucinations+ # See: https://community.openai.com/t/gpt-4-1106-preview-messes-up-function-call-parameters-encoding/478500+ args: dict[str, Any] = repair_json(+ json_str=self.function_arguments.replace("\\\\", "\\").replace("\\n", ""),+ return_objects=True,+ ) # type: ignore++ if args is None:logger.warn(f"Error decoding JSON args for function {name}: {self.function_arguments[:20]}...{self.function_arguments[-20:]}")- return f"Bad JSON format, impossible to execute function {name}"-- # Unescape content (double backslash, HTML entities, ...) for str and list- # TODO: Is there more to unescape?- for key, arg in args.items():- if isinstance(arg, str):- args[key] = arg.encode("raw_unicode_escape").decode("unicode_escape")- elif isinstance(arg, list):- for i, v in enumerate(arg):- args[key][i] = v.encode("raw_unicode_escape").decode(- "unicode_escape"- )- elif isinstance(arg, dict):- for k, v in arg.items():- args[key][k] = v.encode("raw_unicode_escape").decode(- "unicode_escape"- )+ self.content = "Not executed, bad arguments format"+ returntry:res = await getattr(plugins, name)(**args)- logger.info(f"Executing function {name} ({args}): {res[:50]}...")+ logger.info(f"Executing function {name} ({args}): {res[:20]}...{res[-20:]}")except Exception as e:- res = f"Error executing function {self.function_name}: {e}"- logger.warn(res)- return res+ logger.warn(+ f"Error executing function {self.function_name} with args {args}: {e}"+ )+ res = f"Not executed, error: {e}"+ self.content = res@staticmethoddef _available_function_names() -> List[str]:diff --git a/requirements.txt b/requirements.txtindex bac52a0..2bf4ea1 100644--- a/requirements.txt+++ b/requirements.txt@@ -11,6 +11,7 @@ azure-search-documents==11.6.0b1email-validator==2.1.0.post1 # Required for pydanticfastapi==0.109.2jinja2==3.1.3+json-repair==0.9.0mistune==3.0.2openai==1.12.0phonenumbers==8.13.30 # Required for pydantic-extra-types