vtiyyal1 commited on
Commit
08f7e4c
·
verified ·
1 Parent(s): 99f9e29

Upload 2 files

Browse files

date and logging

Files changed (2) hide show
  1. app.py +33 -48
  2. feed_to_llm_v2.py +85 -121
app.py CHANGED
@@ -1,48 +1,33 @@
1
- import openai
2
- import gradio as gr
3
- from full_chain import get_response
4
- import os
5
-
6
- api_key = os.getenv("OPENAI_API_KEY")
7
- client = openai.OpenAI(api_key=api_key)
8
-
9
- def create_hyperlink(url, title, domain):
10
- """Create HTML hyperlink with domain information."""
11
- return f"<a href='{url}' target='_blank'>{title}</a> ({domain})"
12
-
13
- def predict(message, history):
14
- """Process user message and return response with hyperlinked sources."""
15
- # Get response and source information
16
- responder, links, titles, domains = get_response(message, rerank_type="crossencoder")
17
-
18
- # The responder already contains the formatted response with numbered citations
19
- # We just need to add the hyperlinked references at the bottom
20
- hyperlinks = []
21
- for i, (link, title, domain) in enumerate(zip(links, titles, domains), 1):
22
- hyperlink = f"[{i}] {create_hyperlink(link, title, domain)}"
23
- hyperlinks.append(hyperlink)
24
-
25
- # Split the responder to separate the response from its references
26
- response_parts = responder.split("References:")
27
- main_response = response_parts[0].strip()
28
-
29
- # Combine the response with hyperlinked references
30
- final_response = (
31
- f"{main_response}\n\n"
32
- f"References:\n"
33
- f"{chr(10).join(hyperlinks)}"
34
- )
35
-
36
- return final_response
37
-
38
- # Initialize and launch Gradio interface
39
- gr.ChatInterface(
40
- predict,
41
- examples=[
42
- "How many Americans Smoke?",
43
- "What are some measures taken by the Indian Government to reduce the smoking population?",
44
- "Does smoking negatively affect my health?"
45
- ],
46
- title="Tobacco Information Assistant",
47
- description="Ask questions about tobacco-related topics and get answers with reliable sources."
48
- ).launch()
 
