Voorbeeld: Geautomatiseerd CRM
Op deze pagina
Een gespreksgestuurd CRM
Stel u een CRM voor waarin verkopers geen complexe interfaces meer hoeven te navigeren. Ze spreken met een assistent die automatisch contacten aanmaakt, bijwerkt en ophaalt. Dit is precies wat function calling u in staat stelt te bouwen. Het verschil met de betalingstracker uit de vorige les is aanzienlijk: tot nu toe las het model alleen gegevens. Hier schrijft het gegevens, waardoor de focus van de oefening verschuift naar validatie, bevestiging en het beheer van duplicaten.
U implementeert een conversationeel CRM met CRUD-bewerkingen (Create, Read, Update, Delete) op een contactendatabase.
De Gesimuleerde Database
Een Python-dictionary fungeert als database voor deze demonstratie. Twee contacten volstaan: één klant en één prospect. Deze opzet stelt ons in staat om later in de les een statusovergang te testen.
import json
import os
from mistralai.client import Mistral
# In-memory contact database (in production: PostgreSQL, MongoDB, etc.)
contacts_db = {
"CT001": {
"name": "Marie Dupont",
"email": "[email protected]",
"company": "TechCorp",
"role": "Chief Technology Officer",
"phone": "+33 6 12 34 56 78",
"status": "client",
"notes": "Interested in the enterprise solution"
},
"CT002": {
"name": "Pierre Martin",
"email": "[email protected]",
"company": "StartupIO",
"role": "CEO",
"phone": "+33 6 98 76 54 32",
"status": "prospect",
"notes": "Meeting scheduled for April"
}
}
next_id = 3 # Counter for new contacts
De CRUD-functies
get_contact en search_contacts behandelen leesbewerkingen. Laatstgenoemde accepteert een argument voor het zoekveld om te voorkomen dat er meerdere bijna identieke functies worden gemaakt. create_contact is de eerste functie die de systeemstatus wijzigt; deze illustreert een regel die in gespreksmodi vaak over het hoofd wordt gezien: uniciteitscontroles moeten in uw code zitten, nooit in de prompt die aan het model wordt gegeven. Niets verhindert dat een verkoper tweemaal hetzelfde contact dicteert; de e-mailverificatie aan het begin van de functie retourneert duplicate_email met de bestaande ID, waardoor het model de weigering nauwkeurig kan uitleggen.
update_contact hanteert een aanpak met optionele velden: alleen opgegeven velden worden gewijzigd en de functie retourneert een lijst met wat daadwerkelijk is veranderd. Deze lijst is niet louter decoratief; hij stelt de assistent in staat de wijziging te bevestigen met een exacte zin in plaats van een vaag “klaar”.
def get_contact(contact_id: str) -> str:
"""Retrieves information for a contact."""
if contact_id in contacts_db:
contact = contacts_db[contact_id].copy()
contact["contact_id"] = contact_id
return json.dumps(contact, ensure_ascii=False)
return json.dumps({"error": f"Contact {contact_id} not found"})
def search_contacts(query: str, field: str = "name") -> str:
"""Searches for contacts by name, company, or status."""
results = []
for cid, contact in contacts_db.items():
if field in contact and query.lower() in contact[field].lower():
entry = contact.copy()
entry["contact_id"] = cid
results.append(entry)
if results:
return json.dumps({"results": results, "count": len(results)},
ensure_ascii=False)
return json.dumps({"results": [], "count": 0,
"message": f"No contact found for '{query}' in '{field}'"})
def create_contact(name: str, email: str, company: str,
role: str = "", phone: str = "",
status: str = "prospect", notes: str = "") -> str:
"""Creates a new contact in the CRM."""
global next_id
# Check if email already exists
for cid, contact in contacts_db.items():
if contact["email"].lower() == email.lower():
return json.dumps({
"error": "duplicate_email",
"message": f"A contact with this email already exists: {cid}"
})
contact_id = f"CT{next_id:03d}"
next_id += 1
contacts_db[contact_id] = {
"name": name,
"email": email,
"company": company,
"role": role,
"phone": phone,
"status": status,
"notes": notes
}
return json.dumps({
"success": True,
"contact_id": contact_id,
"message": f"Contact {name} created with ID {contact_id}"
}, ensure_ascii=False)
def update_contact(contact_id: str, **fields) -> str:
"""Updates one or more fields of an existing contact."""
if contact_id not in contacts_db:
return json.dumps({"error": f"Contact {contact_id} not found"})
updated_fields = []
for key, value in fields.items():
if key in contacts_db[contact_id]:
contacts_db[contact_id][key] = value
updated_fields.append(key)
if updated_fields:
return json.dumps({
"success": True,
"contact_id": contact_id,
"updated_fields": updated_fields,
"message": f"Contact {contact_id} updated: {', '.join(updated_fields)}"
}, ensure_ascii=False)
return json.dumps({"error": "No valid fields to update"})
De parameter ensure_ascii=False die in verschillende returns voorkomt, is geen cosmetisch detail: zonder deze wordt “Interested” een reeks Unicode-escapesequenties in de context van het model, wat minder leesbaar is en meer tokens kost.
JSON-toolspecificaties
Twee mechanismen dragen hier het meest bij aan de betrouwbaarheid. De enum op status verhindert dat het model waarden verzint: het moet kiezen uit prospect, client, partner en inactive, waarmee uw data-integriteit wordt beschermd zonder extra validatie. De required-array doet de rest door verplichte velden te onderscheiden van optionele velden; voor create_contact heeft een contact zonder naam, e-mail of bedrijf geen zin, terwijl een telefoonnummer later kan worden toegevoegd.
tools = [
{
"type": "function",
"function": {
"name": "get_contact",
"description": "Retrieves all information for a contact by ID",
"parameters": {
"type": "object",
"properties": {
"contact_id": {
"type": "string",
"description": "Contact ID (e.g., CT001)"
}
},
"required": ["contact_id"]
}
}
},
{
"type": "function",
"function": {
"name": "search_contacts",
"description": "Searches for contacts by name, company, or status",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search term"
},
"field": {
"type": "string",
"enum": ["name", "company", "status", "role"],
"description": "Field to search in (default: name)"
}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "create_contact",
"description": "Creates a new contact in the CRM",
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Full name of the contact"
},
"email": {
"type": "string",
"description": "Email address of the contact"
},
"company": {
"type": "string",
"description": "Company name"
},
"role": {
"type": "string",
"description": "Job title or function within the company"
},
"phone": {
"type": "string",
"description": "Phone number"
},
"status": {
"type": "string",
"enum": ["prospect", "client", "partner", "inactive"],
"description": "Contact status"
},
"notes": {
"type": "string",
"description": "Free-form notes about the contact"
}
},
"required": ["name", "email", "company"]
}
}
},
{
"type": "function",
"function": {
"name": "update_contact",
"description": "Updates information for an existing contact",
"parameters": {
"type": "object",
"properties": {
"contact_id": {
"type": "string",
"description": "ID of the contact to modify (e.g., CT001)"
},
"name": {"type": "string", "description": "New name"},
"email": {"type": "string", "description": "New email"},
"company": {"type": "string", "description": "New company"},
"role": {"type": "string", "description": "New job title"},
"phone": {"type": "string", "description": "New phone number"},
"status": {
"type": "string",
"enum": ["prospect", "client", "partner", "inactive"],
"description": "New status"
},
"notes": {"type": "string", "description": "New notes"}
},
"required": ["contact_id"]
}
}
}
]
Dispatch en de lus
Omdat de functies van geen enkele externe objecten afhangen, reduceert de dispatch-dictionary zich tot een directe mapping. Het systeembericht bevat echter twee gedragsbeperkingen die niet in de code staan: bevestig elke actie voor het aanmaken of bijwerken met details, en vraag ontbrekende informatie op voordat u een contact aanmaakt. Zonder die tweede instructie neigt het model ertoe verplichte velden in te vullen met aannemelijke waarden.
available_functions = {
"get_contact": get_contact,
"search_contacts": search_contacts,
"create_contact": create_contact,
"update_contact": update_contact,
}
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
model = "mistral-large-latest"
messages = [
{
"role": "system",
"content": "You are a CRM assistant. You help sales reps "
"manage their contacts. Respond in English. "
"When you create or modify a contact, confirm "
"the action with details. Request missing "
"information before creating a contact."
}
]
Vier scenario’s en wat ze leren
Het eerste scenario laat zien dat het model zelf field="company" kiest, hoewel de gebruiker niets specifieks heeft opgegeven: de schema-enum leverde de opties en de formulering van de vraag deed de rest. Het tweede scenario biedt informatie in een warboel, zonder labels, en het model verdeelt deze correct over naam, e-mail, bedrijf en functietitel. Het derde is het rijkst: “Switch Pierre Martin to client” bevat geen ID, dus het model moet een zoekopdracht koppelen aan een update, waarbij het onderweg de contextuele opmerking afleidt. Het vierde herinnert ons eraan dat het model een functie kan hergebruiken voor een ander doel dan het letterlijke gebruik, om een telvraag te beantwoorden.
# Scenario 1: Search for a contact
chat("Find me contacts at TechCorp")
# -> The model calls search_contacts(query="TechCorp", field="company")
# -> "I found 1 contact at TechCorp: Marie Dupont (CT001),
# Chief Technology Officer, status client."
# Scenario 2: Create a contact
chat("Add a new contact: Sophie Laurent, [email protected], "
"DataViz, Data Scientist")
# -> The model calls create_contact(name="Sophie Laurent",
# email="[email protected]", company="DataViz", role="Data Scientist")
# -> "Contact created successfully! Sophie Laurent (CT003) has been added
# as a prospect at DataViz."
# Scenario 3: Update a status
chat("Switch Pierre Martin to client, he just signed")
# -> The model first searches for Pierre Martin, then calls
# update_contact(contact_id="CT002", status="client",
# notes="Contract signed in April 2026")
# -> "Pierre Martin (CT002) is now marked as a client.
# I added a note about the contract signature."
# Scenario 4: Question without a dedicated function
chat("How many prospects do we have?")
# -> The model calls search_contacts(query="prospect", field="status")
# -> "You currently have 1 prospect: Sophie Laurent at DataViz."
Naar productie zonder alles opnieuw te schrijven
De in-memory dictionary verdwijnt uiteraard zodra er meerdere gebruikers zijn. Het vervangen ervan door een echte database vereist echter slechts het aanraken van één laag: de functie vraagt de ORM of API van uw CRM aan en retourneert nog steeds dezelfde JSON-tekenreeks.
# Functions call your CRM's ORM or API
def get_contact_production(contact_id: str) -> str:
"""Production version with PostgreSQL."""
contact = db.session.query(Contact).filter_by(id=contact_id).first()
if contact:
return json.dumps(contact.to_dict(), ensure_ascii=False)
return json.dumps({"error": f"Contact {contact_id} not found"})
De rest van de code—tools, dispatch, conversatielus—blijft identiek. Dit is de kracht van deze architectuur: alleen de functies voor bedrijfslogica veranderen, en de conversatielaag blijft zich onbewust van uw keuzes voor persistentie.
Belangrijkste punten
- Function calling verandert een LLM in een natuurlijke interface voor een CRM
- CRUD-bewerkingen worden direct toegewezen aan functies met JSON Schema
- Het model kan binnen één gesprek een zoekopdracht ketenen met een update
- De architectuur is ontkoppeld: wijzig de database zonder de conversatielogica aan te raken
- Het systeembericht is cruciaal om het model te sturen op het gebied van bevestigingen en ontbrekende informatie