File size: 1,684 Bytes
d038098
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275d03f
d038098
 
 
 
 
 
 
 
 
 
 
275d03f
d038098
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d0492c
d038098
275d03f
 
d038098
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
from transformers import AutoTokenizer
from langchain_core.prompts import PromptTemplate
from typing import List
import models

tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")

raw_prompt = "{question}"

history_prompt = """
Given the following conversation provide a helpful answer to the follow up question.

Chat History:
{chat_history}

Follow Up question: {question}
helpful answer:
"""

standalone_prompt = """
Given the following conversation and a follow up question, rephrase the 
follow up question to be a standalone question, in its original language.

Chat History:
{chat_history}

Follow Up Input: {question}

Standalone question:
"""

rag_prompt = """
Answer the question based only on the following context:
{context}

Question: {standalone_question}
"""


def format_prompt(prompt):
    chat = [
        {"role": "system", "content": "You are a helpful AI assistant."},
        {"role": "user", "content": prompt},
    ]

    formatted_prompt = tokenizer.apply_chat_template(
        chat, 
        tokenize=False, 
        add_generation_prompt=True
    )

    return PromptTemplate.from_template(formatted_prompt)


def format_chat_history(messages: List[models.Message]):
    return '\n'.join([
        '{}: {}'.format(message.type, message.message)
        for message in messages
    ])

def format_context(docs: List[str]):
    return '\n\n'.join(docs)


raw_prompt_formatted = format_prompt(raw_prompt)
raw_prompt = PromptTemplate.from_template(raw_prompt)
history_prompt_formatted = format_prompt(history_prompt)
standalone_prompt_formatted = format_prompt(standalone_prompt)
rag_prompt_formatted = format_prompt(rag_prompt)