File size: 2,564 Bytes
84fb4ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import os
from retriever import get_retriever
from langchain.chains import RetrievalQA
from transformers import pipeline
from langchain_community.llms import HuggingFacePipeline
from langchain_community.llms import HuggingFaceEndpoint
from dotenv import load_dotenv

load_dotenv()

# Load retriever
retriever = get_retriever()

# Load Hugging Face LLM
# Load the model pipeline
pipe = pipeline(
    "text-generation",
    model="tiiuae/falcon-7b-instruct",
    trust_remote_code=True,
    device_map="auto",
    max_new_tokens=512,
    temperature=0.2
)

# Wrap in LangChain LLM
llm = HuggingFacePipeline(pipeline=pipe)

# Prompt templates
english_prompt_template = """

You are a helpful Nigerian legal assistant.

Answer clearly in English, keeping the legal facts correct.

After the answer, list the sources you used.



Question: {question}

Answer:

"""

pidgin_prompt_template = """

You be legal assistant wey sabi Nigerian law well well.

The user fit talk for English or Pidgin, but you go always answer for Nigerian Pidgin.

No change the legal facts, but make am simple so person wey no study law fit understand.

After you give the answer, put list of the sources wey you use.



Question: {question}

Answer for Nigerian Pidgin:

"""

# Create QA chain
qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    retriever=retriever,
    chain_type="stuff",
    return_source_documents=True
)

def chat():
    print("📜 KnowYourRight Bot")
    print("Type 'exit' to stop.\n")

    # Ask language mode
    while True:
        lang_choice = input("Choose mode: [1] English  [2] Pidgin: ").strip()
        if lang_choice in ["1", "2"]:
            break
        print("❌ Invalid choice. Please type 1 or 2.")

    pidgin_mode = lang_choice == "2"

    # Start chat loop
    while True:
        query = input("\nYou: ")
        if query.lower() in ["exit", "quit"]:
            break

        # Pick prompt based on mode
        if pidgin_mode:
            formatted_query = pidgin_prompt_template.format(question=query)
        else:
            formatted_query = english_prompt_template.format(question=query)

        result = qa_chain.invoke({"query": formatted_query})

        # Print answer
        print("\nBot:", result["result"])

        # Print sources
        print("\n📚 Sources:")
        for doc in result["source_documents"]:
            print("-", doc.metadata.get("source", "Unknown"))
        print("\n" + "-"*50)

if __name__ == "__main__":
    chat()