Document(id=7fe87ca8e57420adb9ed47866809d38424003dd43b4eefdf6b1a400eb3709677, content: ' Quarterly profits at US media giant TimeWarner jumped 76% to $1.13bn (£600m) for the three months t...', meta: {'title': 'Ad sales boost Time Warner profit', 'category': 'business', 'filename': '001.txt'})
เริ่มจากสร้าง function สำหรับเรียกใช้งาน pipeline เพื่อให้ง่ายต่อการเรียกใช้:
Python
# Create the function
defrun_query(query: str):
# Run the pipeline
result=querying_pipeline.run(
{
"question_embedder": {
"text": query
},
"prompt_builder": {
"question": query
}
}
)
# Return the result
returnresult["generator"]["replies"][0].text
จากนั้น เรียกใช้งานโดยถามเกี่ยวกับข่าวที่อยู่ใน BBC News Archive เช่น:
Python
# Set the question
my_question="What concerns did users raise about Google’s AutoLink feature?"
# Run the query
query_result=run_query(query=my_question)
# Display the result
print(query_result)
ผลลัพธ์:
Users raised several concerns about Google’s AutoLink feature:
* It directs people to pre-selected commercial websites [1].
* Google's dominant market position could give a competitive edge to firms like Amazon [1].
* It creates links based on webpage information without the publisher's permission [1].
* Online libraries and other websites might direct users to commercial sites like Amazon or rival services against their will or in conflict with their own advertising [4].
* Some users felt it would only be fair if websites had to opt-in or receive revenue for "click throughs" to commercial sites [2].
* Concerns were raised about user choice, transparency regarding Google's payments, and the ability to substitute preferred companies for those chosen by Google [3].
* There was an objection to users being forced or tricked into using the service [3].
* The feature was compared to Microsoft's Smart Tags, which was widely criticised [2].
Full-time employees receive health insurance after completing probation.
The company provides annual health checkups once per year.
Employees can claim up to 2,000 THB per month for wellness activities such as fitness memberships, yoga classes, or mental health support.
Employees are also eligible for learning support. The company reimburses up to 10,000 THB per year for approved online courses, books, or professional certificates.
Full-time employees receive health insurance after completing probation.
The company provides annual health checkups once per year.
Employees can claim up to 2,000 THB per month for wellness activities such as fitness memberships, yoga classes, or mental health support.
Employees are also eligible for learning support. The company reimburses up to 10,000 THB per year for approved online courses, books, or professional certificates.
[SystemMessage(content='You are an expert curator of mental models across science, philosophy, and applied reasoning.\\n\\nYour task is to explain mental models clearly and accurately using a fixed schema.\\n\\nIf the origin of a model is unclear or debated, state that explicitly.\\n\\nDo not invent historical sources. Be concise and concrete.', additional_kwargs={}, response_metadata={}),
HumanMessage(content='Explain the following mental model: Pareto Princinple', additional_kwargs={}, response_metadata={})]
"origin": "Finance, Mathematics; concept dates back to ancient times, formalized in the Renaissance.",
"description": "Compound interest is the interest on a loan or deposit calculated based on both the initial principal and the accumulated interest from previous periods. It is often called 'interest on interest' and leads to exponential growth over time, making it a powerful force in finance for both wealth creation and debt accumulation.",
"example": "If you invest $1,000 at an annual interest rate of 5% compounded annually, after the first year you'll have $1,050. In the second year, the 5% interest is calculated on $1,050, not just the original $1,000, leading to a balance of $1,102.50. This snowball effect accelerates over decades, significantly increasing the total return compared to simple interest.",
"origin": "Often attributed to Aristotle; popularized in modern business by Elon Musk.",
"description": "First Principles Thinking involves breaking down complex problems into their most basic, fundamental truths or 'first principles,' rather than reasoning by analogy or conventional wisdom. It matters because it allows for innovative solutions by challenging assumptions and building new knowledge from the ground up.",
"example": "Instead of accepting the high cost of batteries for electric cars, Elon Musk famously broke down a battery into its constituent raw materials (cobalt, nickel, lithium, etc.) to understand their actual cost, then sought ways to procure and assemble them more efficiently, leading to significant cost reductions and innovation.",
"tags": [
"Problem-solving",
"Innovation",
"Critical Thinking",
"Decision-making"
]
}
👉 Query 2:
{
"model_name": "Occam's Razor",
"origin": "William of Ockham (14th-century philosopher and theologian)",
"description": "Occam's Razor is a problem-solving principle stating that among competing hypotheses that explain an event or phenomenon equally well, the simplest solution is most likely the correct one. It advocates for parsimony, suggesting that one should not multiply entities beyond necessity, thereby favoring theories with fewer assumptions.",
"example": "If you hear hoofbeats outside, it is more likely to be horses than zebras, assuming you are in a location where horses are common and zebras are not. The 'horse' explanation is simpler and requires fewer extraordinary assumptions.",
"tags": [
"Philosophy",
"Decision-making",
"Problem-solving",
"Critical thinking",
"Science"
]
}
👉 Query 3:
{
"model_name": "Confirmation Bias",
"origin": "Psychology; early concepts traced to Francis Bacon's Novum Organum (1620)",
"description": "Confirmation bias is the tendency to search for, interpret, favor, and recall information in a way that confirms one's pre-existing beliefs or hypotheses. It matters because it can lead to flawed reasoning, poor decision-making, and resistance to new or contradictory evidence, hindering objective analysis.",
"example": "A person who believes a certain stock will perform well might selectively read news articles and analyst reports that support this positive outlook, while ignoring or downplaying any negative news or warnings about the company.",
# Set payment
payment = "one thousand"
# Code that may raise exception
try:
if float(payment) < 0:
print("Payment cannot be negative.")
# Print when exception occurs
except ValueError:
print("Payment must be a number.")
# Set payment
payment = 500
# Code that may raise exception
try:
if float(payment) < 0:
print("Payment cannot be negative.")
# Print when exception occurs
except ValueError as e:
print(f"Error: {e}")
# Print when exception does not occur
else:
print("Processing payment ...")
# Set payment
payment = 500
# Code that may raise exception
try:
if float(payment) < 0:
print("Payment cannot be negative.")
# Print when exception occurs
except ValueError as e:
print(f"Error: {e}")
# Print when exception does not occur
else:
print("Processing payment ...")
# Print no matter what
finally:
print("Thank you for your payment.")
ผลลัพธ์:
Processing payment ...
Thank you for your payment.
# Set payment
payment = -50
# Code that may raise exception
try:
if not isinstance(payment, (int, float)):
raise TypeError("Payment must be a number.")
if payment < 0:
raise ValueError("Payment cannot be negative.")
# Print when exception occurs
except (TypeError, ValueError) as e:
print(f"Error: {e}")
# Print when exception does not occur
else:
print("Processing payment ...")
# Print no matter what
finally:
print("Thank you for your payment.")
ผลลัพธ์:
Error: Payment cannot be negative.
Thank you for your payment.
# Set payments
payments = {
"Alex": "one thousand",
"Barbara": -50,
"Carter": 500
}
# Loop through payments
for name, payment in payments.items():
# Print name and payment
print(f"{name} paying {payment}.")
# Code that may raise exception
try:
if not isinstance(payment, (int, float)):
raise TypeError("Payment must be a number.")
if payment < 0:
raise ValueError("Payment cannot be negative.")
# Print when exception occurs
except (TypeError, ValueError) as e:
print(f"Error: {e}")
# Print when exception does not occur
else:
print("Processing payment ...")
# Print no matter what
finally:
print("Thank you for your payment.")
# Print divider
print("\\n -------------------------------------------------- \\n")
ผลลัพธ์:
Alex paying one thousand.
Error: Payment must be a number.
Thank you for your payment.
--------------------------------------------------
Barbara paying -50.
Error: Payment cannot be negative.
Thank you for your payment.
--------------------------------------------------
Carter paying 500.
Processing payment ...
Thank you for your payment.
--------------------------------------------------
# Set system prompt
system_prompt = """
You are a helpful, cheerful, and optimistic assistant.
Be concise, validate answers, and admit when you don’t know.
Make responses clear, easy to read, and sprinkle in playful emoji.
"""
# Instantiate chat history
chat_history = [
{
"role": "system",
"content": system_prompt
}
]
📨 Step 4. Create a Chat Function
ในขั้นที่ 4 เราจะสร้าง function ที่จะทำให้เราถาม-ตอบกับ chatbot แบบ real-time ได้:
# Create a function for chatbot
def chatbot(model="gemini-2.5-flash"):
# Set chat history as global variable
global chat_history
# Print chat header
display(Markdown("# 🟢 --- Chat Begins ---"))
# Print chat instruction
print("ℹ️ Type \\"end chat\\" to exit.")
# Loop through conversation
while True:
# Render user prompt display
display(Markdown("## 🧑💻 You:"))
# Get user input
user_prompt = input("")
# Check if user wants to exit chat
if user_prompt.lower() == "end chat":
# Print goodbye message
display(Markdown("## ✨ Assistant:\\n" + "👋 See you later!"))
# End chat
break
# Append user input to chat history
chat_history.append(
{
"role": "user",
"content": user_prompt
}
)
# Get response
response = client.chat.completions.create(
# Set prompt
messages=chat_history,
# Set model
model=model
)
# Append response to history
chat_history.append(
{
"role": "assistant",
"content": response.choices[0].message.content
}
)
# Render response
display(Markdown("## ✨ Assistant:\\n" + response.choices[0].message.content + "\\n"))
💬 Step 5. Chat
ในขั้นสุดท้าย เราจะเรียกใช้งาน chatbot() เพื่อเริ่มคุยกับ AI เลย: