Spaces:
Runtime error
Runtime error
Upload 6 files
Browse files- chainlit.md +39 -0
- chatbot.py +166 -0
- classes.py +51 -0
- config.json +3 -0
- methods.py +84 -0
- prompts.py +124 -0
chainlit.md
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Hi, I'm TransparentGPT! 🚀❤️🔥
|
2 |
+
|
3 |
+
I am a chatbot that is able to clarify my reasoning, explain my thought process, and cite the sources that I used for my response.
|
4 |
+
|
5 |
+
I provide intermediate responses when I receive your query, expand upon that query, and am looking for sources to generate my response.
|
6 |
+
|
7 |
+
The sources that I use for my response are exposed by 🫐 **prompt engineering** 🫐, which means I am told to only use sources that I can provide links for. You can then click on these links to verify if the response I provided was correct or not. Along with each source, I output a percentage that shows how helpful that source was to my response.*
|
8 |
+
|
9 |
+
I also provide a percentage of how confident I am in each answer.**
|
10 |
+
|
11 |
+
In the Settings UI that can be found by clicking the gear icon in the message box, I provide a suite of customizable features!
|
12 |
+
|
13 |
+
Picking a 🪼 **large language model** 🪼 (LLM):
|
14 |
+
Large language models are AI systems that allow me to understand and output human-like natural language. You can pick from a handful of Meta, MistralAI, and Microsoft's open-source LLM's!
|
15 |
+
|
16 |
+
Display sources:
|
17 |
+
You can choose if you want me to display what 💎 **sources** 💎 I used for my response. I show my sources by default.
|
18 |
+
|
19 |
+
Number of sources:
|
20 |
+
You can choose the number of sources you want me to use for my response.
|
21 |
+
|
22 |
+
Prompt template:
|
23 |
+
You can choose which 🦋 **prompt template** 🦋 I use. A prompt template essentially tells me how to act and speak when I respond to you.You can experiment with a doctor, genz, food-critic, and media-critic prompt template!
|
24 |
+
|
25 |
+
Query expansion:
|
26 |
+
You can choose if you want to use 🥶 **query expansion** 🥶. If so, you can also choose what kind of query expansion I use! Query expansion allows me to improve my response by "secretly" expanding your query with related terms behind-the-scenes. This allows me to find more relevant sources.
|
27 |
+
|
28 |
+
Temperature:
|
29 |
+
You can choose how 🏙 **consistent** 🏙 my responses will be.
|
30 |
+
|
31 |
+
#### I am built with Langchain, Chainlit, Nebius Studio, Open-source Large Language Models, a bit of web scraping, and some vector similarity analysis on text embeddings.
|
32 |
+
|
33 |
+
- **My Github:** [TransparentGPT](https://github.com/rrachelhuangg/TransparentGPT) 🔗
|
34 |
+
|
35 |
+
\* Calculating the relevance of each score: The bot is only allowed to use Wikipedia sources, for which direct links can be provided and the text content of the page is more easily scraped. I scrape the text content of the source using the Revisions API. Then, I compare the scraped source text and my response text via a cosine vector similarity analysis. Please note that the relevance scores provided with each source will seem pretty low because the scraped text of the sources is likely longer than my response and may contain HTML or other related
|
36 |
+
formatting text, though I try to minimize non-natural language text in the scraped content.
|
37 |
+
|
38 |
+
** Calculating how confident I am in my answer: I calculate the negative log-likelihood of each token in my response, relative to the position of other tokens. The average of these values can represent how confident I am in my response, and this form of confidence calculating is formally called "perplexity."
|
39 |
+
|
chatbot.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import chainlit as cl
|
3 |
+
from langchain.memory.buffer import ConversationBufferMemory
|
4 |
+
from langchain_openai import ChatOpenAI, OpenAI
|
5 |
+
from langchain.chains import LLMChain
|
6 |
+
from prompts import default_prompt_template, doctor_prompt_template, default_prompt_template_no_sources, doctor_prompt_template_no_sources, default_quirky_genz_prompt, default_quirky_genz_prompt_no_sources, default_food_critic_prompt, default_food_critic_prompt_no_sources, default_media_critic_prompt, default_media_critic_prompt_no_sources
|
7 |
+
from dotenv import load_dotenv
|
8 |
+
from chainlit.input_widget import Select, Switch, Slider
|
9 |
+
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
|
10 |
+
from math import exp
|
11 |
+
import numpy as np
|
12 |
+
from typing import Any, Dict, List, Tuple
|
13 |
+
from langchain_core.output_parsers import BaseOutputParser
|
14 |
+
from difflib import SequenceMatcher
|
15 |
+
from methods import test_scrape_sim, update_config, load_config, generate_hypothetical_answer, highest_log_prob
|
16 |
+
import json
|
17 |
+
from classes import LineListOutputParser, TransparentGPTSettings
|
18 |
+
import emoji
|
19 |
+
|
20 |
+
#setting environment variables (non-Nebius API access keys)
|
21 |
+
#HAVE CLASSES BE IMPORT FROM OTHER FILES TO CLEAN UP CODE!! proper documentation and typing are v important
|
22 |
+
#also don't forget to refactor!^
|
23 |
+
#have a requirements.txt file if not deployed?
|
24 |
+
load_dotenv()
|
25 |
+
|
26 |
+
config = load_config()
|
27 |
+
num_sources = config["num_sources"]
|
28 |
+
|
29 |
+
TransparentGPT_settings = TransparentGPTSettings()
|
30 |
+
|
31 |
+
@cl.on_chat_start
|
32 |
+
async def start():
|
33 |
+
greeting = f"Hello! I am TransparentGPT, a chatbot that is able to clarify my reasoning 🧠, explain my thought process 🙊, and cite the sources 📚 that I used for my response. \n\n I also provide a suite of customizable features! 😁 \n\n You can find my customization options in the settings panel that opens up when you click on the gear icon below 🔨. \n\n Click on the ReadME button in the top right of your screen to learn more about how I work. 🫶"
|
34 |
+
await cl.Message(greeting).send()
|
35 |
+
settings = await cl.ChatSettings(
|
36 |
+
[
|
37 |
+
Select(
|
38 |
+
id="Model",
|
39 |
+
label="Select Model",
|
40 |
+
description="Choose which large language model you want to interact with.",
|
41 |
+
values=["Meta Llama 3.1", "Meta Llama 3.3", "MistralAI", "Dolphin Mixtral", "Microsoft Mini"],
|
42 |
+
initial_index=1,
|
43 |
+
),
|
44 |
+
Switch(
|
45 |
+
id="Display Sources",
|
46 |
+
label="Display Sources",
|
47 |
+
description = "Choose to have sources for response displayed.",
|
48 |
+
initial=True
|
49 |
+
),
|
50 |
+
Select(
|
51 |
+
id="Prompt Template",
|
52 |
+
label="Prompt Template",
|
53 |
+
description="Determines the type of bot you interact with.",
|
54 |
+
values=["default", "doctor", "genz", "food_critic", "media_critic"],
|
55 |
+
initial_index=0,
|
56 |
+
),
|
57 |
+
Select(
|
58 |
+
id="Query Expansion",
|
59 |
+
label="Use Query Expansion",
|
60 |
+
description = "Use query expansion to improve response context.",
|
61 |
+
items = TransparentGPT_settings.query_expansion_options,
|
62 |
+
initial_value="No query expansion"
|
63 |
+
),
|
64 |
+
Slider(
|
65 |
+
id="Number of Sources",
|
66 |
+
label="Number of Sources",
|
67 |
+
description="Choose the number of sources you want the bot to use for its response.",
|
68 |
+
initial=3,
|
69 |
+
min=1,
|
70 |
+
max=10,
|
71 |
+
step=1
|
72 |
+
),
|
73 |
+
Slider(
|
74 |
+
id="Temperature",
|
75 |
+
label="Temperature",
|
76 |
+
description="Choose the desired consistency of bot response.",
|
77 |
+
initial=0.7,
|
78 |
+
min=0,
|
79 |
+
max=2,
|
80 |
+
step=0.1
|
81 |
+
),
|
82 |
+
]
|
83 |
+
).send()
|
84 |
+
|
85 |
+
@cl.on_settings_update
|
86 |
+
async def start(settings):
|
87 |
+
update_config(settings['Number of Sources'])
|
88 |
+
TransparentGPT_settings.update_settings(settings)
|
89 |
+
|
90 |
+
@cl.on_message
|
91 |
+
async def handle_message(message: cl.Message):
|
92 |
+
await cl.Message("Your message was received successfully. I am working on generating my response. Please wait for a few seconds...").send()
|
93 |
+
question = message.content
|
94 |
+
expanded_query = ''
|
95 |
+
if TransparentGPT_settings.query_expansion != 'No query expansion':
|
96 |
+
if TransparentGPT_settings.query_expansion == 'Basic query expansion':
|
97 |
+
t = 'Return a one sentence thorough description of this content: {question}'
|
98 |
+
pt = PromptTemplate(input_variables=['question'], template=t)
|
99 |
+
init_chain = pt | TransparentGPT_settings.llm
|
100 |
+
expanded_query = init_chain.invoke({"question": message.content, "num_sources": TransparentGPT_settings.num_sources}).content
|
101 |
+
elif TransparentGPT_settings.query_expansion == 'Multiquery expansion':
|
102 |
+
output_parser = LineListOutputParser()
|
103 |
+
pt = PromptTemplate(
|
104 |
+
input_variables=['question'],
|
105 |
+
template="""
|
106 |
+
You are an AI language model assistant. Your task is to generate give different versions of the given user question to retrieve
|
107 |
+
context for your response. By generating multiple perspectives on the user question, your goal is to help the user overcome
|
108 |
+
some of hte limitations of the distance-based similarity search. Provide these alternative questions separated by newlines.
|
109 |
+
Original question: {question},
|
110 |
+
"""
|
111 |
+
)
|
112 |
+
init_chain = pt | TransparentGPT_settings.llm | output_parser
|
113 |
+
expanded_query = ' '.join(init_chain.invoke({'question': message.content, "num_sources": TransparentGPT_settings.num_sources}))
|
114 |
+
elif TransparentGPT_settings.query_expansion == "Hypothetical answer":
|
115 |
+
hypothetical_answer = generate_hypothetical_answer(message.content)
|
116 |
+
expanded_query = f'{message.content} {hypothetical_answer.content}'
|
117 |
+
if expanded_query!='':
|
118 |
+
await cl.Message(f"Using {TransparentGPT_settings.query_expansion}, your query is now: {expanded_query}. This expanded query will help me find more relevant information for my response.").send()
|
119 |
+
no_source_prompt=""
|
120 |
+
if expanded_query == '' and not TransparentGPT_settings.display_sources:
|
121 |
+
no_source_prompt = TransparentGPT_settings.prompt_mappings[TransparentGPT_settings.prompt_name+"_no_sources"]
|
122 |
+
expanded_query = no_source_prompt.invoke({"question": question, "num_sources": TransparentGPT_settings.num_sources})
|
123 |
+
elif expanded_query == '' and TransparentGPT_settings.display_sources:
|
124 |
+
expanded_query = TransparentGPT_settings.prompt.invoke({"question":question, "num_sources":TransparentGPT_settings.num_sources})
|
125 |
+
elif expanded_query !='' and not TransparentGPT_settings.display_sources:
|
126 |
+
no_source_prompt = TransparentGPT_settings.prompt_mappings[TransparentGPT_settings.prompt_name+"_no_sources"]
|
127 |
+
expanded_query = no_source_prompt.invoke({"question": expanded_query, "num_sources": TransparentGPT_settings.num_sources})
|
128 |
+
elif expanded_query !='' and TransparentGPT_settings.display_sources:
|
129 |
+
expanded_query = TransparentGPT_settings.prompt.invoke({"question":expanded_query, "num_sources":TransparentGPT_settings.num_sources})
|
130 |
+
await cl.Message("I have begun looking for relevant sources to answer your query, and am giving them a similarity score to show you how relevant they are to my response.").send()
|
131 |
+
response = TransparentGPT_settings.llm.invoke(expanded_query)
|
132 |
+
similarity_values = []
|
133 |
+
if no_source_prompt=="":
|
134 |
+
temp = response.content
|
135 |
+
sources = []
|
136 |
+
count = 0
|
137 |
+
while "*" in temp:
|
138 |
+
if count < num_sources:
|
139 |
+
link_idx = temp.rfind("*")
|
140 |
+
source = temp[link_idx+1:]
|
141 |
+
similarity_values += [test_scrape_sim(source, response.content)]
|
142 |
+
temp = temp[:link_idx]
|
143 |
+
count += 1
|
144 |
+
else:
|
145 |
+
break
|
146 |
+
temp = response.content
|
147 |
+
here = 2
|
148 |
+
count = 0
|
149 |
+
n_label = num_sources
|
150 |
+
if len(similarity_values) > 0:
|
151 |
+
while "*" in temp:
|
152 |
+
if count < num_sources:
|
153 |
+
link_idx = temp.rfind("*")
|
154 |
+
response.content = response.content[:link_idx] + f"Source {n_label} relevance score: " + str(round(similarity_values[here],3)) + "%\n" + response.content[link_idx+1:]
|
155 |
+
temp = temp[:link_idx]
|
156 |
+
count += 1
|
157 |
+
here -= 1
|
158 |
+
n_label -= 1
|
159 |
+
else:
|
160 |
+
break
|
161 |
+
output_message = response.content + f"\n I am {highest_log_prob(response.response_metadata["logprobs"]['content'])}% confident in this response."
|
162 |
+
await cl.Message(output_message).send()
|
163 |
+
|
164 |
+
|
165 |
+
if __name__ == '__main__':
|
166 |
+
start()
|
classes.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain_core.output_parsers import BaseOutputParser
|
2 |
+
from typing import List
|
3 |
+
from prompts import default_prompt_template, doctor_prompt_template, default_prompt_template_no_sources, doctor_prompt_template_no_sources, default_quirky_genz_prompt, default_quirky_genz_prompt_no_sources, default_food_critic_prompt, default_food_critic_prompt_no_sources, default_media_critic_prompt, default_media_critic_prompt_no_sources
|
4 |
+
from methods import load_config
|
5 |
+
from langchain_openai import ChatOpenAI
|
6 |
+
import os
|
7 |
+
|
8 |
+
class LineListOutputParser(BaseOutputParser[List[str]]):
|
9 |
+
"""Output parser that splits a LLM result into a list of queries."""
|
10 |
+
def parse(self, text: str) -> List[str]:
|
11 |
+
lines = text.strip().split('\n')
|
12 |
+
return list(filter(None, lines))
|
13 |
+
|
14 |
+
class TransparentGPTSettings:
|
15 |
+
def __init__(self):
|
16 |
+
self.model = "meta-llama/Llama-3.3-70B-Instruct"
|
17 |
+
self.temperature = 0.7
|
18 |
+
self.prompt = default_prompt_template
|
19 |
+
self.prompt_mappings = {"default": default_prompt_template, "default_no_sources": default_prompt_template_no_sources, "doctor": doctor_prompt_template, "doctor_no_sources": default_prompt_template_no_sources, "genz": default_quirky_genz_prompt, "genz_no_sources": default_quirky_genz_prompt_no_sources, "food_critic": default_food_critic_prompt, "food_critic_no_sources": default_food_critic_prompt_no_sources, "media_critic":default_media_critic_prompt, "media_critic_no_sources": default_media_critic_prompt_no_sources }
|
20 |
+
self.model_mappings = {"Meta Llama 3.1":"meta-llama/Meta-Llama-3.1-70B-Instruct", "Meta Llama 3.3":"meta-llama/Llama-3.3-70B-Instruct", "MistralAI":"mistralai/Mixtral-8x7B-Instruct-v0.1", "Dolphin Mixtral":"cognitivecomputations/dolphin-2.9.2-mixtral-8x22b", "Microsoft Mini":"microsoft/Phi-3-mini-4k-instruct"}
|
21 |
+
self.prompt_name = "default"
|
22 |
+
self.num_sources = load_config()["num_sources"]
|
23 |
+
self.llm = ChatOpenAI(
|
24 |
+
base_url="https://api.studio.nebius.com/v1/",
|
25 |
+
api_key=os.environ.get("NEBIUS_API_KEY"),
|
26 |
+
model = self.model,
|
27 |
+
temperature = self.temperature
|
28 |
+
).bind(logprobs=True)
|
29 |
+
self.display_sources = True
|
30 |
+
self.query_expansion_options = {
|
31 |
+
'No query expansion': 'No query expansion',
|
32 |
+
'Basic query expansion': 'Basic query expansion',
|
33 |
+
'Multiquery expansion': 'Multiquery expansion',
|
34 |
+
'Hypothetical answer expansion': 'Hypothetical answer'
|
35 |
+
}
|
36 |
+
self.query_expansion = 'No query expansion'
|
37 |
+
|
38 |
+
def update_settings(self, settings):
|
39 |
+
self.model = self.model_mappings[settings['Model']]
|
40 |
+
self.temperature = settings['Temperature']
|
41 |
+
self.prompt = self.prompt_mappings[settings['Prompt Template']]
|
42 |
+
self.num_sources=settings['Number of Sources']
|
43 |
+
self.llm = ChatOpenAI(
|
44 |
+
base_url="https://api.studio.nebius.com/v1/",
|
45 |
+
api_key=os.environ.get("NEBIUS_API_KEY"),
|
46 |
+
model = self.model,
|
47 |
+
temperature = self.temperature
|
48 |
+
).bind(logprobs=True)
|
49 |
+
self.display_sources = settings['Display Sources']
|
50 |
+
self.prompt_name = settings['Prompt Template']
|
51 |
+
self.query_expansion = settings['Query Expansion']
|
config.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"num_sources": 3
|
3 |
+
}
|
methods.py
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import chainlit as cl
|
3 |
+
from langchain.memory.buffer import ConversationBufferMemory
|
4 |
+
from langchain_openai import ChatOpenAI, OpenAI
|
5 |
+
from langchain.chains import LLMChain
|
6 |
+
from prompts import default_prompt_template, doctor_prompt_template, default_prompt_template_no_sources, doctor_prompt_template_no_sources
|
7 |
+
from dotenv import load_dotenv
|
8 |
+
from chainlit.input_widget import Select, Switch, Slider
|
9 |
+
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
|
10 |
+
from math import exp
|
11 |
+
import numpy as np
|
12 |
+
from typing import Any, Dict, List, Tuple
|
13 |
+
from langchain_core.output_parsers import BaseOutputParser
|
14 |
+
from difflib import SequenceMatcher
|
15 |
+
import requests
|
16 |
+
from bs4 import BeautifulSoup
|
17 |
+
import nltk
|
18 |
+
import re
|
19 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
20 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
21 |
+
import json
|
22 |
+
|
23 |
+
llm = ChatOpenAI(
|
24 |
+
base_url="https://api.studio.nebius.com/v1/",
|
25 |
+
api_key=os.environ.get("NEBIUS_API_KEY"),
|
26 |
+
model = "meta-llama/Llama-3.3-70B-Instruct",
|
27 |
+
temperature = 0.7
|
28 |
+
).bind(logprobs=True)
|
29 |
+
|
30 |
+
def get_wikipedia_page_content(page_title):
|
31 |
+
#scraping wikipedia pages with the Revisions API
|
32 |
+
page_title = re.sub(r"\s+", "", page_title).strip()
|
33 |
+
url = f"https://en.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&titles={page_title}&formatversion=2&rvprop=content&rvslots=*"
|
34 |
+
response = requests.get(url)
|
35 |
+
data = response.json()
|
36 |
+
return data["query"]["pages"][0]["revisions"][0]["slots"]["main"]["content"]
|
37 |
+
|
38 |
+
def test_scrape_sim(link, response):
|
39 |
+
tfidf_vectorizer = TfidfVectorizer()
|
40 |
+
try:
|
41 |
+
idx = link.rfind("/")
|
42 |
+
title = link[idx+1:]
|
43 |
+
tfidf_matrix = tfidf_vectorizer.fit_transform([get_wikipedia_page_content(title), response])
|
44 |
+
# tfidf_matrix = tfidf_vectorizer.fit_transform([scrape_web_text(link), response])
|
45 |
+
cosine_sim = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]
|
46 |
+
return cosine_sim*100
|
47 |
+
except:
|
48 |
+
return 0
|
49 |
+
|
50 |
+
config_file="config.json"
|
51 |
+
def get_config():
|
52 |
+
with open(config_file, "r") as file:
|
53 |
+
return json.load(file)
|
54 |
+
def update_config(new_value):
|
55 |
+
config = get_config()
|
56 |
+
config["num_sources"] = new_value
|
57 |
+
with open(config_file, "w") as file:
|
58 |
+
json.dump(config, file, indent=4)
|
59 |
+
|
60 |
+
def load_config():
|
61 |
+
with open("config.json","r") as file:
|
62 |
+
return json.load(file)
|
63 |
+
|
64 |
+
def generate_hypothetical_answer(question: str) -> str:
|
65 |
+
"""Have LLM generate a hypothetical answer to assist with bot response."""
|
66 |
+
prompt = PromptTemplate(
|
67 |
+
input_variables=['question'],
|
68 |
+
template="""
|
69 |
+
You are an AI assistant taked with generate a hypothetical answer to the following question. Your answer shoulld be detailed and comprehensive,
|
70 |
+
as if you had access to all relevant information. This hypothetical answer will be used to improve document retrieval, so include key terms and concepts
|
71 |
+
that might be relevant. Do not include phrases like "I think" or "It's possible that" - present the information as if it were factual.
|
72 |
+
Question:{question}
|
73 |
+
Hypothetical answer:
|
74 |
+
""",
|
75 |
+
)
|
76 |
+
return TransparentGPT_settings.llm.invoke(prompt.format(question=question))
|
77 |
+
|
78 |
+
def highest_log_prob(vals):
|
79 |
+
"""Calculates the perplexity score (confidence) of bot response."""
|
80 |
+
logprobs = []
|
81 |
+
for token in vals:
|
82 |
+
logprobs += [token['logprob']]
|
83 |
+
average_log_prob = sum(logprobs)/len(logprobs)
|
84 |
+
return np.round(np.exp(average_log_prob)*100,2)
|
prompts.py
ADDED
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain.prompts import PromptTemplate
|
2 |
+
|
3 |
+
default_conversational_template="""
|
4 |
+
You are a conversational assistant.
|
5 |
+
Use {num_sources} valid Wikipedia sources whose pages have content for your response.
|
6 |
+
Please include the links of the {num_sources} sources that you used as {num_sources} separate bullet-pointed
|
7 |
+
links after your response.
|
8 |
+
Question: {question}
|
9 |
+
Answer:"""
|
10 |
+
|
11 |
+
default_prompt_template = PromptTemplate(
|
12 |
+
input_variables = ["question"],
|
13 |
+
template = default_conversational_template
|
14 |
+
)
|
15 |
+
|
16 |
+
default_conversational_template_no_sources="""
|
17 |
+
You are a conversational assistant.
|
18 |
+
Question: {question}
|
19 |
+
Answer:"""
|
20 |
+
|
21 |
+
default_prompt_template_no_sources = PromptTemplate(
|
22 |
+
input_variables = ["question"],
|
23 |
+
template = default_conversational_template_no_sources
|
24 |
+
)
|
25 |
+
|
26 |
+
|
27 |
+
doctor_conversational_template="""
|
28 |
+
You are a doctor assisting the user with any health-related queries that they have. Please provide responses in a professional manner,
|
29 |
+
using as many scientifically relevant terms and concepts as possible. Please output your response in 3 concise bullet points with 1 bullet point being a conversational response,
|
30 |
+
1 bullet point providing potential causes of their query, and 1 bullet point suggesting next steps for evaluation.
|
31 |
+
Use {num_sources} valid Wikipedia sources whose pages have content for your response.
|
32 |
+
Please include the links of the {num_sources} sources that you used as {num_sources} separate bullet-pointed
|
33 |
+
links after your response.
|
34 |
+
Question: {question}
|
35 |
+
Answer:"""
|
36 |
+
|
37 |
+
doctor_prompt_template = PromptTemplate(
|
38 |
+
input_variables = ["question"],
|
39 |
+
template = doctor_conversational_template
|
40 |
+
)
|
41 |
+
|
42 |
+
doctor_conversational_template_no_sources="""
|
43 |
+
You are a doctor assisting the user with any health-related queries that they have. Please provide responses in a professional manner,
|
44 |
+
using as many scientifically relevant terms and concepts as possible. Please output your response in 3 concise bullet points with 1 bullet point being a conversational response,
|
45 |
+
1 bullet point providing potential causes of their query, and 1 bullet point suggesting next steps for evaluation.
|
46 |
+
Question: {question}
|
47 |
+
Answer:"""
|
48 |
+
|
49 |
+
doctor_prompt_template_no_sources = PromptTemplate(
|
50 |
+
input_variables = ["question"],
|
51 |
+
template = doctor_conversational_template_no_sources
|
52 |
+
)
|
53 |
+
|
54 |
+
|
55 |
+
default_quirky_genz_template="""
|
56 |
+
You are a quirky GenZ young person that is knowledgeable of current trends and slang.
|
57 |
+
Use {num_sources} valid Wikipedia sources whose pages have content for your response.
|
58 |
+
Please include the links of the {num_sources} sources that you used as {num_sources} separate bullet-pointed
|
59 |
+
links after your response.
|
60 |
+
Question: {question}
|
61 |
+
Answer:"""
|
62 |
+
|
63 |
+
default_quirky_genz_prompt = PromptTemplate(
|
64 |
+
input_variables = ["question"],
|
65 |
+
template = default_quirky_genz_template
|
66 |
+
)
|
67 |
+
|
68 |
+
default_quirky_genz_template_no_sources="""
|
69 |
+
You are a quirky GenZ young person that is knowledgeable of current trends and slang.
|
70 |
+
Question: {question}
|
71 |
+
Answer:"""
|
72 |
+
|
73 |
+
default_quirky_genz_prompt_no_sources = PromptTemplate(
|
74 |
+
input_variables = ["question"],
|
75 |
+
template = default_quirky_genz_template_no_sources
|
76 |
+
)
|
77 |
+
|
78 |
+
|
79 |
+
default_media_critic_template="""
|
80 |
+
You are a world renowned film director and novel writer discussing your expertise and knowledge.
|
81 |
+
Use {num_sources} valid Wikipedia sources whose pages have content for your response.
|
82 |
+
Please include the links of the {num_sources} sources that you used as {num_sources} separate bullet-pointed
|
83 |
+
links after your response.
|
84 |
+
Question: {question}
|
85 |
+
Answer:"""
|
86 |
+
|
87 |
+
default_media_critic_prompt = PromptTemplate(
|
88 |
+
input_variables = ["question"],
|
89 |
+
template = default_media_critic_template
|
90 |
+
)
|
91 |
+
|
92 |
+
default_media_critic_no_sources="""
|
93 |
+
You are a world renowned film director and novel writer discussing your expertise and knowledge.
|
94 |
+
Question: {question}
|
95 |
+
Answer:"""
|
96 |
+
|
97 |
+
default_media_critic_prompt_no_sources = PromptTemplate(
|
98 |
+
input_variables = ["question"],
|
99 |
+
template = default_media_critic_no_sources
|
100 |
+
)
|
101 |
+
|
102 |
+
|
103 |
+
default_food_critic_template="""
|
104 |
+
You are an experienced and cultured international food and wine aficionado.
|
105 |
+
Use {num_sources} valid Wikipedia sources whose pages have content for your response.
|
106 |
+
Please include the links of the {num_sources} sources that you used as {num_sources} separate bullet-pointed
|
107 |
+
links after your response.
|
108 |
+
Question: {question}
|
109 |
+
Answer:"""
|
110 |
+
|
111 |
+
default_food_critic_prompt = PromptTemplate(
|
112 |
+
input_variables = ["question"],
|
113 |
+
template = default_food_critic_template
|
114 |
+
)
|
115 |
+
|
116 |
+
default_food_critic_no_sources="""
|
117 |
+
You are an experienced and cultured international food and wine aficionado.
|
118 |
+
Question: {question}
|
119 |
+
Answer:"""
|
120 |
+
|
121 |
+
default_food_critic_prompt_no_sources = PromptTemplate(
|
122 |
+
input_variables = ["question"],
|
123 |
+
template = default_food_critic_no_sources
|
124 |
+
)
|