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 citations to the summary

Clémence Lesnéfc4505542257
diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.py
index 077cbbd..31f3ab6 100644
--- a/helpers/config_models/prompts.py
+++ b/helpers/config_models/prompts.py
@@ -3,17 +3,24 @@ from fastapi.encoders import jsonable_encoder
from functools import cached_property
from logging import Logger
from models.claim import ClaimModel
-from models.message import Action as MessageAction, MessageModel
+from models.message import (
+ Action as MessageAction,
+ MessageModel,
+ Persona as MessagePersona,
+)
from models.reminder import ReminderModel
from models.training import TrainingModel
from pydantic import computed_field, BaseModel
from pydantic_settings import BaseSettings
from textwrap import dedent
-from typing import List, Optional, Union
+from typing import List, Optional, Union, Set
import json
-def _pydantic_to_str(model: Optional[Union[BaseModel, List[BaseModel]]]) -> str:
+def _pydantic_to_str(
+ model: Optional[Union[BaseModel, List[BaseModel]]],
+ exclude: Optional[Set[str]] = None,
+) -> str:
"""
Convert a Pydantic model to a JSON string.
"""
@@ -21,9 +28,9 @@ def _pydantic_to_str(model: Optional[Union[BaseModel, List[BaseModel]]]) -> str:
return ""
return json.dumps(
jsonable_encoder(
- model.model_dump()
+ model.model_dump(exclude=exclude)
if isinstance(model, BaseModel)
- else [m.model_dump() for m in model]
+ else [m.model_dump(exclude=exclude) for m in model]
)
)
@@ -161,6 +168,7 @@ class LlmModel(BaseSettings, env_prefix="prompts_llm_"):
- Prefer including details about the incident (e.g. what, when, where, how)
- Say "you" to refer to the customer, and "I" to refer to the assistant
- Take into consideration all the conversation history, from the beginning
+ - Use Markdown syntax to format the message with paragraphs, bold text, and URL
- Won't make any assumptions
Claim status:
@@ -172,6 +180,46 @@ class LlmModel(BaseSettings, env_prefix="prompts_llm_"):
Conversation history:
{messages}
"""
+ citations_tpl: str = """
+ Assitant will add Markdown citations to the text. Citations are used to add additional context to the text, without cluttering the content itself.
+
+ Assitant:
+ - Add as many citations as needed to the text to make it fact-checkable
+ - Only use exact words from the text as citations
+ - Treats a citation as a word or a group of words
+ - Use claim, reminders, and messages extracts as citations
+ - Won't make any assumptions
+ - Write citations as Markdown abbreviations at the end of the text (e.g. "*[words from the text]: extract from the conversation")
+
+ Claim status:
+ {claim}
+
+ Reminders:
+ {reminders}
+
+ Conversation history:
+ {messages}
+
+ Response format:
+ [source text]\\n
+ *[extract from text]: "citation from claim, reminders, or messages"
+
+ Example #1:
+ The car accident of yesterday.\\n
+ *[of yesterday]: "That was yesterday"
+
+ Example #2:
+ # Holes in the roof of the garden shed.\\n
+ *[in the roof]: "The holes are in the roof"
+
+ Example #2:
+ You have reported a claim following a fall in the parking lot. A reminder has been created to follow up on your medical appointment scheduled for the day after tomorrow.\\n
+ *[the parking lot]: "I stumbled into the supermarket parking lot"
+ *[your medical appointment]: "I called my family doctor, I have an appointment for the day after tomorrow."
+
+ Text:
+ {text}
+ """
def default_system(self, phone_number: str) -> str:
from helpers.config import CONFIG
@@ -250,7 +298,28 @@ class LlmModel(BaseSettings, env_prefix="prompts_llm_"):
claim=_pydantic_to_str(claim),
conversation_lang=CONFIG.workflow.conversation_lang,
messages=_pydantic_to_str(messages),
+ )
+
+ def citations(
+ self,
+ claim: ClaimModel,
+ messages: List[MessageModel],
+ reminders: List[ReminderModel],
+ text: str,
+ ) -> str:
+ return self._return(
+ self.citations_tpl,
+ claim=_pydantic_to_str(claim),
+ messages=_pydantic_to_str(
+ [
+ message
+ for message in messages
+ if message.persona is not MessagePersona.TOOL
+ ],
+ exclude={"tool_calls"},
+ ), # Filter out tool messages, to avoid LLM to cite itself
reminders=_pydantic_to_str(reminders),
+ text=text,
)
def _return(
diff --git a/main.py b/main.py
index fcca181..49c197e 100644
--- a/main.py
+++ b/main.py
@@ -59,16 +59,18 @@ from models.claim import ClaimModel
from pydantic import ValidationError
from uuid import UUID
import json
-from helpers.llm import completion_stream, completion_sync, safety_check
+import mistune
-# Jinja templates
+# Jinja configuration
jinja = Environment(
autoescape=select_autoescape(),
enable_async=True,
loader=FileSystemLoader("public_website"),
)
+# Jinja custom functions
jinja.filters["quote_plus"] = lambda x: quote_plus(str(x)) if x else ""
+jinja.filters["markdown"] = lambda x: mistune.create_markdown(escape=False, plugins=["abbr", "speedup", "url"])(x) if x else "" # type: ignore
# Azure Communication Services
source_caller = PhoneNumberIdentifier(CONFIG.communication_service.phone_number)
@@ -1205,8 +1207,19 @@ async def post_call_synthesis(call: CallModel) -> None:
max_tokens=100,
),
gpt_completion(
- system=CONFIG.prompts.llm.synthesis_long_system(
- call.claim, call.messages, call.reminders
+ system=CONFIG.prompts.llm.citations(
+ claim=call.claim,
+ messages=call.messages,
+ reminders=call.reminders,
+ text=await gpt_completion(
+ system=CONFIG.prompts.llm.synthesis_long_system(
+ claim=call.claim,
+ messages=call.messages,
+ reminders=call.reminders,
+ ),
+ call=call,
+ max_tokens=1000,
+ ),
),
call=call,
max_tokens=1000,
diff --git a/public_website/report.html.jinja b/public_website/report.html.jinja
index 19049dc..6eb8a68 100644
--- a/public_website/report.html.jinja
+++ b/public_website/report.html.jinja
@@ -24,7 +24,9 @@ Déclaration de sinistre {{ call.claim.claim_id }}
{% if not call.synthesis.long %}
<p class="text-neutral-600 dark:text-neutral-400">Aucune synthèse pour l'instant.</p>
{% else %}
- <p>{{ call.synthesis.long }}</p>
+ <div class="space-y-2">
+ {{ call.synthesis.long | markdown }}
+ </div>
{% endif %}
</div>
</div>
diff --git a/requirements.txt b/requirements.txt
index e44d9bf..aa4b44c 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -9,6 +9,7 @@ azure-identity==1.15.0 # Required for all Azure SDKs
azure-search-documents==11.4.0b11
fastapi==0.108.0
jinja2==3.1.3
+mistune==3.0.2
openai==1.10.0
phonenumbers==8.13.28 # Required for pydantic-extra-types
pydantic-extra-types==2.4.1