Macdensten91's picture
Update app.py
f0915ac verified
raw
history blame
4.05 kB
import random
import re
from huggingface_hub import InferenceClient
# Initialize the InferenceClient with your Hugging Face API token
client = InferenceClient(
model="HuggingFaceH4/zephyr-7b-beta", # Specify your model here
token="your_huggingface_api_token" # Replace with your actual token
)
# Multilingual greetings dictionary
greetings = {
"en": ["hello", "hi", "hey", "good morning", "good afternoon", "good evening"],
"fr": ["bonjour", "salut", "coucou", "bonsoir"],
"am": ["ሰላም", "ሰላም እንደምን", "እንዴት"]
}
def is_greeting(query: str, lang: str) -> bool:
"""
Check if the user's query is a greeting in the specified language.
"""
greet_list = greetings.get(lang, greetings["en"])
# Convert to lowercase for non-Amharic languages
if lang != "am":
query = query.lower()
return any(query.startswith(greet) for greet in greet_list)
def generate_dynamic_out_of_scope_message(language: str) -> str:
"""
Generate a dynamic out-of-scope message using the Hugging Face Inference API.
"""
# Define language-specific system prompts
system_prompts = {
"en": (
"You are a helpful chatbot specializing in agriculture and agro-investment. "
"A user has asked a question unrelated to these topics. "
"Generate a friendly and intelligent out-of-scope response in English, encouraging the user to ask about agriculture or agro-investment."
),
"fr": (
"Vous êtes un chatbot utile spécialisé dans l'agriculture et les investissements agroalimentaires. "
"Un utilisateur a posé une question sans rapport avec ces sujets. "
"Générez une réponse amicale et intelligente en français, encourageant l'utilisateur à poser des questions sur l'agriculture ou les investissements agroalimentaires."
),
"am": (
"እርስዎ በግብርናና በአገልግሎት ስርዓተ-ቢዝነስ ውስጥ የሚሰራ እገዛ የሚሰጥ ቻትቦት ነው። "
"ተጠቃሚው ከእነዚህ ጉዳዮች ውጪ ጥያቄ አቀርቧል። "
"በአማርኛ የተሰጠ የውጭ ክፍል ምላሽ ይፍጠሩ፣ ተጠቃሚውን ለግብርና ወይም ለአገልግሎት ስርዓተ-ቢዝነስ ጥያቄዎች ለመጠየቅ ያበረታታ።"
)
}
prompt = system_prompts.get(language, system_prompts["en"])
messages = [{"role": "system", "content": prompt}]
# Call the model to generate the response
response = client.chat_completion(
messages,
max_tokens=80,
temperature=0.7,
top_p=0.95,
)
# Extract the generated message content
try:
out_message = response.choices[0].message.content
except AttributeError:
out_message = str(response)
return out_message.strip()
def is_domain_query(query: str) -> bool:
"""
Determine if the query is related to agriculture or agro-investment.
"""
domain_keywords = [
"agriculture", "farming", "crop", "agro", "investment", "soil",
"irrigation", "harvest", "organic", "sustainable", "agribusiness",
"livestock", "agroalimentaire", "agriculture durable"
]
return any(re.search(r"\b" + keyword + r"\b", query, re.IGNORECASE) for keyword in domain_keywords)
def handle_user_query(query: str, lang: str = "en") -> str:
"""
Process the user's query and provide an appropriate response.
"""
if is_greeting(query, lang):
return random.choice(greetings.get(lang, greetings["en"])).capitalize() + "!"
elif is_domain_query(query):
# Here you would integrate your domain-specific response generation
return "This is a domain-specific question. Processing accordingly..."
else:
return generate_dynamic_out_of_scope_message(lang)
# Example usage
user_query = "Tell me about space travel."
response = handle_user_query(user_query, lang="en")
print(response)