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

feat: Add sales team next actions into the call

Clémence Lesné8788b52f6fb2
diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.py
index 2732529..e4cde7f 100644
--- a/helpers/config_models/prompts.py
+++ b/helpers/config_models/prompts.py
@@ -8,6 +8,7 @@ from models.message import (
MessageModel,
Persona as MessagePersona,
)
+from models.next import Action as NextAction
from models.reminder import ReminderModel
from models.training import TrainingModel
from pydantic import computed_field, BaseModel
@@ -220,6 +221,44 @@ class LlmModel(BaseSettings, env_prefix="prompts_llm_"):
Text:
{text}
"""
+ next_system_tpl: str = """
+ Assitant will choose the next action from the company sales team point of view. Answer is a JSON object with the action to take and the justification for this action.
+
+ Assitant:
+ - Take as first priority the customer satisfaction
+ - Won't make any assumptions
+ - Write no more than a few sentences as justification
+
+ Available actions:
+ {actions}
+
+ Claim status:
+ {claim}
+
+ Reminders:
+ {reminders}
+
+ Conversation history:
+ {messages}
+
+ Response format:
+ {{
+ "action": "[action]",
+ "justification": "[justification]"
+ }}
+
+ Example #1:
+ {{
+ "action": "in_depth_study",
+ "justification": "The customer has a lot of questions about the insurance policy. They are not sure if they are covered for the incident. Contract seems to not 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."
+ }}
+ """
def default_system(self, phone_number: str) -> str:
from helpers.config import CONFIG
@@ -344,6 +383,20 @@ class LlmModel(BaseSettings, env_prefix="prompts_llm_"):
text=text,
)
+ def next_system(
+ self,
+ claim: ClaimModel,
+ messages: List[MessageModel],
+ reminders: List[ReminderModel],
+ ) -> str:
+ return self._return(
+ self.next_system_tpl,
+ actions=", ".join([action.value for action in NextAction]),
+ claim=_pydantic_to_str(claim),
+ messages=_pydantic_to_str(messages),
+ reminders=_pydantic_to_str(reminders),
+ )
+
def _return(
self, prompt_tpl: str, trainings: Optional[List[TrainingModel]] = None, **kwargs
) -> str:
diff --git a/helpers/llm.py b/helpers/llm.py
index f6ad95a..fd6ddba 100644
--- a/helpers/llm.py
+++ b/helpers/llm.py
@@ -10,18 +10,16 @@ from azure.core.exceptions import HttpResponseError
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from helpers.config import CONFIG
from helpers.logging import build_logger
-from openai import _types as openaiTypes
from openai import AsyncAzureOpenAI, AsyncStream
from openai.types.chat import (
ChatCompletionChunk,
- ChatCompletionMessage,
ChatCompletionMessageParam,
ChatCompletionToolParam,
)
-import asyncio
from openai.types.chat.chat_completion_chunk import ChoiceDelta
from tenacity import retry, stop_after_attempt, wait_random_exponential
-from typing import Any, AsyncGenerator, List, Optional
+from typing import Any, AsyncGenerator, List, Optional, Union
+import asyncio
_logger = build_logger(__name__)
@@ -55,13 +53,18 @@ async def completion_stream(
max_tokens: int,
tools: Optional[List[ChatCompletionToolParam]] = None,
) -> AsyncGenerator[ChoiceDelta, None]:
+ extra = {}
+
+ if tools:
+ extra["tools"] = tools
+
stream: AsyncStream[ChatCompletionChunk] = await _oai.chat.completions.create(
max_tokens=max_tokens,
messages=messages,
model=CONFIG.openai.gpt_model,
stream=True,
temperature=0, # Most focused and deterministic
- tools=tools or openaiTypes.NOT_GIVEN,
+ **extra,
)
async for chunck in stream:
yield chunck.choices[0].delta
@@ -71,16 +74,21 @@ async def completion_stream(
async def completion_sync(
messages: List[ChatCompletionMessageParam],
max_tokens: int,
- tools: Optional[List[ChatCompletionToolParam]] = None,
-) -> ChatCompletionMessage:
+ json_output: bool = False,
+) -> str:
+ extra = {}
+
+ if json_output:
+ extra["response_format"] = {"type": "json_object"}
+
res = await _oai.chat.completions.create(
max_tokens=max_tokens,
messages=messages,
model=CONFIG.openai.gpt_model,
temperature=0, # Most focused and deterministic
- tools=tools or openaiTypes.NOT_GIVEN,
+ **extra,
)
- return res.choices[0].message
+ return res.choices[0].message.content
async def safety_check(text: str) -> bool:
diff --git a/main.py b/main.py
index c3f9a23..fd8b2ec 100644
--- a/main.py
+++ b/main.py
@@ -31,6 +31,7 @@ from helpers.config_models.database import Mode as DatabaseMode
from jinja2 import Environment, FileSystemLoader, select_autoescape
from models.action import ActionModel, Indent as IndentAction
from models.call import CallModel
+from models.next import NextModel
from models.reminder import ReminderModel
from models.synthesis import SynthesisModel
from openai.types.chat import (
@@ -580,7 +581,7 @@ async def handle_play(
raise e
-async def gpt_completion(system: str, call: CallModel, max_tokens: int) -> str:
+async def gpt_completion(system: str, call: CallModel, max_tokens: int, json_output: bool = False) -> str:
_logger.debug(f"Running GPT completion ({call.call_id})")
messages: List[ChatCompletionMessageParam] = [
@@ -599,12 +600,11 @@ async def gpt_completion(system: str, call: CallModel, max_tokens: int) -> str:
content = None
try:
- res = await completion_sync(
+ content = await completion_sync(
+ json_output=json_output,
max_tokens=max_tokens,
messages=messages,
)
- content = res.content
-
except Exception:
_logger.warn(f"OpenAI API call error", exc_info=True)
@@ -972,7 +972,9 @@ async def gpt_chat(
full_content += local_content + " "
await user_callback(local_content)
- # Generate synthesis for the old claim
+ # Generate next action
+ background_tasks.add_task(post_call_next, call)
+ # Generate synthesis
background_tasks.add_task(post_call_synthesis, call)
# Add context of the last message, if not, LLM messed up and loop on this action
@@ -1143,6 +1145,7 @@ async def handle_hangup(client: CallConnectionClient, call: CallModel) -> None:
# Start post-call intelligence
await asyncio.gather(
+ post_call_next(call),
post_call_sms(call),
post_call_synthesis(call),
)
@@ -1269,6 +1272,38 @@ async def post_call_synthesis(call: CallModel) -> None:
await db.call_aset(call)
+# TODO: Param _retry_attempt may be replaced by the @retry decorator
+async def post_call_next(call: CallModel, _retry_attempt: int = 0) -> None:
+ """
+ Generate next action for the call.
+ """
+ content = await gpt_completion(
+ system=CONFIG.prompts.llm.next_system(
+ claim=call.claim,
+ messages=call.messages,
+ reminders=call.reminders,
+ ),
+ call=call,
+ json_output=True,
+ max_tokens=1000,
+ )
+
+ try:
+ next = NextModel.model_validate_json(content)
+ except ValidationError:
+ _logger.debug(f"Invalid next action: {content}")
+ if _retry_attempt > 3:
+ _logger.warn("LLM send back invalid next action, retry limit reached")
+ return
+ _logger.warn("LLM send back invalid next action, retrying")
+ await post_call_next(call, _retry_attempt + 1)
+ return
+
+ _logger.info(f"Next action ({call.call_id}): {next}")
+ call.next = next
+ await db.call_aset(call)
+
+
def _remove_message_actions(text: str) -> str:
"""
Remove action from content. AI often adds it by mistake event if explicitly asked not to.
diff --git a/models/call.py b/models/call.py
index 86d8d92..a512417 100644
--- a/models/call.py
+++ b/models/call.py
@@ -1,6 +1,7 @@
from datetime import datetime
from models.claim import ClaimModel
from models.message import MessageModel
+from models.next import NextModel
from models.reminder import ReminderModel
from models.synthesis import SynthesisModel
from pydantic import BaseModel, Field
@@ -15,6 +16,7 @@ class CallModel(BaseModel):
# Editable fields
claim: ClaimModel = Field(default_factory=ClaimModel)
messages: List[MessageModel] = []
+ next: Optional[NextModel] = None
phone_number: str
recognition_retry: int = Field(default=0)
reminders: List[ReminderModel] = []
diff --git a/models/next.py b/models/next.py
new file mode 100644
index 0000000..e12e0f5
--- /dev/null
+++ b/models/next.py
@@ -0,0 +1,14 @@
+from enum import Enum
+from pydantic import BaseModel
+
+
+class Action(str, Enum):
+ CASE_CLOSED = "case_closed"
+ COMMERCIAL_OFFER = "commercial_offer"
+ IN_DEPTH_STUDY = "in_depth_study"
+ PROPOSE_NEW_CONTRACT = "propose_new_contract"
+
+
+class NextModel(BaseModel):
+ action: Action
+ justification: str
diff --git a/public_website/report.html.jinja b/public_website/report.html.jinja
index 6eb8a68..aebc5a9 100644
--- a/public_website/report.html.jinja
+++ b/public_website/report.html.jinja
@@ -113,6 +113,19 @@ Déclaration de sinistre {{ call.claim.claim_id }}
{% endif %}
</div>
+ <!-- Reminders -->
+ <div class="rounded-md lg:ring-1 ring-neutral-200/60 dark:ring-neutral-700/60 p-4">
+ <h2 class="text-lg pb-4">⏭️ Prochaine action</h2>
+
+ {% if not call.next %}
+ <p class="text-neutral-600 dark:text-neutral-400">Aucune prochaine action pour l'instant.</p>
+ {% else %}
+ <p>
+ {{ call.next.action.value | replace("_", " " ) | capitalize }}.&nbsp;<span class="text-neutral-600 dark:text-neutral-400">{{ call.next.justification }}</span>
+ </p>
+ {% endif %}
+ </div>
+
<!-- Details -->
<div class="rounded-md lg:ring-1 ring-neutral-200/60 dark:ring-neutral-700/60">
<h2 class="text-lg px-4 pt-4">🔎 Détails</h2>