1
+
2
+ import openai
3
+ import gradio as gr
4
+ from full_chain import get_response
5
+ import os
6
+
7
+ api_key = os.getenv("OPENAI_API_KEY")
8
+ client = openai.OpenAI(api_key=api_key)
9
+
10
+
11
+ def create_hyperlink(url, title, domain):
12
+ return f"<a href='{url}'>{title}</a>" + " (" + domain + ")"
13
+
14
+
15
+ def predict(message, history):
16
+ print("get_responses: ")
17
+ # print(get_response(message, rerank_type="crossencoder"))
18
+ responder, links, titles, domains = get_response(message, rerank_type="crossencoder")
19
+ for i in range(len(links)):
20
+ links[i] = create_hyperlink(links[i], titles[i], domains[i])
21
+
22
+ out = responder + "\n" + "\n".join(links)
23
+
24
+ return out
25
+
26
+
27
+ gr.ChatInterface(predict,
28
+ examples = [
29
+ "How many Americans Smoke?",
30
+ "What are some measures taken by the Indian Government to reduce the smoking population?",
31
+ "Does smoking negatively affect my health?"
32
+ ]
33
+ ).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
feed_to_llm_v2.py CHANGED
@@ -1,121 +1,85 @@
1
- from langchain_openai import ChatOpenAI
2
-
3
- from langchain.schema import (
4
- HumanMessage,
5
- SystemMessage
6
- )
7
- import tiktoken
8
- import re
9
-
10
- from get_articles import save_solr_articles_full
11
- from rerank import crossencoder_rerank_answer
12
-
13
-
14
- def num_tokens_from_string(string: str, encoder) -> int:
15
- num_tokens = len(encoder.encode(string))
16
- return num_tokens
17
-
18
-
19
- def feed_articles_to_gpt_with_links(information, question):
20
- prompt = """
21
- You are a Question Answering system specializing in tobacco-related topics. You have access to several curated articles, each numbered (e.g., Article 1, Article 2). These articles cover various aspects of tobacco use, health effects, legislation, and quitting resources.
22
-
23
- When formulating your response, adhere to the following guidelines:
24
-
25
- 1. Use information from the provided articles to directly answer the question. Explicitly reference the article(s) used in your response by stating the article number(s) (e.g., "According to Article 1, ..." or "Articles 2 and 3 mention that...").
26
- 2. If the answer is not covered by any of the articles, clearly state that the information is unavailable. Do not guess or fabricate information.
27
- 3. Avoid using ambiguous time references like 'recently' or 'last year.' Instead, use absolute terms based on the article's content (e.g., 'In 2021' or 'As per Article 2, published in 2020').
28
- 4. Keep responses concise, accurate, and helpful while maintaining a professional tone.
29
-
30
- Below is a list of articles you can reference. Each article is identified by its number and content:
31
- """
32
- end_prompt = "\n----------------\n"
33
- prompt += end_prompt
34
-
35
- content = ""
36
- separator = "<<<<>>>>"
37
- token_count = 0
38
-
39
- # Encoder setup for token count tracking
40
- encoder = tiktoken.encoding_for_model("gpt-3.5-turbo")
41
- token_count += num_tokens_from_string(prompt, encoder)
42
-
43
- # Add articles to the prompt
44
- articles = [contents for score, contents, uuids, titles, domains in information]
45
- uuids = [uuids for score, contents, uuids, titles, domains in information]
46
- titles_list = [titles for score, contents, uuids, titles, domains in information]
47
- domains_list = [domains for score, contents, uuids, titles, domains in information]
48
-
49
- for i in range(len(articles)):
50
- addition = f"Article {i + 1}: {articles[i]} {separator}"
51
- token_count += num_tokens_from_string(addition, encoder)
52
- if token_count > 3500:
53
- break
54
- content += addition
55
-
56
- prompt += content
57
- llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.0)
58
- message = [
59
- SystemMessage(content=prompt),
60
- HumanMessage(content=question)
61
- ]
62
-
63
- response = llm.invoke(message)
64
- response_content = response.content # Access the content of the AIMessage
65
- print("LLM Response Content:", response_content)
66
-
67
- # Extract sources from the response content
68
- inline_matches = re.findall(r'Article \d+', response_content)
69
- parenthetical_matches = re.findall(r'\(Article \d+\)', response_content)
70
-
71
- if not (inline_matches or parenthetical_matches):
72
- return response_content, [], [], []
73
-
74
- # Combine and get unique article numbers
75
- all_matches = inline_matches + [m.strip('()') for m in parenthetical_matches]
76
- unique_articles = list(set(all_matches))
77
- used_article_nums = [int(re.findall(r'\d+', match)[0]) - 1 for match in unique_articles]
78
-
79
- # Create citation mapping
80
- citation_map = {}
81
- citations = []
82
- for idx, article_num in enumerate(used_article_nums, start=1):
83
- original = f"Article {article_num + 1}"
84
- citation_map[original] = f"[{idx}]"
85
- citation = f"[{idx}] {titles_list[article_num]} ({domains_list[article_num]})"
86
- citations.append(citation)
87
-
88
- # Replace all article references with citation numbers
89
- modified_response = response_content
90
- for original, citation_num in citation_map.items():
91
- # Replace both inline and parenthetical references
92
- modified_response = modified_response.replace(f"({original})", citation_num)
93
- modified_response = modified_response.replace(original, citation_num)
94
-
95
- # Format final response with citations
96
- response_with_citations = (
97
- f"{modified_response}\n\n"
98
- f"References:\n"
99
- f"{chr(10).join(citations)}"
100
- )
101
-
102
- # Prepare links only for cited articles
103
- cited_links = []
104
- cited_titles = []
105
- cited_domains = []
106
- for article_num in used_article_nums:
107
- uuid = uuids[article_num]
108
- link = f"https://tobaccowatcher.globaltobaccocontrol.org/articles/{uuid}/"
109
- cited_links.append(link)
110
- cited_titles.append(titles_list[article_num])
111
- cited_domains.append(domains_list[article_num])
112
-
113
- return response_with_citations, cited_links, cited_titles, cited_domains
114
-
115
- if __name__ == "__main__":
116
- question = "How is United States fighting against tobacco addiction?"
117
- rerank_type = "crossencoder"
118
- llm_type = "chat"
119
- csv_path = save_solr_articles_full(question, keyword_type="rake")
120
- reranked_out = crossencoder_rerank_answer(csv_path, question)
121
- feed_articles_to_gpt_with_links(reranked_out, question)
 
