File size: 3,383 Bytes
f80362a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d34c3c1
 
f80362a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from logging_config import logger
from summarizer import truncate_and_summarize
import streamlit as st
from curriculum import CURRICULUM_SUMMARY
from token_counter import count_tokens

# Function to build the prompt
def build_prompt(user_query, retrieved_chunks, messages):
    """
    Build the prompt for the LLM:
    - Include system prompts from secrets
    - Include the curriculum summary
    - Summarize older conversation history
    - Add retrieved chunks as system context
    - Include user query at the end
    """
    logger.info("Building prompt for the model.")

    # Summarize older messages if needed
    messages = truncate_and_summarize(messages)

    # Load system prompts from secrets
    try:
        socratic_guide = st.secrets["SOCRATIC_GUIDE"] #v3
        prometheus_prompt = st.secrets["PROMETHEUS_PROMPT"] #v3
        logger.info("Successfully loaded system prompts from secrets.")
    except KeyError as e:
        logger.error(f"Missing key in secrets.toml: {e}")
        raise ValueError(f"Missing secret key: {e}")

    # Initialize the prompt messages
    prompt_messages = []

    # Add the Socratic guide to the prompt
    prompt_messages.append({"role": "system", "content": socratic_guide})

    # Add the placeholder prompt to the prompt
    prompt_messages.append({"role": "system", "content": prometheus_prompt})

    # Include the curriculum summary
    curriculum_instructions = f"""
    Here are the learning goals for this class based on the TDSB's Curriculum. Ensure that your responses are aligned with these goals:\n
    {CURRICULUM_SUMMARY}
    """
    prompt_messages.append({"role": "system", "content": curriculum_instructions})

    # Add conversation history
    for m in messages:
        prompt_messages.append({"role": m["role"], "content": m["content"]})

    # Add retrieved chunks as system context
    if retrieved_chunks:
        chunks_text = "\n".join([f"Page {c['page_num']}:\n{c['content']}" for c in retrieved_chunks])
        retrieved_content_instruction = (
    "Considering your previous instructions, you must use the retrieved content to guide and position your responses and follow-up questions, relying solely on this information as your source of truth."
    "Do not use any other prior or external knowledge or make assumptions beyond the retrieved content provided below to respond to user queries. if the content is insufficient to answer the question, tell the student to consider consulting alternative resources. This dynamic approach ensures students develop both essential knowledge and the ability to reason critically and independently."
    "Retrieved chunks:"
)
        prompt_messages.append({"role": "system", "content": retrieved_content_instruction + "\n" + chunks_text})


    # Add the user's query
    prompt_messages.append({"role": "user", "content": user_query})

    # Count tokens in the final prompt
    try:
        token_data = count_tokens(prompt_messages)
        logger.info(f"Total tokens for prompt: {token_data['total']}")
        logger.info(f"Token breakdown by role: {token_data['by_role']}")
    except Exception as e:
        logger.error(f"Error counting tokens: {e}")
        raise ValueError("Failed to count tokens for the prompt.")

    #logger.info("Prompt successfully built. Prompt messages: %s", json.dumps(prompt_messages, indent=4))
    return prompt_messages