Primjer iz prakse: Automatizirani CRM
Na ovoj stranici
CRM vođen razgovorom
Zamisli CRM u kojem prodajni predstavnici više ne moraju navigirati kroz složena sučelja. Oni razgovaraju s asistentom koji automatski stvara, ažurira i dohvaća kontakte. Točno to ti omogućuje izgradnju pozivanjem funkcija. Razlika u odnosu na pratitelja plaćanja iz prethodne lekcije je značajna: dosad je model samo čitao podatke. Ovdje on i piše podatke, što vježbu usmjerava prema validaciji, potvrđivanju i upravljanju duplikatima.
Implementirat ćeš konverzacijski CRM s CRUD operacijama (Create, Read, Update, Delete) na bazi kontakata.
Simulirana baza podataka
Python rječnik služi kao baza podataka za ovu demonstraciju. Dva kontakta su dovoljna: jedan klijent i jedan potencijalni kupac. Ova postavka omogućuje nam kasnije u lekciji testiranje promjene statusa.
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
CRUD funkcije
get_contact i search_contacts obrađuju operacije čitanja. Potonja prihvaća argument polja za pretraživanje kako bi se izbjeglo stvaranje više gotovo identičnih funkcija. create_contact je prva funkcija koja modificira stanje sustava i ilustrira pravilo koje se u konverzacijskim načinima često zanemaruje: provjere jedinstvenosti moraju živjeti u tvom kodu, nikada u promptu danom modelu. Ništa ne sprječava prodajnog predstavnika da diktira isti kontakt dvaput; provjera e-pošte na početku funkcije vraća duplicate_email s postojećim ID-om, omogućujući modelu da precizno objasni odbijanje.
update_contact koristi pristup s opcionalnim poljima: modificiraju se samo navedena polja, a funkcija vraća popis onoga što se zapravo promijenilo. Taj popis nije dekorativan – omogućuje asistentu da potvrdi izmjenu točnom rečenicom umjesto neodređenog „gotovo“.
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"})
Parametar ensure_ascii=False prisutan u nekoliko povrata nije kozmetički detalj: bez njega, „Interested“ postaje niz Unicode escape sekvenci u kontekstu modela, što je manje čitljivo i skuplje u tokenima.
Specifikacije JSON alata
Dva mehanizma ovdje nose većinu pouzdanosti. enum na status sprječava model da izmišlja vrijednosti: mora birati između prospect, client, partner i inactive, štiteći integritet tvojih podataka bez dodatne validacije. Niz required obavlja ostatak razlikujući obavezna od opcionalnih polja – za create_contact, kontakt bez imena, e-pošte ili tvrtke nema smisla, dok broj telefona može pričekati.
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"]
}
}
}
]
Usmjeravanje i petlja
Budući da funkcije ne ovise o vanjskim objektima, rječnik za usmjeravanje svodi se na izravno mapiranje. Sistemska poruka, međutim, nosi dva ponašajna ograničenja koja nisu u kodu: potvrdi svaku radnju stvaranja ili ažuriranja s detaljima i zatraži nedostajuće informacije prije stvaranja kontakta. Bez te druge upute, model teži popunjavanju obaveznih polja vjerojatnim vrijednostima.
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."
}
]
Četiri scenarija i što nas uče
Prvi scenarij pokazuje kako model samostalno bira field="company" iako korisnik nije ništa specificirao: shema enum pružila je opcije, a formulacija pitanja učinila ostalo. Drugi pruža informacije u neredu, bez oznaka, a model ih ispravno raspoređuje među ime, e-poštu, tvrtku i titulu. Treći je najbogatiji: „Prebaci Pierrea Martina na klijenta“ ne sadrži ID, pa model mora lančano izvršiti pretraživanje, a zatim ažuriranje, usput zaključujući kontekstualnu bilješku. Četvrti nas podsjeća da model može prenamijeniti funkciju iz njezine doslovne uporabe kako bi odgovorio na pitanje o brojanju.
# 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."
Prelazak u proizvodnju bez potpunog prepisivanja
Rječnik u memoriji očito nestaje čim postoji više korisnika. Zamjena pravom bazom podataka, međutim, zahtijeva diranje samo jednog sloja: funkcija upituje ORM ili API tvog CRM-a i dalje vraća isti JSON niz.
# 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"})
Ostatak koda – alati, usmjeravanje, petlja razgovora – ostaje identičan. U tome je snaga ove arhitekture: mijenjaju se samo funkcije poslovne logike, a konverzacijski sloj ostaje nesvjestan tvojih izbora trajnosti podataka.
Ključne točke
- Pozivanje funkcija pretvara LLM u prirodno sučelje za CRM
- CRUD operacije izravno se mapiraju na funkcije s JSON shemom
- Model može lančano izvršiti pretraživanje, a zatim ažuriranje unutar jednog razgovora
- Arhitektura je odvojena: promijeni bazu podataka bez diranja logike razgovora
- Sistemska poruka ključna je za vođenje modela oko potvrda i nedostajućih informacija