1. Kiến trúc tổng thể AI trong Odoo 19
1.1. Pattern tích hợp AI
Trong Odoo, AI KHÔNG phải là 1 module standalone mà thường đi theo pattern:
Odoo Module (CRM / HR / Accounting)
↓
Service Layer (Python)
↓
AI Provider (OpenAI / Local Model / API)
↓
Return → write vào model / UI suggestion
👉 Điểm quan trọng:
- AI call thường nằm ở service layer, không đặt trực tiếp trong model core
- Kết quả AI được:
- hiển thị (suggestion)
- hoặc persist (write vào field)
1.2. Kiến trúc chuẩn nên dùng
class AiService(models.AbstractModel):
_name = ‘ai.service’
def call_llm(self, prompt):
# wrapper để dễ swap provider
response = self._call_openai(prompt)
return response
def _call_openai(self, prompt):
# call external API
pass
👉 Tại sao cần wrapper:
- Dễ đổi OpenAI → local LLM (Llama, Mistral…)
- Control timeout / retry / logging
2. AI Assistant trong Odoo (Chatter / CRM)
2.1. Use case: generate email reply
Flow:
mail.message → lấy context
↓
build prompt
↓
AI generate content
↓
show suggestion (không auto send)
Code sample:
def generate_reply(self, message_id):
message = self.env[‘mail.message’].browse(message_id)
prompt = f”””
Customer message:
{message.body}
Generate a professional reply:
“””
result = self.env[‘ai.service’].call_llm(prompt)
return {
‘suggested_reply’: result
}
👉 Best practice:
- Không auto gửi email → luôn require user confirm
- Prompt cần include:
- tone (formal / friendly)
- language
2.2. Hook vào UI (OWL)
Trong Odoo 17+ (và dự kiến Odoo 19):
- Extend component:
patch(Chatter.prototype, ‘ai_suggestion’, {
async onClickGenerateReply() {
const result = await this.rpc({
route: ‘/ai/generate_reply’,
params: { message_id: this.message.id }
});
this.state.suggestion = result.suggested_reply;
}
});
3. AI Lead Scoring (CRM)
3.1. Approach phổ biến
Cách 1: Rule-based + AI hybrid
score = 0
if lead.expected_revenue > 10000:
score += 20
ai_score = self.env[‘ai.service’].predict_lead(lead)
score += ai_score
Cách 2: Full AI scoring
def predict_lead(self, lead):
prompt = f”””
Lead info:
– Industry: {lead.industry_id.name}
– Revenue: {lead.expected_revenue}
– Country: {lead.country_id.name}
Predict conversion probability (0-100)
“””
return int(self.call_llm(prompt))
3.2. Performance issue
⚠️ Không được gọi AI trực tiếp trong create/write
❌ Sai:
@api.model
def create(self, vals):
record = super().create(vals)
record.ai_score = self.env[‘ai.service’].predict_lead(record)
👉 Sẽ:
- chậm UI
- dễ timeout
✅ Đúng:
- dùng queue job / cron
def cron_compute_ai_score(self):
leads = self.search([(‘ai_score’, ‘=’, False)])
for lead in leads:
lead.ai_score = self.env[‘ai.service’].predict_lead(lead)
4. AI OCR (Accounting)
4.1. Flow xử lý hóa đơn



4
attachment → AI OCR → JSON
↓
mapping → account.move
↓
auto-fill fields
4.2. Code mapping
def process_invoice(self, attachment):
ocr_data = self.env[‘ai.service’].extract_invoice(attachment)
vals = {
‘partner_id’: self._find_partner(ocr_data[‘vendor’]),
‘invoice_date’: ocr_data[‘date’],
‘amount_total’: ocr_data[‘total’],
}
move = self.env[‘account.move’].create(vals)
return move
4.3. Vấn đề thực tế
- OCR sai format → cần validation layer
- Không nên auto-post invoice
- Luôn cần user review step
5. AI trong HR (CV Matching)
5.1. Matching JD ↔ CV
def match_candidate(self, candidate, job):
prompt = f”””
Job:
{job.description}
Candidate:
{candidate.resume_text}
Score match from 0-100
“””
return int(self.env[‘ai.service’].call_llm(prompt))
5.2. Optimization
👉 Không nên:
- call AI mỗi lần mở form
👉 Nên:
- compute + store
match_score = fields.Integer(store=True)
- recompute khi:
- CV change
- JD change
6. AI Automation Workflow
6.1. Example: approve OT
def ai_check_ot(self, ot):
prompt = f”””
OT hours: {ot.hours}
Employee history: {ot.employee_id.ot_history}
Is this abnormal? (yes/no)
“””
return self.call_llm(prompt)
6.2. Combine rule + AI
if ot.hours > 4:
if ai_result == ‘yes’:
ot.state = ‘to_review’
👉 Không nên trust AI 100%
7. Logging, Retry, Timeout (rất quan trọng)
7.1. Wrapper chuẩn
def call_llm(self, prompt):
try:
return self._call(prompt)
except Exception as e:
_logger.error(“AI error: %s”, e)
return False
7.2. Retry strategy
- retry 2–3 lần
- exponential backoff
8. Security & Cost
8.1. Data leak
⚠️ Không gửi:
- salary
- personal data nhạy cảm
👉 cần:
- anonymize data trước khi gửi AI
8.2. Cost control
- cache result
- batch request
- limit usage per user
9. Best Practices (rút ra từ thực tế)
✅ Nên làm
- Tách AI service layer
- Dùng async (cron / queue)
- Luôn có human review step
- Cache kết quả
❌ Không nên
- Call AI trong loop lớn
- Call AI trong onchange
- Tin AI 100%
- Không logging
10. Kết luận
Với Odoo + AI:
👉 Dev không chỉ code business logic nữa, mà phải:
- Thiết kế flow AI hợp lý
- Control performance + cost
- Đảm bảo data & UX
Vui lòng đăng nhập để bình luận.