1
+ from langchain_openai import OpenAI
2
+
3
+ from langchain.schema import (
4
+ HumanMessage,
5
+ SystemMessage
6
+ )
7
+ import tiktoken
8
+ import re
9
+
10
+ from get_articles import save_solr_articles_full
11
+ from rerank import crossencoder_rerank_answer
12
+
13
+
14
+ def num_tokens_from_string(string: str, encoder) -> int:
15
+ num_tokens = len(encoder.encode(string))
16
+ return num_tokens
17
+
18
+
19
+ def feed_articles_to_gpt_with_links(information, question):
20
+ prompt = """
21
+ You are a Question Answering machine specialized in providing information on tobacco-related queries. You have access to a curated list of articles that span various aspects of tobacco use, health effects, legislation, and quitting resources. When responding to questions, follow these guidelines:
22
+
23
+ 1. Use information from the articles to formulate your answers. Indicate the article number you're referencing at the end of your response.
24
+ 2. If the question's answer is not covered by your articles, clearly state that you do not know the answer. Do not attempt to infer or make up information.
25
+ 3. Avoid using time-relative terms like 'last year,' 'recently,' etc., as the articles' publication dates and the current date may not align. Instead, use absolute terms (e.g., 'In 2022,' 'As of the article's 2020 publication,').
26
+ 4. Aim for concise, informative responses that directly address the question asked.
27
+
28
+ Remember, your goal is to provide accurate, helpful information on tobacco-related topics, aiding in education and informed decision-making.
29
+ """
30
+ end_prompt = "\n----------------\n"
31
+ prompt += end_prompt
32
+ content = ""
33
+ seperator = "<<<<>>>>"
34
+
35
+ token_count = 0
36
+ encoder = tiktoken.encoding_for_model("gpt-3.5-turbo")
37
+ token_count += num_tokens_from_string(prompt, encoder)
38
+
39
+ articles = [contents for score, contents, uuids, titles, domains in information]
40
+ uuids = [uuids for score, contents, uuids, titles, domains in information]
41
+ domains = [domains for score, contents, uuids, titles, domains in information]
42
+
43
+ for i in range(len(articles)):
44
+ addition = "Article " + str(i + 1) + ": " + articles[i] + seperator
45
+ addition += articles[i] + seperator
46
+ token_count += num_tokens_from_string(addition, encoder)
47
+ if token_count > 3500:
48
+ print(i)
49
+ break
50
+
51
+ content += addition
52
+
53
+ prompt += content
54
+ llm = OpenAI(model_name="gpt-4o-mini", temperature=0.0)
55
+ message = [
56
+ SystemMessage(content=prompt),
57
+ HumanMessage(content=question)
58
+ ]
59
+
60
+ response = llm.invoke(message)
61
+ print(response)
62
+ print("response length:", len(response))
63
+ source = re.findall('\((.*?)\)', response)[-1]
64
+
65
+ # get integers from source
66
+ source = re.findall(r'\d+', source)
67
+ used_article_num = [int(i) - 1 for i in source]
68
+
69
+ links = [f"https://tobaccowatcher.globaltobaccocontrol.org/articles/{uuid}/" for uuid in uuids]
70
+ titles = [titles for score, contents, uuids, titles, domains in information]
71
+
72
+ links = [links[i] for i in used_article_num]
73
+ titles = [titles[i] for i in used_article_num]
74
+ domains = [domains[i] for i in used_article_num]
75
+
76
+ response_without_source = re.sub("""\(Article.*\)""", "", response)
77
+ return response_without_source, links, titles, domains
78
+
79
+ if __name__ == "__main__":
80
+ question = "How is United States fighting against tobacco addiction?"
81
+ rerank_type = "crossencoder"
82
+ llm_type = "chat"
83
+ csv_path = save_solr_articles_full(question, keyword_type="rake")
84
+ reranked_out = crossencoder_rerank_answer(csv_path, question)
85
+ feed_articles_to_gpt_with_links(reranked_out, question)