File size: 7,180 Bytes
7e99c90
 
 
5d38be9
7e99c90
 
 
 
 
5d38be9
7e99c90
c80a1a0
5d38be9
 
 
 
 
 
 
fc85e8f
 
5d38be9
c74009c
 
 
 
 
 
 
 
 
 
c80a1a0
dafe406
c80a1a0
c74009c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c80a1a0
 
 
 
 
 
 
 
 
 
c74009c
 
 
d565b10
c74009c
d565b10
c74009c
 
 
 
d565b10
c74009c
a3f2e55
c74009c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c80a1a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b05f901
 
 
 
 
 
 
 
 
c80a1a0
b05f901
 
 
c80a1a0
c74009c
 
 
 
 
b05f901
 
23b330d
b05f901
4e52914
fd9cd93
4e52914
b39160d
5c9e79d
b39160d
 
4e52914
fd9cd93
4c3483a
b05f901
c80a1a0
 
 
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
from langchain.prompts import PromptTemplate
from langchain_core.output_parsers import JsonOutputParser, StrOutputParser
from langchain_community.chat_models import ChatOllama
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
from langchain_core.tools import Tool
from langchain_google_community import GoogleSearchAPIWrapper
from firecrawl import FirecrawlApp

import gradio as gr
import os

# Initialize LLM and Tools

# local_llm = 'llama3.1'
# llama3 = ChatOllama(model=local_llm, temperature=1)
# llama3_json = ChatOllama(model=local_llm, format='json', temperature=0)

#
os.environ["HUGGINGFACEHUB_API_TOKEN"] = os.getenv('HF_KEY')
os.environ["GOOGLE_CSE_ID"] = os.getenv('GOOGLE_CSE_ID')
os.environ["GOOGLE_API_KEY"] = os.getenv('GOOGLE_API_KEY')

llm = HuggingFaceEndpoint(
    repo_id="meta-llama/Meta-Llama-3.1-8B-Instruct",
    task="text-generation",
    max_new_tokens=4000,
    do_sample=False,
    repetition_penalty=1.03,
    )
llama3 = ChatHuggingFace(llm=llm, temperature = 1)
llama3_json = ChatHuggingFace(llm=llm, format = 'json', temperature = 0)

google_search = GoogleSearchAPIWrapper()
firecrawl_app = FirecrawlApp(api_key=os.getenv('FIRECRAWL_KEY'))

# Query Transformation
query_prompt = PromptTemplate(
    template="""
    
    <|begin_of_text|>
    
    <|start_header_id|>system<|end_header_id|> 
    
    You are an expert at crafting web search queries for fact checking.
    More often than not, a user will provide an information that they wish to fact check, however it might not be in the best format. 
    Reword their query to be the most effective web search string possible.
    Return the JSON with a single key 'query' with no premable or explanation.
    
    Information to transform: {question} 
    
    <|eot_id|>
    
    <|start_header_id|>assistant<|end_header_id|>
    
    """,
    input_variables=["question"],
)

# Chain
query_chain = query_prompt | llama3_json | JsonOutputParser()

# Google Search and Firecrawl Setup
def search_and_scrape(keyword):
    search_results = google_search.results(keyword, 3)
    scraped_data = []
    for result in search_results:
        url = result['link']
        scrape_response = firecrawl_app.scrape_url(url=url, params={'formats': ['markdown']})
        scraped_data.append(scrape_response)
    return scraped_data

# Summarizer
summarize_prompt = PromptTemplate(
    template="""
    
    <|begin_of_text|>
    
    <|start_header_id|>system<|end_header_id|> 
    
    You are an expert at summarizing web crawling results. The user will give you multiple web search result with different topics. Your task is to summarize all the important information
    from the article in a readable paragraph. It is okay if one paragraph contains multiple topics.
    
    Information to transform: {question} 
    
    <|eot_id|>
    
    <|start_header_id|>assistant<|end_header_id|>
    
    """,
    input_variables=["question"],
)

