Q&A Systems Example
Create powerful question-answering systems that can understand context, provide accurate answers, and learn from your data.Overview
This example shows how to build:- Customer support chatbots
- Internal knowledge bases
- FAQ systems
- Technical documentation assistants
Basic Q&A System
Copy
Ask AI
from meibelai import Meibelai
import os
client = Meibelai(
api_key_header=os.getenv("MEIBELAI_API_KEY_HEADER")
)
# Create a knowledge base
kb = client.datasources.create(
name="Product Knowledge Base",
description="Product documentation and FAQs"
)
Building the Knowledge Base
Copy
Ask AI
# Add FAQ entries
faqs = [
{
"question": "How do I reset my password?",
"answer": "Go to Settings > Security > Reset Password. You'll receive an email with instructions."
},
{
"question": "What payment methods do you accept?",
"answer": "We accept all major credit cards, PayPal, and bank transfers for enterprise accounts."
},
{
"question": "Is there a free trial?",
"answer": "Yes, we offer a 14-day free trial with full access to all features."
}
]
for faq in faqs:
client.dataelements.create(
datasource_id=kb.id,
name=f"FAQ: {faq['question']}",
content=f"Q: {faq['question']}\nA: {faq['answer']}",
metadata={
"type": "faq",
"category": "support"
}
)
Simple Q&A Interface
Copy
Ask AI
def answer_question(question: str) -> str:
response = client.rag.chat(
messages=[
{"role": "user", "content": question}
],
datasource_ids=[kb.id],
confidence_threshold=0.7,
execution_control={
"temperature": 0.2, # Lower temperature for consistency
"max_tokens": 150
}
)
if response.confidence_score < 0.7:
return "I'm not sure about that. Please contact support for help."
return response.choices[0].message.content
# Test the system
print(answer_question("How can I reset my password?"))
print(answer_question("Do you have a free trial?"))
Advanced Q&A with Context
Copy
Ask AI
class QASession:
def __init__(self, datasource_id: str):
self.datasource_id = datasource_id
self.history = []
def ask(self, question: str) -> dict:
# Add question to history
self.history.append({"role": "user", "content": question})
# Get answer with context
response = client.rag.chat(
messages=self.history[-5:], # Last 5 messages for context
datasource_ids=[self.datasource_id],
confidence_threshold=0.6,
execution_control={
"enable_tracing": True,
"temperature": 0.3
}
)
answer = response.choices[0].message.content
confidence = response.confidence_score
# Add answer to history
self.history.append({"role": "assistant", "content": answer})
return {
"answer": answer,
"confidence": confidence,
"sources": response.sources if hasattr(response, 'sources') else []
}
# Use the session-based Q&A
session = QASession(kb.id)
print(session.ask("What payment methods are available?"))
print(session.ask("Can I use Bitcoin?")) # Follow-up question
Multi-lingual Support
Copy
Ask AI
# Add multi-lingual content
languages = ["es", "fr", "de"]
base_content = "Our product helps you manage tasks efficiently."
for lang in languages:
translated = client.rag.chat(
messages=[
{"role": "system", "content": f"Translate to {lang}"},
{"role": "user", "content": base_content}
]
)
client.dataelements.create(
datasource_id=kb.id,
name=f"Product Description ({lang})",
content=translated.choices[0].message.content,
metadata={"language": lang, "type": "translation"}
)
# Answer in different languages
def answer_in_language(question: str, language: str = "en"):
response = client.rag.chat(
messages=[
{"role": "system", "content": f"Answer in {language}"},
{"role": "user", "content": question}
],
datasource_ids=[kb.id],
execution_control={
"metadata_filter": {"language": language}
}
)
return response.choices[0].message.content
Performance Optimization
Copy
Ask AI
# Implement caching for common questions
from functools import lru_cache
import hashlib
@lru_cache(maxsize=100)
def cached_answer(question_hash: str, datasource_id: str):
# This would be called with a hash of the question
return client.rag.chat(
messages=[{"role": "user", "content": question}],
datasource_ids=[datasource_id]
)
def smart_answer(question: str, datasource_id: str):
# Create hash of question for caching
q_hash = hashlib.md5(question.lower().strip().encode()).hexdigest()
# Check cache first
try:
return cached_answer(q_hash, datasource_id)
except:
# Fallback to direct call if cache fails
return answer_question(question)
Analytics and Improvement
Copy
Ask AI
# Track questions and improve the system
def track_and_answer(question: str):
response = answer_question(question)
# Log the interaction
client.dataelements.create(
datasource_id=kb.id,
name=f"User Question: {question[:50]}",
content=f"Question: {question}\nAnswer: {response}\nTimestamp: {datetime.now()}",
metadata={
"type": "user_interaction",
"answered": response != "I'm not sure about that."
}
)
return response
# Analyze common unanswered questions
def find_knowledge_gaps():
# This would analyze logged interactions
# to find frequently asked but unanswered questions
pass
Best Practices
- Regular Updates: Keep your knowledge base current
- Confidence Thresholds: Set appropriate thresholds for your use case
- Fallback Handling: Always have a plan for low-confidence answers
- User Feedback: Collect feedback to improve responses
- Testing: Regularly test with real user questions