File size: 4,387 Bytes
a498df4
 
 
0ea45f7
 
 
dc956a7
0ea45f7
a498df4
 
 
 
 
 
 
 
 
 
dc956a7
 
 
 
 
 
 
 
 
 
 
 
 
a498df4
 
dc956a7
a498df4
 
 
 
 
 
dc956a7
a498df4
 
 
dc956a7
a498df4
dc956a7
a498df4
 
 
 
 
 
 
 
 
 
 
dc956a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ea45f7
 
 
 
dc956a7
3327888
 
 
dc956a7
 
 
 
 
 
 
 
 
 
3327888
dc956a7
 
3327888
 
 
a498df4
0ea45f7
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import gradio as gr
from huggingface_hub import InferenceClient

"""
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
"""
# Using Hugging Face Zephyr 7B for better contextual responses
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")


def respond(
    message,
    history: list[tuple[str, str]],
    system_message,
    max_tokens,
    temperature,
    top_p,
):
    # Define system message to act as MPSC/UPSC assistant
    system_message = """You are an intelligent and well-informed MPSC/UPSC Assistant Chatbot. 
    Your job is to assist users with questions related to:
    - MPSC and UPSC Syllabus
    - Exam Patterns and Timelines
    - Study Materials and References
    - Important Current Affairs
    - Guidance on Optional Subjects
    - Previous Year Question Papers
    - Tips for Prelims, Mains, and Interview Preparation
    Provide relevant and concise answers along with reliable references or study materials.
    """

    messages = [{"role": "system", "content": system_message}]

    # Load conversation history for context
    for val in history:
        if val[0]:
            messages.append({"role": "user", "content": val[0]})
        if val[1]:
            messages.append({"role": "assistant", "content": val[1]})

    # Add user’s latest query
    messages.append({"role": "user", "content": message})

    response = ""
    references = ""

    # Generate chatbot response
    for message in client.chat_completion(
        messages,
        max_tokens=max_tokens,
        stream=True,
        temperature=temperature,
        top_p=top_p,
    ):
        token = message.choices[0].delta.content
        response += token
        yield response

    # Generate additional references and notes based on user query
    references = generate_references(message)
    if references:
        response += f"\n\n📚 **References & Study Notes:**\n{references}"
        yield response


def generate_references(query):
    """Generate references and study notes based on user query."""
    if "syllabus" in query.lower():
        return (
            "- UPSC Syllabus: [Official UPSC Website](https://www.upsc.gov.in)\n"
            "- MPSC Syllabus: [Official MPSC Website](https://mpsc.gov.in)"
        )
    elif "current affairs" in query.lower():
        return (
            "- The Hindu, PIB, Yojana Magazine\n"
            "- Monthly Current Affairs PDFs (Vision IAS, Insights IAS)"
        )
    elif "prelims" in query.lower():
        return (
            "- Prelims Strategy: [UPSC Topper's Insights](https://www.insightsonindia.com)\n"
            "- Previous Year Papers: [Download Here](https://upsc.gov.in/previous-year-papers)"
        )
    elif "mains" in query.lower():
        return (
            "- Mains Answer Writing: [IAS Baba, Forum IAS]\n"
            "- Optional Subject Notes: Refer to standard books (Laxmikanth, Bipan Chandra, etc.)"
        )
    elif "interview" in query.lower():
        return (
            "- Mock Interview Preparation: [Drishti IAS, Vision IAS]\n"
            "- DAF Analysis and Personality Tips"
        )
    else:
        return (
            "- Standard Books for All Subjects: NCERTs, Laxmikanth, Spectrum\n"
            "- Regular Updates on Exam Patterns"
        )


"""
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
"""
# Create Gradio Chat Interface
demo = gr.ChatInterface(
    respond,
    additional_inputs=[
        gr.Textbox(value="You are a smart MPSC/UPSC Assistant.", label="System message"),
        gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max Tokens (Length of Response)"),
        gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature (Creativity Level)"),
        gr.Slider(
            minimum=0.1,
            maximum=1.0,
            value=0.95,
            step=0.05,
            label="Top-p (Nucleus Sampling for Better Results)",
        ),
    ],
    title="🎯 MPSC/UPSC Assistant Chatbot",
    description="Ask anything related to MPSC/UPSC preparation, syllabus, tips, and study materials. The chatbot provides answers with references and helpful notes for your exam preparation.",
)


if __name__ == "__main__":
    demo.launch()