# Chain
summarize_chain = summarize_prompt | llama3 | StrOutputParser()

# Generation prompt
generate_prompt = PromptTemplate(
    template="""
    
    <|begin_of_text|>
    
    <|start_header_id|>system<|end_header_id|> 
    
    You are a fact-checker AI assistant that receives an information from the user, synthesizes web search results for that information, and verify whether the user's information is a fact or possibly a hoax. 
    Strictly use the following pieces of web search context to answer the question. If you don't know the answer, just give "Possibly Hoax" verdict. Only make direct references to material if provided in the context.
    Return a JSON output with these keys, with no premable:
    1. user_information: the user's input
    2. system_verdict: is the user question above a fact? choose only between "Fact" or "Possibly Hoax"
    3. explanation: a short explanation on why the verdict was chosen
    If the context does not relate with the information provided by user, you can give "Possibly Hoax" result and tell the user that based on web search, it seems that the provided information is a false information.
    
    <|eot_id|>
    
    <|start_header_id|>user<|end_header_id|>
    
    User Information: {question} 
    Web Search Context: {context} 
    JSON Verdict and Explanation: 
    
    <|eot_id|>
    
    <|start_header_id|>assistant<|end_header_id|>
    """,
    input_variables=["question", "context"],
)

# Chain
generate_chain = generate_prompt | llama3_json | JsonOutputParser()

# Full Flow Function
def fact_check_flow(user_question):
    # Step 2: Transform question into search query keyword
    keyword = query_chain.invoke({"question": user_question})["query"]
    
    # Step 3 & 4: Google search and scrape results
    context_data = search_and_scrape(keyword)
    
    final_markdown = []
    for results in context_data:
        final_markdown.append(results['markdown'])

    final_markdown = ' '.join(final_markdown)

    context = summarize_chain.invoke({"question": final_markdown})

    # Step 5: Use scraped data as context and run generate chain

    final_response = generate_chain.invoke({"question": user_question, "context": context})

    # Process output
    verdict = final_response['system_verdict']
    explanation = final_response['explanation']
    
    if verdict == "Fact":
        verdict_html = f"<span style='color:green; font-size: 24px;'><strong>{verdict}</strong></span>"
    else:
        verdict_html = f"<span style='color:red; font-size: 24px;'><strong>{verdict}</strong></span>"
    
    explanation_html = f"<p style='font-size: 14px;'>{explanation}</p>"
    
    return verdict_html + explanation_html

# Example Use
# user_question = "biden is not joining election in 2024"
# result = fact_check_flow(user_question)
# print(result)

demo = gr.Interface(
    fn=fact_check_flow,
    inputs=gr.Textbox(label="Input any information you want to fact-check!"),
    outputs="html", 
    title="Aletheia: Llama-Powered Fact-Checker AI Agent 🤖",
    description="""
        *"Aletheia: Llama-Powered Fact-Checker AI Agent"* is an experimental fact-checking tool designed to help users verify the accuracy of information quickly and easily. This tool leverages the power of Large Language Models (LLM) combined with real-time web crawling to analyze the validity of user-provided information. This tool is a prototype, currently being used by the author as part of a submission for Meta's Llama Hackathon 2024, demonstrating the potential for Llama to assist in information verification.\
        <p align="center">
          <img src="https://huggingface.co/spaces/matthewfarant/fact-checker/resolve/main/Flowchart.png" />
        </p>
        <br>
        <p><strong>Important Note:</strong></p> Due to current resource constraints, you need to restart the space each time you use this app to ensure it functions correctly (Go to "Settings" > "Restart Space"). This is a known issue and will be improved in future iterations (source: <a href="https://huggingface.co/spaces/huggingchat/chat-ui/discussions/430">https://huggingface.co/spaces/huggingchat/chat-ui/discussions/430</a>)

        """
)

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