Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
refacto: Simplify LLM completion with response validation
Clémence Lesnédb1d6eba002f
diff --git a/helpers/call_events.py b/helpers/call_events.pyindex 29c0506..84dc814 100644--- a/helpers/call_events.py+++ b/helpers/call_events.py@@ -1,5 +1,6 @@from azure.communication.callautomation import DtmfTone, RecognitionChoicefrom azure.communication.callautomation.aio import CallAutomationClient+from pydantic import ValidationErrorfrom helpers.config import CONFIGfrom helpers.logging import logger, tracerfrom typing import Awaitable, Callable, Optional@@ -26,7 +27,8 @@ from helpers.call_utils import (handle_recognize_text,handle_transfer,)-from helpers.call_llm import llm_completion, llm_model, load_llm_chat+from helpers.call_llm import load_llm_chat+from helpers.llm_worker import completion_syncfrom models.next import NextModelimport asyncio@@ -431,9 +433,17 @@ async def _intelligence_sms(call: CallStateModel) -> None:"""Send an SMS report to the customer."""- content = await llm_completion(- text=CONFIG.prompts.llm.sms_summary_system(call),- call=call,+ def _validate(req: Optional[str]) -> tuple[bool, Optional[str], Optional[str]]:+ if not req:+ return False, "No SMS content", None+ if len(req) < 10:+ return False, "SMS content too short", None+ return True, None, req++ content = await completion_sync(+ res_type=str,+ system=CONFIG.prompts.llm.sms_summary_system(call),+ validation_callback=_validate,)# Delete action and style from the message as they are in the history and LLM hallucinates them@@ -474,38 +484,29 @@ async def _intelligence_synthesis(call: CallStateModel) -> None:"""logger.debug("Synthesizing call")- short, long = await asyncio.gather(- llm_completion(- call=call,- text=CONFIG.prompts.llm.synthesis_short_system(call),- ),- llm_completion(- call=call,- text=CONFIG.prompts.llm.citations_system(- call=call,- text=await llm_completion(- call=call,- text=CONFIG.prompts.llm.synthesis_long_system(call),- ),- ),- ),+ def _validate(+ req: Optional[str],+ ) -> tuple[bool, Optional[str], Optional[SynthesisModel]]:+ if not req:+ return False, "Empty response", None+ try:+ return True, None, SynthesisModel.model_validate_json(req)+ except ValidationError as e:+ return False, str(e), None++ synthesis = await completion_sync(+ res_type=SynthesisModel,+ system=CONFIG.prompts.llm.synthesis_system(call),+ validate_json=True,+ validation_callback=_validate,)- # Delete action and style from the message as they are in the history and LLM hallucinates them- _, short = extract_message_style(remove_message_action(short or ""))- _, long = extract_message_style(remove_message_action(long or ""))-- if not short or not long:+ if not synthesis:logger.warning("Error generating synthesis")return- logger.info(f"Short synthesis: {short}")- logger.info(f"Long synthesis: {long}")-- call.synthesis = SynthesisModel(- long=long,- short=short,- )+ logger.info(f"Synthesis: {synthesis}")+ call.synthesis = synthesisawait _db.call_aset(call)@@ -513,10 +514,23 @@ async def _intelligence_next(call: CallStateModel) -> None:"""Generate next action for the call."""- next = await llm_model(- call=call,- model=NextModel,- text=CONFIG.prompts.llm.next_system(call),+ logger.debug("Generating next action")++ def _validate(+ req: Optional[str],+ ) -> tuple[bool, Optional[str], Optional[NextModel]]:+ if not req:+ return False, "Empty response", None+ try:+ return True, None, NextModel.model_validate_json(req)+ except ValidationError as e:+ return False, str(e), None++ next = await completion_sync(+ res_type=NextModel,+ system=CONFIG.prompts.llm.next_system(call),+ validate_json=True,+ validation_callback=_validate,)if not next:diff --git a/helpers/call_llm.py b/helpers/call_llm.pyindex 877b5a5..a5364e9 100644--- a/helpers/call_llm.py+++ b/helpers/call_llm.py@@ -1,4 +1,4 @@-from typing import Awaitable, Callable, Optional, Type+from typing import Awaitable, Callablefrom azure.communication.callautomation.aio import CallAutomationClientfrom helpers.config import CONFIGfrom helpers.logging import logger@@ -21,15 +21,11 @@ from helpers.call_utils import (from helpers.llm_tools import LlmPluginsimport asynciofrom helpers.llm_worker import (- completion_model_sync,completion_stream,- completion_sync,MaximumTokensReachedError,- ModelType,SafetyCheckError,)from openai import APIError-from openai.types.chat import ChatCompletionSystemMessageParamimport time@@ -37,78 +33,6 @@ _cache = CONFIG.cache.instance()_db = CONFIG.database.instance()-async def llm_completion(text: Optional[str], call: CallStateModel) -> Optional[str]:- """- Run LLM completion from a system prompt and a Call model.-- If the system prompt is None, no completion will be run and None will be returned. Otherwise, the response of the LLM will be returned.- """- logger.info("Running LLM completion")-- if not text:- return None-- system = _llm_completion_system(text, call)- content = None-- try:- content = await completion_sync(- max_tokens=1000,- system=system,- )- except APIError as e:- logger.warning(f"OpenAI API call error: {e}")- except SafetyCheckError as e:- logger.warning(f"Safety Check error: {e}")-- return content---async def llm_model(- text: Optional[str], call: CallStateModel, model: Type[ModelType]-) -> Optional[ModelType]:- """- Run LLM completion from a system prompt, a Call model, and an expected model type as a return.-- The logic will try its best to return a model of the expected type, but it is not guaranteed. It it fails, `None` will be returned.- """- logger.debug("Running LLM model")-- if not text:- return None-- system = _llm_completion_system(text, call)- res = None-- try:- res = await completion_model_sync(- max_tokens=1000,- model=model,- system=system,- )- except APIError as e:- logger.warning(f"OpenAI API call error: {e}")-- return res---def _llm_completion_system(- system: str, call: CallStateModel-) -> list[ChatCompletionSystemMessageParam]:- messages = [- ChatCompletionSystemMessageParam(- content=CONFIG.prompts.llm.default_system(call),- role="system",- ),- ChatCompletionSystemMessageParam(- content=system,- role="system",- ),- ]- logger.debug(f"Messages: {messages}")- return messages--async def load_llm_chat(call: CallStateModel,client: CallAutomationClient,@@ -350,20 +274,11 @@ async def _execute_llm_chat(logger.info(f"Enhancing LLM chat with {len(trainings)} trainings")logger.debug(f"Trainings: {trainings}")- # Build system prompts- system = [- ChatCompletionSystemMessageParam(- content=CONFIG.prompts.llm.default_system(call),- role="system",- ),- ChatCompletionSystemMessageParam(- content=CONFIG.prompts.llm.chat_system(- call=call,- trainings=trainings,- ),- role="system",- ),- ]+ # System prompts+ system = CONFIG.prompts.llm.chat_system(+ call=call,+ trainings=trainings,+ )# Build pluginsplugins = LlmPlugins(diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.pyindex 2c18e2e..4b7b620 100644--- a/helpers/config_models/prompts.py+++ b/helpers/config_models/prompts.py@@ -5,9 +5,11 @@ from html import escapefrom logging import Loggerfrom models.call import CallStateModelfrom models.message import MessageModel-from models.next import ActionEnum as NextActionEnum+from models.next import NextModelfrom models.reminder import ReminderModel+from models.synthesis import SynthesisModelfrom models.training import TrainingModel+from openai.types.chat import ChatCompletionSystemMessageParamfrom pydantic import TypeAdapter, BaseModelfrom textwrap import dedentfrom typing import Optional@@ -179,17 +181,15 @@ class LlmModel(BaseModel):## Example 3Hello, I had difficulties to hear you. If you need help, let me know how I can help you. Have a nice day! {bot_name} from {bot_company}."""- synthesis_short_system_tpl: str = """+ synthesis_system_tpl: str = """# Objective- Summarize the call with the customer in a few words. The customer cannot reply to this message, but will read it in their web portal.+ Synthetize the call.# Rules- Answers in English, even if the customer speaks another language- Be concise- Consider all the conversation history, from the beginning- - Do not prefix the answer with any text (e.g., "The answer is", "Summary of the call")- - Prefix the answer with a determiner (e.g., "the theft of your car", "your broken window")- - Won't make any assumptions+ - Don't make any assumptions# Initial call objective{task}@@ -203,41 +203,8 @@ class LlmModel(BaseModel):# Conversation history{messages}- # Answer examples- - "the breakdown of your scooter"- - "the flooding in your field"- - "the theft of your car"- - "the water damage in your kitchen"- - "your broken window"- """- synthesis_long_system_tpl: str = """- # Objective- Summarize the call with the customer in a paragraph. The customer cannot reply to this message, but will read it in their web portal.-- # Rules- - Answers in English, even if the customer speaks another language- - Be concise- - Consider all the conversation history, from the beginning- - Do not include details of the call process- - Do not include personal details (e.g., name, phone number, address)- - Do not prefix the answer with any text (e.g., "The answer is", "Summary of the call")- - Include details stored in the claim, to make the customer confident that the situation is understood- - Prefer including details about the situation (e.g., what, when, where, how)- - Say "you" to refer to the customer, and "I" to refer to the assistant- - Use Markdown syntax to format the message with paragraphs, bold text, and URL- - Won't make any assumptions-- # Initial call objective- {task}-- # Claim status- {claim}-- # Reminders- {reminders}-- # Conversation history- {messages}+ # Response format in JSON+ {format}"""citations_system_tpl: str = """# Objective@@ -293,9 +260,6 @@ class LlmModel(BaseModel):# Initial call objective{task}- # Allowed actions- {actions}-# Claim status{claim}@@ -306,47 +270,13 @@ class LlmModel(BaseModel):{messages}# Response format in JSON- {{- "action": "[action]",- "justification": "[justification]"- }}-- ## Example 1- {{- "action": "in_depth_study",- "justification": "The customer has many questions about the insurance policy. They are not sure if they are covered for the incident. The contract seems not to be clear about this situation."- }}-- ## Example 2- {{- "action": "commercial_offer",- "justification": "The company planned the customer taxi ride from the wrong address. The customer is not happy about this situation."- }}-- ## Example 3- {{- "action": "customer_will_send_info",- "justification": "Document related to the damaged bike are missing. Documents are bike invoice, and the bike repair quote. The customer confirmed they will send them tomorrow by email."- }}-- ## Example 4- {{- "action": "requires_expertise",- "justification": "Described damages on the roof are more important than expected. Plus, customer is not sure if the insurance policy covers this kind of damage. The company needs to send an expert to evaluate the situation."- }}-- ## Example 5- {{- "action": "case_closed",- "justification": "Customer is satisfied with the service and confirmed the repair of the car is done. The case can be closed."- }}+ {format}"""def default_system(self, call: CallStateModel) -> str:from helpers.config import CONFIG- # TODO: Parse the date from the end-user timezone, allowing LLM to be used in multiple countries- return self._return(+ return self._format(self.default_system_tpl.format(bot_company=call.initiate.bot_company,bot_name=call.initiate.bot_name,@@ -358,110 +288,118 @@ class LlmModel(BaseModel):))- def chat_system(self, call: CallStateModel, trainings: list[TrainingModel]) -> str:+ def chat_system(+ self, call: CallStateModel, trainings: list[TrainingModel]+ ) -> list[ChatCompletionSystemMessageParam]:from models.message import (ActionEnum as MessageActionEnum,StyleEnum as MessageStyleEnum,)- return self._return(- self.chat_system_tpl,- actions=", ".join([action.value for action in MessageActionEnum]),- bot_company=call.initiate.bot_company,- claim=json.dumps(call.claim),- default_lang=call.lang.human_name,- reminders=TypeAdapter(list[ReminderModel])- .dump_json(call.reminders, exclude_none=True)- .decode(),- styles=", ".join([style.value for style in MessageStyleEnum]),- task=call.initiate.task,- trainings=trainings,- )-- def sms_summary_system(self, call: CallStateModel) -> str:- return self._return(- self.sms_summary_system_tpl,- bot_company=call.initiate.bot_company,- bot_name=call.initiate.bot_name,- claim=json.dumps(call.claim),- default_lang=call.lang.human_name,- messages=TypeAdapter(list[MessageModel])- .dump_json(call.messages, exclude_none=True)- .decode(),- reminders=TypeAdapter(list[ReminderModel])- .dump_json(call.reminders, exclude_none=True)- .decode(),- task=call.initiate.task,+ return self._messages(+ self._format(+ self.chat_system_tpl,+ actions=", ".join([action.value for action in MessageActionEnum]),+ bot_company=call.initiate.bot_company,+ claim=json.dumps(call.claim),+ default_lang=call.lang.human_name,+ reminders=TypeAdapter(list[ReminderModel])+ .dump_json(call.reminders, exclude_none=True)+ .decode(),+ styles=", ".join([style.value for style in MessageStyleEnum]),+ task=call.initiate.task,+ trainings=trainings,+ ),+ call=call,)- def synthesis_short_system(self, call: CallStateModel) -> str:- return self._return(- self.synthesis_short_system_tpl,- claim=json.dumps(call.claim),- messages=TypeAdapter(list[MessageModel])- .dump_json(call.messages, exclude_none=True)- .decode(),- reminders=TypeAdapter(list[ReminderModel])- .dump_json(call.reminders, exclude_none=True)- .decode(),- task=call.initiate.task,+ def sms_summary_system(+ self, call: CallStateModel+ ) -> list[ChatCompletionSystemMessageParam]:+ return self._messages(+ self._format(+ self.sms_summary_system_tpl,+ bot_company=call.initiate.bot_company,+ bot_name=call.initiate.bot_name,+ claim=json.dumps(call.claim),+ default_lang=call.lang.human_name,+ messages=TypeAdapter(list[MessageModel])+ .dump_json(call.messages, exclude_none=True)+ .decode(),+ reminders=TypeAdapter(list[ReminderModel])+ .dump_json(call.reminders, exclude_none=True)+ .decode(),+ task=call.initiate.task,+ ),+ call=call,)- def synthesis_long_system(self, call: CallStateModel) -> str:- return self._return(- self.synthesis_long_system_tpl,- claim=json.dumps(call.claim),- messages=TypeAdapter(list[MessageModel])- .dump_json(call.messages, exclude_none=True)- .decode(),- reminders=TypeAdapter(list[ReminderModel])- .dump_json(call.reminders, exclude_none=True)- .decode(),- task=call.initiate.task,+ def synthesis_system(+ self, call: CallStateModel+ ) -> list[ChatCompletionSystemMessageParam]:+ return self._messages(+ self._format(+ self.synthesis_system_tpl,+ claim=json.dumps(call.claim),+ format=json.dumps(SynthesisModel.model_json_schema()),+ messages=TypeAdapter(list[MessageModel])+ .dump_json(call.messages, exclude_none=True)+ .decode(),+ reminders=TypeAdapter(list[ReminderModel])+ .dump_json(call.reminders, exclude_none=True)+ .decode(),+ task=call.initiate.task,+ ),+ call=call,)def citations_system(- self, call: CallStateModel, text: Optional[str]- ) -> Optional[str]:+ self, call: CallStateModel, text: str+ ) -> list[ChatCompletionSystemMessageParam]:"""Return the formatted prompt. Prompt is used to add citations to the text, without cluttering the content itself.The citations system is only used if `text` param is not empty, otherwise `None` is returned."""- if not text:- return None-- return self._return(- self.citations_system_tpl,- claim=json.dumps(call.claim),- reminders=TypeAdapter(list[ReminderModel])- .dump_json(call.reminders, exclude_none=True)- .decode(),- text=text,+ return self._messages(+ self._format(+ self.citations_system_tpl,+ claim=json.dumps(call.claim),+ reminders=TypeAdapter(list[ReminderModel])+ .dump_json(call.reminders, exclude_none=True)+ .decode(),+ text=text,+ ),+ call=call,)- def next_system(self, call: CallStateModel) -> str:- return self._return(- self.next_system_tpl,- actions=", ".join([action.value for action in NextActionEnum]),- claim=json.dumps(call.claim),- messages=TypeAdapter(list[MessageModel])- .dump_json(call.messages, exclude_none=True)- .decode(),- reminders=TypeAdapter(list[ReminderModel])- .dump_json(call.reminders, exclude_none=True)- .decode(),- task=call.initiate.task,+ def next_system(+ self, call: CallStateModel+ ) -> list[ChatCompletionSystemMessageParam]:+ return self._messages(+ self._format(+ self.next_system_tpl,+ claim=json.dumps(call.claim),+ format=json.dumps(NextModel.model_json_schema()),+ messages=TypeAdapter(list[MessageModel])+ .dump_json(call.messages, exclude_none=True)+ .decode(),+ reminders=TypeAdapter(list[ReminderModel])+ .dump_json(call.reminders, exclude_none=True)+ .decode(),+ task=call.initiate.task,+ ),+ call=call,)- def _return(+ def _format(self,prompt_tpl: str,trainings: Optional[list[TrainingModel]] = None,**kwargs: str,) -> str:# Remove possible indentation then render the template- res = dedent(prompt_tpl.format(**kwargs)).strip()+ formatted_prompt = dedent(prompt_tpl.format(**kwargs)).strip()# Format trainings, if anyif trainings:@@ -473,14 +411,32 @@ class LlmModel(BaseModel):for training in trainings])- res += "\n\n# Trusted data you can use"- res += f"\n{trainings_str}"+ formatted_prompt += "\n\n# Trusted data you can use"+ formatted_prompt += f"\n{trainings_str}"# Remove newlines to avoid hallucinations issues with GPT-4 Turbo- res = " ".join([line.strip() for line in res.splitlines()])+ formatted_prompt = " ".join(+ [line.strip() for line in formatted_prompt.splitlines()]+ )- self.logger.debug(f"LLM prompt: {res}")- return res+ self.logger.debug(f"Formatted prompt: {formatted_prompt}")+ return formatted_prompt++ def _messages(+ self, system: str, call: CallStateModel+ ) -> list[ChatCompletionSystemMessageParam]:+ messages = [+ ChatCompletionSystemMessageParam(+ content=self.default_system(call),+ role="system",+ ),+ ChatCompletionSystemMessageParam(+ content=system,+ role="system",+ ),+ ]+ self.logger.debug(f"Messages: {messages}")+ return messages@cached_propertydef logger(self) -> Logger:diff --git a/helpers/llm_worker.py b/helpers/llm_worker.pyindex f35aa0e..54bcfa0 100644--- a/helpers/llm_worker.py+++ b/helpers/llm_worker.py@@ -39,7 +39,7 @@ from helpers.resources import resources_dirfrom models.message import MessageModelfrom opentelemetry.instrumentation.openai import OpenAIInstrumentorfrom os import environ-from typing import AsyncGenerator, Optional, Type, TypeVar, Union+from typing import AsyncGenerator, Callable, Optional, TypeVar, Unionimport jsonimport tiktoken@@ -57,6 +57,7 @@ logger.info()ModelType = TypeVar("ModelType", bound=BaseModel)+T = TypeVar("T")class SafetyCheckError(Exception):@@ -227,56 +228,77 @@ async def _completion_stream_worker(raise MaximumTokensReachedError(f"Maximum tokens reached {max_tokens}")+@retry(+ reraise=True,+ retry=retry_if_exception_type(ValidationError),+ stop=stop_after_attempt(3),+ wait=wait_random_exponential(multiplier=0.8, max=8),+)@tracer.start_as_current_span("completion_sync")async def completion_sync(- max_tokens: int,+ res_type: type[T],system: list[ChatCompletionSystemMessageParam],- json_output: bool = False,-) -> Optional[str]:- """- Returns a completion.+ validation_callback: Callable[+ [Optional[str]], tuple[bool, Optional[str], Optional[T]]+ ],+ validate_json: bool = False,+ _previous_result: Optional[str] = None,+ _retries_remaining: int = 3,+ _validation_error: Optional[str] = None,+) -> Optional[T]:+ # Initialize prompts+ messages = system+ if _validation_error:+ messages.append(+ ChatCompletionSystemMessageParam(+ role="system",+ content=f"""+ A validation error occurred during the previous attempt.++ # Previous result+ {_previous_result or "N/A"}++ # Error details+ {_validation_error}+ """,+ )+ )- Catch errors for a maximum of 10 times (internal + `RateLimitError`). If the error persists, try with the fast LLM. If it fails again, raise the error.- """- # Try a first time with slow LLM- try:- return await _completion_sync_worker(- is_fast=False,- max_tokens=max_tokens,+ # Generate+ res_content = await _completion_sync_worker(+ is_fast=False,+ json_output=validate_json,+ system=messages,+ )++ # Validate+ is_valid, validation_error, res_object = validation_callback(res_content)+ if not is_valid: # Retry if validation failed+ if _retries_remaining == 0:+ logger.error(f"LLM validation error: {validation_error}")+ return None+ logger.warning(+ f"LLM validation error, retrying ({_retries_remaining} retries left)"+ )+ return await completion_sync(+ res_type=res_type,system=system,- json_output=json_output,+ validate_json=validate_json,+ validation_callback=validation_callback,+ _previous_result=res_content,+ _retries_remaining=_retries_remaining - 1,+ _validation_error=validation_error,)- except Exception as e:- if not any(isinstance(e, exception) for exception in _retried_exceptions):- raise e- logger.warning(f"{e.__class__.__name__} error, trying with fast LLM")- # Try more times with fast LLM, if it fails again, raise the error- retryed = AsyncRetrying(- reraise=True,- retry=retry_any(- *[retry_if_exception_type(exception) for exception in _retried_exceptions]- ),- stop=stop_after_attempt(- 10- ), # Usage is async and long-lived, so stop after 10 attempts- wait=wait_random_exponential(multiplier=0.8, max=8),- )- async for attempt in retryed:- with attempt:- return await _completion_sync_worker(- is_fast=True,- max_tokens=max_tokens,- system=system,- json_output=json_output,- )+ # Return after validation or if failed too many times+ return res_objectasync def _completion_sync_worker(is_fast: bool,- max_tokens: int,system: list[ChatCompletionSystemMessageParam],json_output: bool = False,+ max_tokens: Optional[int] = None,) -> Optional[str]:"""Returns a completion.@@ -295,61 +317,47 @@ async def _completion_sync_worker(system=system,)- try:- res = await client.chat.completions.create(- max_tokens=max_tokens,- messages=prompt,- model=platform.model,- seed=42, # Reproducible results- temperature=0, # Most focused and deterministic- **extra,- )- except BadRequestError as e:- if e.code == "content_filter":- raise SafetyCheckError("Issue detected in prompt")- raise e- choice = res.choices[0]- if choice.finish_reason == "content_filter": # Azure OpenAI content filter- raise SafetyCheckError(- f"Issue detected in generation: {choice.message.content}"- )- if choice.finish_reason == "length":- raise MaximumTokensReachedError(f"Maximum tokens reached {max_tokens}")+ # Try more times with fast LLM, if it fails again, raise the error+ retryed = AsyncRetrying(+ reraise=True,+ retry=retry_any(+ *[retry_if_exception_type(exception) for exception in _retried_exceptions]+ ),+ stop=stop_after_attempt(+ 10+ ), # Usage is async and long-lived, so stop after 10 attempts+ wait=wait_random_exponential(multiplier=0.8, max=8),+ )+ async for attempt in retryed:+ with attempt:+ try:+ res = await client.chat.completions.create(+ max_tokens=max_tokens,+ messages=prompt,+ model=platform.model,+ seed=42, # Reproducible results+ temperature=0, # Most focused and deterministic+ **extra,+ )+ except BadRequestError as e:+ if e.code == "content_filter":+ raise SafetyCheckError("Issue detected in prompt")+ raise e+ choice = res.choices[0]+ if choice.finish_reason == "content_filter": # Azure OpenAI content filter+ raise SafetyCheckError(+ f"Issue detected in generation: {choice.message.content}"+ )+ if choice.finish_reason == "length":+ raise MaximumTokensReachedError(f"Maximum tokens reached {max_tokens}")content = choice.message.contentreturn content or None-@retry(- reraise=True,- retry=retry_if_exception_type(ValidationError),- stop=stop_after_attempt(3),- wait=wait_random_exponential(multiplier=0.8, max=8),-)[email protected]_as_current_span("completion_model_sync")-async def completion_model_sync(- max_tokens: int,- model: Type[ModelType],- system: list[ChatCompletionSystemMessageParam],-) -> Optional[ModelType]:- """- Generate a Pydantic model from a completion.-- Catch Pydantic validation errors for a maximum of 3 times, then raise the error.- """- res = await completion_sync(- json_output=True,- max_tokens=max_tokens,- system=system,- )- if not res:- return None- return model.model_validate_json(res)--def _limit_messages(context_window: int,- max_tokens: int,+ max_tokens: Optional[int],messages: list[MessageModel],model: str,system: list[ChatCompletionSystemMessageParam],@@ -368,6 +376,8 @@ def _limit_messages(The context size is the maximum number of tokens allowed by the model. The messages are selected from the newest to the oldest, until the context or the maximum number of messages is reached."""+ max_tokens = max_tokens or 0 # Default+counter = 0max_context = context_window - max_tokensselected_messages = []diff --git a/models/next.py b/models/next.pyindex cc0e2e9..b5db202 100644--- a/models/next.py+++ b/models/next.py@@ -1,5 +1,5 @@from enum import Enum-from pydantic import BaseModel+from pydantic import BaseModel, Fieldclass ActionEnum(str, Enum):@@ -12,5 +12,21 @@ class ActionEnum(str, Enum):class NextModel(BaseModel):- action: ActionEnum- justification: str+ action: ActionEnum = Field(+ description="Action to take after the call, based on the conversation, for the company."+ )+ justification: str = Field(+ description="""+ Justification for the selected action.++ # Rules+ - No more than a few sentences++ # Response examples+ - "Customer is satisfied with the service and confirmed the repair of the car is done. The case can be closed."+ - "Described damages on the roof are more important than expected. Plus, customer is not sure if the insurance policy covers this kind of damage. The company needs to send an expert to evaluate the situation."+ - "Document related to the damaged bike are missing. Documents are bike invoice, and the bike repair quote. The customer confirmed they will send them tomorrow by email."+ - "The company planned the customer taxi ride from the wrong address. The customer is not happy about this situation."+ - "The customer has many questions about the insurance policy. They are not sure if they are covered for the incident. The contract seems not to be clear about this situation."+ """+ )diff --git a/models/readiness.py b/models/readiness.pyindex d0b50f7..4960724 100644--- a/models/readiness.py+++ b/models/readiness.py@@ -3,14 +3,14 @@ from pydantic import BaseModelfrom typing import List-class ReadinessStatus(str, Enum):+class ReadinessEnum(str, Enum):FAIL = "fail"OK = "ok"class ReadinessCheckModel(BaseModel):id: str- status: ReadinessStatus+ status: ReadinessEnumclass ReadinessModel(BaseModel):diff --git a/models/synthesis.py b/models/synthesis.pyindex 6d61632..25f7448 100644--- a/models/synthesis.py+++ b/models/synthesis.py@@ -1,6 +1,32 @@-from pydantic import BaseModel+from pydantic import BaseModel, Fieldclass SynthesisModel(BaseModel):- long: str- short: str+ long: str = Field(+ description="""+ Summarize the call with the customer in a paragraph. The customer cannot reply to this message, but will read it in their web portal.++ # Rules+ - Do not include details of the call process+ - Do not include personal details (e.g., name, phone number, address)+ - Include details stored in the claim, to make the customer confident that the situation is understood+ - Prefer including details about the situation (e.g., what, when, where, how)+ - Say "you" to refer to the customer, and "I" to refer to the assistant+ - Use Markdown syntax to format the message with paragraphs, bold text, and URL+ """+ )+ short: str = Field(+ description="""+ Summarize the call with the customer in a few words. The customer cannot reply to this message, but will read it in their web portal.++ # Rules+ - Prefix the answer with a determiner (e.g., "the theft of your car", "your broken window")++ # Response examples+ - "the breakdown of your scooter"+ - "the flooding in your field"+ - "the theft of your car"+ - "the water damage in your kitchen"+ - "your broken window"+ """+ )