Stay Ahead, Stay ONMINE

LLM + RAG: Creating an AI-Powered File Reader Assistant

Introduction AI is everywhere.  It is hard not to interact at least once a day with a Large Language Model (LLM). The chatbots are here to stay. They’re in your apps, they help you write better, they compose emails, they read emails…well, they do a lot. And I don’t think that that is bad. In fact, my opinion is the other way – at least so far. I defend and advocate for the use of AI in our daily lives because, let’s agree, it makes everything much easier. I don’t have to spend time double-reading a document to find punctuation problems or type. AI does that for me. I don’t waste time writing that follow-up email every single Monday. AI does that for me. I don’t need to read a huge and boring contract when I have an AI to summarize the main takeaways and action points to me! These are only some of AI’s great uses. If you’d like to know more use cases of LLMs to make our lives easier, I wrote a whole book about them. Now, thinking as a data scientist and looking at the technical side, not everything is that bright and shiny.  LLMs are great for several general use cases that apply to anyone or any company. For example, coding, summarizing, or answering questions about general content created until the training cutoff date. However, when it comes to specific business applications, for a single purpose, or something new that didn’t make the cutoff date, that is when the models won’t be that useful if used out-of-the-box – meaning, they will not know the answer. Thus, it will need adjustments. Training an LLM model can take months and millions of dollars. What is even worse is that if we don’t adjust and tune the model to our purpose, there will be unsatisfactory results or hallucinations (when the model’s response doesn’t make sense given our query). So what is the solution, then? Spending a lot of money retraining the model to include our data? Not really. That’s when the Retrieval-Augmented Generation (RAG) becomes useful. RAG is a framework that combines getting information from an external knowledge base with large language models (LLMs). It helps AI models produce more accurate and relevant responses. Let’s learn more about RAG next. What is RAG? Let me tell you a story to illustrate the concept. I love movies. For some time in the past, I knew which movies were competing for the best movie category at the Oscars or the best actors and actresses. And I would certainly know which ones got the statue for that year. But now I am all rusty on that subject. If you asked me who was competing, I would not know. And even if I tried to answer you, I would give you a weak response.  So, to provide you with a quality response, I will do what everybody else does: search for the information online, obtain it, and then give it to you. What I just did is the same idea as the RAG: I obtained data from an external database to give you an answer. When we enhance the LLM with a content store where it can go and retrieve data to augment (increase) its knowledge base, that is the RAG framework in action. RAG is like creating a content store where the model can enhance its knowledge and respond more accurately. User prompt about Content C. LLM retrieves external content to aggregate to the answer. Image by the author. Summarizing: Uses search algorithms to query external data sources, such as databases, knowledge bases, and web pages. Pre-processes the retrieved information. Incorporates the pre-processed information into the LLM. Why use RAG? Now that we know what the RAG framework is let’s understand why we should be using it. Here are some of the benefits: Enhances factual accuracy by referencing real data. RAG can help LLMs process and consolidate knowledge to create more relevant answers  RAG can help LLMs access additional knowledge bases, such as internal organizational data  RAG can help LLMs create more accurate domain-specific content  RAG can help reduce knowledge gaps and AI hallucination As previously explained, I like to say that with the RAG framework, we are giving an internal search engine for the content we want it to add to the knowledge base. Well. All of that is very interesting. But let’s see an application of RAG. We will learn how to create an AI-powered PDF Reader Assistant. Project This is an application that allows users to upload a PDF document and ask questions about its content using AI-powered natural language processing (NLP) tools.  The app uses Streamlit as the front end. Langchain, OpenAI’s GPT-4 model, and FAISS (Facebook AI Similarity Search) for document retrieval and question answering in the backend. Let’s break down the steps for better understanding: Loading a PDF file and splitting it into chunks of text. This makes the data optimized for retrieval Present the chunks to an embedding tool. Embeddings are numerical vector representations of data used to capture relationships, similarities, and meanings in a way that machines can understand. They are widely used in Natural Language Processing (NLP), recommender systems, and search engines. Next, we put those chunks of text and embeddings in the same DB for retrieval. Finally, we make it available to the LLM. Data preparation Preparing a content store for the LLM will take some steps, as we just saw. So, let’s start by creating a function that can load a file and split it into text chunks for efficient retrieval. # Imports from langchain_community.document_loaders import PyPDFLoader from langchain.text_splitter import RecursiveCharacterTextSplitter def load_document(pdf): # Load a PDF “”” Load a PDF and split it into chunks for efficient retrieval. :param pdf: PDF file to load :return: List of chunks of text “”” loader = PyPDFLoader(pdf) docs = loader.load() # Instantiate Text Splitter with Chunk Size of 500 words and Overlap of 100 words so that context is not lost text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100) # Split into chunks for efficient retrieval chunks = text_splitter.split_documents(docs) # Return return chunks Next, we will start building our Streamlit app, and we’ll use that function in the next script. Web application We will begin importing the necessary modules in Python. Most of those will come from the langchain packages. FAISS is used for document retrieval; OpenAIEmbeddings transforms the text chunks into numerical scores for better similarity calculation by the LLM; ChatOpenAI is what enables us to interact with the OpenAI API; create_retrieval_chain is what actually the RAG does, retrieving and augmenting the LLM with that data; create_stuff_documents_chain glues the model and the ChatPromptTemplate. Note: You will need to generate an OpenAI Key to be able to run this script. If it’s the first time you’re creating your account, you get some free credits. But if you have it for some time, it is possible that you will have to add 5 dollars in credits to be able to access OpenAI’s API. An option is using Hugging Face’s Embedding.  # Imports from langchain_community.vectorstores import FAISS from langchain_openai import OpenAIEmbeddings from langchain.chains import create_retrieval_chain from langchain_openai import ChatOpenAI from langchain.chains.combine_documents import create_stuff_documents_chain from langchain_core.prompts import ChatPromptTemplate from scripts.secret import OPENAI_KEY from scripts.document_loader import load_document import streamlit as st This first code snippet will create the App title, create a box for file upload, and prepare the file to be added to the load_document() function. # Create a Streamlit app st.title(“AI-Powered Document Q&A”) # Load document to streamlit uploaded_file = st.file_uploader(“Upload a PDF file”, type=”pdf”) # If a file is uploaded, create the TextSplitter and vector database if uploaded_file :     # Code to work around document loader from Streamlit and make it readable by langchain     temp_file = “./temp.pdf”     with open(temp_file, “wb”) as file:         file.write(uploaded_file.getvalue())         file_name = uploaded_file.name     # Load document and split it into chunks for efficient retrieval.     chunks = load_document(temp_file)     # Message user that document is being processed with time emoji     st.write(“Processing document… :watch:”) Machines understand numbers better than text, so in the end, we will have to provide the model with a database of numbers that it can compare and check for similarity when performing a query. That’s where the embeddings will be useful to create the vector_db, in this next piece of code. # Generate embeddings     # Embeddings are numerical vector representations of data, typically used to capture relationships, similarities,     # and meanings in a way that machines can understand. They are widely used in Natural Language Processing (NLP),     # recommender systems, and search engines.     embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_KEY,                                   model=”text-embedding-ada-002″)     # Can also use HuggingFaceEmbeddings     # from langchain_huggingface.embeddings import HuggingFaceEmbeddings     # embeddings = HuggingFaceEmbeddings(model_name=”sentence-transformers/all-MiniLM-L6-v2″)     # Create vector database containing chunks and embeddings     vector_db = FAISS.from_documents(chunks, embeddings) Next, we create a retriever object to navigate in the vector_db. # Create a document retriever     retriever = vector_db.as_retriever()     llm = ChatOpenAI(model_name=”gpt-4o-mini”, openai_api_key=OPENAI_KEY) Then, we will create the system_prompt, which is a set of instructions to the LLM on how to answer, and we will create a prompt template, preparing it to be added to the model once we get the input from the user. # Create a system prompt     # It sets the overall context for the model.     # It influences tone, style, and focus before user interaction starts.     # Unlike user inputs, a system prompt is not visible to the end user.     system_prompt = (         “You are a helpful assistant. Use the given context to answer the question.”         “If you don’t know the answer, say you don’t know. ”         “{context}”     )     # Create a prompt Template     prompt = ChatPromptTemplate.from_messages(         [             (“system”, system_prompt),             (“human”, “{input}”),         ]     )     # Create a chain     # It creates a StuffDocumentsChain, which takes multiple documents (text data) and “stuffs” them together before passing them to the LLM for processing.     question_answer_chain = create_stuff_documents_chain(llm, prompt) Moving on, we create the core of the RAG framework, pasting together the retriever object and the prompt. This object adds relevant documents from a data source (e.g., a vector database) and makes it ready to be processed using an LLM to generate a response. # Creates the RAG      chain = create_retrieval_chain(retriever, question_answer_chain) Finally, we create the variable question for the user input. If this question box is filled with a query, we pass it to the chain, which calls the LLM to process and return the response, which will be printed on the app’s screen. # Streamlit input for question     question = st.text_input(“Ask a question about the document:”)     if question:         # Answer         response = chain.invoke({“input”: question})[‘answer’]         st.write(response) Here is a screenshot of the result. Screenshot of the final app. Image by the author. And this is a GIF for you to see the File Reader Ai Assistant in action! File Reader AI Assistant in action. Image by the author. Before you go In this project, we learned what the RAG framework is and how it helps the Llm to perform better and also perform well with specific knowledge. AI can be powered with knowledge from an instruction manual, databases from a company, some finance files, or contracts, and then become fine-tuned to respond accurately to domain-specific content queries. The knowledge base is augmented with a content store. To recap, this is how the framework works: 1️⃣ User Query → Input text is received. 2️⃣ Retrieve Relevant Documents → Searches a knowledge base (e.g., a database, vector store). 3️⃣ Augment Context → Retrieved documents are added to the input. 4️⃣ Generate Response → An LLM processes the combined input and produces an answer. GitHub repository https://github.com/gurezende/Basic-Rag About me If you liked this content and want to learn more about my work, here is my website, where you can also find all my contacts. https://gustavorsantos.me References https://cloud.google.com/use-cases/retrieval-augmented-generation https://www.ibm.com/think/topics/retrieval-augmented-generation https://python.langchain.com/docs/introduction https://www.geeksforgeeks.org/how-to-get-your-own-openai-api-key

Introduction

AI is everywhere. 

It is hard not to interact at least once a day with a Large Language Model (LLM). The chatbots are here to stay. They’re in your apps, they help you write better, they compose emails, they read emails…well, they do a lot.

And I don’t think that that is bad. In fact, my opinion is the other way – at least so far. I defend and advocate for the use of AI in our daily lives because, let’s agree, it makes everything much easier.

I don’t have to spend time double-reading a document to find punctuation problems or type. AI does that for me. I don’t waste time writing that follow-up email every single Monday. AI does that for me. I don’t need to read a huge and boring contract when I have an AI to summarize the main takeaways and action points to me!

These are only some of AI’s great uses. If you’d like to know more use cases of LLMs to make our lives easier, I wrote a whole book about them.

Now, thinking as a data scientist and looking at the technical side, not everything is that bright and shiny. 

LLMs are great for several general use cases that apply to anyone or any company. For example, coding, summarizing, or answering questions about general content created until the training cutoff date. However, when it comes to specific business applications, for a single purpose, or something new that didn’t make the cutoff date, that is when the models won’t be that useful if used out-of-the-box – meaning, they will not know the answer. Thus, it will need adjustments.

Training an LLM model can take months and millions of dollars. What is even worse is that if we don’t adjust and tune the model to our purpose, there will be unsatisfactory results or hallucinations (when the model’s response doesn’t make sense given our query).

So what is the solution, then? Spending a lot of money retraining the model to include our data?

Not really. That’s when the Retrieval-Augmented Generation (RAG) becomes useful.

RAG is a framework that combines getting information from an external knowledge base with large language models (LLMs). It helps AI models produce more accurate and relevant responses.

Let’s learn more about RAG next.

What is RAG?

Let me tell you a story to illustrate the concept.

I love movies. For some time in the past, I knew which movies were competing for the best movie category at the Oscars or the best actors and actresses. And I would certainly know which ones got the statue for that year. But now I am all rusty on that subject. If you asked me who was competing, I would not know. And even if I tried to answer you, I would give you a weak response. 

So, to provide you with a quality response, I will do what everybody else does: search for the information online, obtain it, and then give it to you. What I just did is the same idea as the RAG: I obtained data from an external database to give you an answer.

When we enhance the LLM with a content store where it can go and retrieve data to augment (increase) its knowledge base, that is the RAG framework in action.

RAG is like creating a content store where the model can enhance its knowledge and respond more accurately.

Diagram: User prompts and content using LLM + RAG
User prompt about Content C. LLM retrieves external content to aggregate to the answer. Image by the author.

Summarizing:

  1. Uses search algorithms to query external data sources, such as databases, knowledge bases, and web pages.
  2. Pre-processes the retrieved information.
  3. Incorporates the pre-processed information into the LLM.

Why use RAG?

Now that we know what the RAG framework is let’s understand why we should be using it.

Here are some of the benefits:

  • Enhances factual accuracy by referencing real data.
  • RAG can help LLMs process and consolidate knowledge to create more relevant answers 
  • RAG can help LLMs access additional knowledge bases, such as internal organizational data 
  • RAG can help LLMs create more accurate domain-specific content 
  • RAG can help reduce knowledge gaps and AI hallucination

As previously explained, I like to say that with the RAG framework, we are giving an internal search engine for the content we want it to add to the knowledge base.

Well. All of that is very interesting. But let’s see an application of RAG. We will learn how to create an AI-powered PDF Reader Assistant.

Project

This is an application that allows users to upload a PDF document and ask questions about its content using AI-powered natural language processing (NLP) tools. 

  • The app uses Streamlit as the front end.
  • Langchain, OpenAI’s GPT-4 model, and FAISS (Facebook AI Similarity Search) for document retrieval and question answering in the backend.

Let’s break down the steps for better understanding:

  1. Loading a PDF file and splitting it into chunks of text.
    1. This makes the data optimized for retrieval
  2. Present the chunks to an embedding tool.
    1. Embeddings are numerical vector representations of data used to capture relationships, similarities, and meanings in a way that machines can understand. They are widely used in Natural Language Processing (NLP), recommender systems, and search engines.
  3. Next, we put those chunks of text and embeddings in the same DB for retrieval.
  4. Finally, we make it available to the LLM.

Data preparation

Preparing a content store for the LLM will take some steps, as we just saw. So, let’s start by creating a function that can load a file and split it into text chunks for efficient retrieval.

# Imports
from  langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter

def load_document(pdf):
    # Load a PDF
    """
    Load a PDF and split it into chunks for efficient retrieval.

    :param pdf: PDF file to load
    :return: List of chunks of text
    """

    loader = PyPDFLoader(pdf)
    docs = loader.load()

    # Instantiate Text Splitter with Chunk Size of 500 words and Overlap of 100 words so that context is not lost
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
    # Split into chunks for efficient retrieval
    chunks = text_splitter.split_documents(docs)

    # Return
    return chunks

Next, we will start building our Streamlit app, and we’ll use that function in the next script.

Web application

We will begin importing the necessary modules in Python. Most of those will come from the langchain packages.

FAISS is used for document retrieval; OpenAIEmbeddings transforms the text chunks into numerical scores for better similarity calculation by the LLM; ChatOpenAI is what enables us to interact with the OpenAI API; create_retrieval_chain is what actually the RAG does, retrieving and augmenting the LLM with that data; create_stuff_documents_chain glues the model and the ChatPromptTemplate.

Note: You will need to generate an OpenAI Key to be able to run this script. If it’s the first time you’re creating your account, you get some free credits. But if you have it for some time, it is possible that you will have to add 5 dollars in credits to be able to access OpenAI’s API. An option is using Hugging Face’s Embedding. 

# Imports
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain.chains import create_retrieval_chain
from langchain_openai import ChatOpenAI
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain_core.prompts import ChatPromptTemplate
from scripts.secret import OPENAI_KEY
from scripts.document_loader import load_document
import streamlit as st

This first code snippet will create the App title, create a box for file upload, and prepare the file to be added to the load_document() function.

# Create a Streamlit app
st.title("AI-Powered Document Q&A")

# Load document to streamlit
uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")

# If a file is uploaded, create the TextSplitter and vector database
if uploaded_file :

    # Code to work around document loader from Streamlit and make it readable by langchain
    temp_file = "./temp.pdf"
    with open(temp_file, "wb") as file:
        file.write(uploaded_file.getvalue())
        file_name = uploaded_file.name

    # Load document and split it into chunks for efficient retrieval.
    chunks = load_document(temp_file)

    # Message user that document is being processed with time emoji
    st.write("Processing document... :watch:")

Machines understand numbers better than text, so in the end, we will have to provide the model with a database of numbers that it can compare and check for similarity when performing a query. That’s where the embeddings will be useful to create the vector_db, in this next piece of code.

# Generate embeddings
    # Embeddings are numerical vector representations of data, typically used to capture relationships, similarities,
    # and meanings in a way that machines can understand. They are widely used in Natural Language Processing (NLP),
    # recommender systems, and search engines.
    embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_KEY,
                                  model="text-embedding-ada-002")

    # Can also use HuggingFaceEmbeddings
    # from langchain_huggingface.embeddings import HuggingFaceEmbeddings
    # embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

    # Create vector database containing chunks and embeddings
    vector_db = FAISS.from_documents(chunks, embeddings)

Next, we create a retriever object to navigate in the vector_db.

# Create a document retriever
    retriever = vector_db.as_retriever()
    llm = ChatOpenAI(model_name="gpt-4o-mini", openai_api_key=OPENAI_KEY)

Then, we will create the system_prompt, which is a set of instructions to the LLM on how to answer, and we will create a prompt template, preparing it to be added to the model once we get the input from the user.

# Create a system prompt
    # It sets the overall context for the model.
    # It influences tone, style, and focus before user interaction starts.
    # Unlike user inputs, a system prompt is not visible to the end user.

    system_prompt = (
        "You are a helpful assistant. Use the given context to answer the question."
        "If you don't know the answer, say you don't know. "
        "{context}"
    )

    # Create a prompt Template
    prompt = ChatPromptTemplate.from_messages(
        [
            ("system", system_prompt),
            ("human", "{input}"),
        ]
    )

    # Create a chain
    # It creates a StuffDocumentsChain, which takes multiple documents (text data) and "stuffs" them together before passing them to the LLM for processing.

    question_answer_chain = create_stuff_documents_chain(llm, prompt)

Moving on, we create the core of the RAG framework, pasting together the retriever object and the prompt. This object adds relevant documents from a data source (e.g., a vector database) and makes it ready to be processed using an LLM to generate a response.

# Creates the RAG
     chain = create_retrieval_chain(retriever, question_answer_chain)

Finally, we create the variable question for the user input. If this question box is filled with a query, we pass it to the chain, which calls the LLM to process and return the response, which will be printed on the app’s screen.

# Streamlit input for question
    question = st.text_input("Ask a question about the document:")
    if question:
        # Answer
        response = chain.invoke({"input": question})['answer']
        st.write(response)

Here is a screenshot of the result.

Screenshot of the AI-Powered Document Q&A
Screenshot of the final app. Image by the author.

And this is a GIF for you to see the File Reader Ai Assistant in action!

GIF of the File Reader AI Assistant in action
File Reader AI Assistant in action. Image by the author.

Before you go

In this project, we learned what the RAG framework is and how it helps the Llm to perform better and also perform well with specific knowledge.

AI can be powered with knowledge from an instruction manual, databases from a company, some finance files, or contracts, and then become fine-tuned to respond accurately to domain-specific content queries. The knowledge base is augmented with a content store.

To recap, this is how the framework works:

1️⃣ User Query → Input text is received.

2️⃣ Retrieve Relevant Documents → Searches a knowledge base (e.g., a database, vector store).

3️⃣ Augment Context → Retrieved documents are added to the input.

4️⃣ Generate Response → An LLM processes the combined input and produces an answer.

GitHub repository

https://github.com/gurezende/Basic-Rag

About me

If you liked this content and want to learn more about my work, here is my website, where you can also find all my contacts.

https://gustavorsantos.me

References

https://cloud.google.com/use-cases/retrieval-augmented-generation

https://www.ibm.com/think/topics/retrieval-augmented-generation

https://youtu.be/T-D1OfcDW1M?si=G0UWfH5-wZnMu0nw

https://python.langchain.com/docs/introduction

https://www.geeksforgeeks.org/how-to-get-your-own-openai-api-key

Shape
Shape
Stay Ahead

Explore More Insights

Stay ahead with more perspectives on cutting-edge power, infrastructure, energy,  bitcoin and AI solutions. Explore these articles to uncover strategies and insights shaping the future of industries.

Shape

Cisco exec testifies at US Senate panel on AI’s network impact

“We will explore how widespread AI use has forced networks to evolve, requiring more capacity and more complex designs so that AI can run efficiently on those networks,” said U.S. Senator Deb Fischer (R-Neb), Chairman of the Senate Commerce Subcommittee on Telecommunications and Media, in her opening statement. “We will consider

Read More »

Vista seeks RIGI approval for $5.8 billion Bandurria Norte development

Vista Energy SAB de CV has applied to include its Bandurria Norte shale oil development in Argentina’s Large Investment Incentive Regime (RIGI). The $5.8-billion project targets peak production of 50,000 boe/d. Bandurria Norte is the largest oil project submitted under RIGI, which provides tax, customs, and foreign-exchange incentives for qualifying investments, and follows approval of Pampa Energía SA’s $4.521 billion Rincón de Aranda development, which established the first framework for qualifying incremental shale oil production under the regime. Together, the projects represent more than $10.3 billion in planned investment and would extend RIGI-backed development into undeveloped Vaca Muerta oil acreage. Bandurria Norte spans 26,500 acres in Vaca Muerta’s oil window and currently has no producing wells. Vista plans to drill and complete 332 horizontal wells and build dedicated infrastructure, including a 40,000-b/d oil treatment plant, a gas compression plant, gathering systems, pipelines, and associated infrastructure. The project would be Vista’s first large-scale development outside its core Bajada del Palo hub, where existing roads, processing capacity, and gathering networks support lower-cost drilling. Bandurria Norte requires full greenfield development, increasing upfront capital requirements, and execution risk. Vista said RIGI incentives are material to developing its undeveloped acreage because incremental production from new areas can qualify separately from existing output if volumes remain physically and operationally traceable. Export capacity remains critical Bandurria Norte forms part of Vista’s plan to increase production to 208,000 boe/d in 2028 and 250,000 boe/d in 2030. Development depends on additional crude transportation capacity from the Neuquén basin, particularly the Vaca Muerta Oil Sur (VMOS) pipeline under construction between Allen and Punta Colorada in Río Negro province. Designed for an initial capacity of 550,000 b/d and expandable to 700,000 b/d, VMOS is scheduled for start-up in first-half 2027. Vista averaged 156,000 boe/d of production in second-quarter 2026, up 16%

Read More »

Oil prices surge on renewed Middle East tensions

@import url(‘https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap’); .ebm-page__main h1, .ebm-page__main h2, .ebm-page__main h3, .ebm-page__main h4, .ebm-page__main h5, .ebm-page__main h6 { font-family: Inter; } body { line-height: 150%; letter-spacing: 0.025em; } button, .ebm-button-wrapper { font-family: Inter; } .label-style { text-transform: uppercase; color: var(–color-grey); font-weight: 600; font-size: 0.75rem; } .caption-style { font-size: 0.75rem; opacity: .6; } #onetrust-pc-sdk [id*=btn-handler], #onetrust-pc-sdk [class*=btn-handler] { background-color: #c19a06 !important; border-color: #c19a06 !important; } #onetrust-policy a, #onetrust-pc-sdk a, #ot-pc-content a { color: #c19a06 !important; } #onetrust-consent-sdk #onetrust-pc-sdk .ot-active-menu { border-color: #c19a06 !important; } #onetrust-consent-sdk #onetrust-accept-btn-handler, #onetrust-banner-sdk #onetrust-reject-all-handler, #onetrust-consent-sdk #onetrust-pc-btn-handler.cookie-setting-link { background-color: #c19a06 !important; border-color: #c19a06 !important; } #onetrust-consent-sdk .onetrust-pc-btn-handler { color: #c19a06 !important; border-color: #c19a06 !important; } Global oil prices rallied sharply July 29 as renewed military escalation in the Middle East ended several days of relative calm and revived concerns over crude flows from the region. Brent crude surged 7% to above $90/bbl, while US WTI climbed above $84/bbl. The rally followed joint US-Saudi airstrikes on Iran-backed militias in Iraq—which killed at least 20 fighters, according to Iraq’s Popular Mobilization Forces—and a retaliatory Iranian missile barrage targeting US forces in the region. Stay updated on oil price volatility, shipping disruptions, LNG market analysis, and production output through OGJ’s Iran war content hub. This operation marks the first time Saudi Arabia has publicly acknowledged a combat role in the conflict. Washington and Riyadh stated that the strikes were launched in response to drone attacks on oil facilities in Saudi Arabia’s Eastern Province—attacks that originated from within Iraq. The sudden escalation across multiple fronts has raised concerns that the 5-month-old conflict could expand further, threatening critical shipping lanes—the Strait of Hormuz and, following the Houthis’ declared blockade of Saudi shipping, the Bab el-Mandeb strait. Adding support to prices, US commercial crude inventories fell by 7.2 million bbl in the week ended July 24, according

Read More »

Türkiye signs partnership deal with bp for Kirkuk oil field redevelopment

bp plc has farmed out a 15% interest in BP Energy Co. of Kirkuk Ltd. (BP ECKL) to state-owned Turkish Petroleum Corp. (TPAO), expanding on a partnership to support the redevelopment of major oil and gas fields in the Kirkuk region of northern Iraq. The move comes as Iraq aims to increase oil and gas production through various international partnerships. Signed during the official visit of Iraqi Prime Minister Ali Al-Zaidi to Türkiye, the agreement builds on a strategic cooperation memorandum of understanding (MoU) signed by the companies in February 2026.  The development and production contract covers an initial phase of oil and gas production of more than 3 billion boe from the Baba and Avanah domes of Kirkuk oil field and the adjacent Bai Hassan, Jambur, and Khabbaz fields in Federal Iraq, all currently operated by the North Oil Co. (NOC) and North Gas Co. (NGC), bp said in a release July 28. The contract area holds potential for additional exploration, the companies said. The deal follows one that saw ConocoPhillips acquire a 42% interest in BP ECKL. Together, bp said, the transactions support the next phase of redevelopment in Kirkuk. Türkiye Energy and Natural Resources Minister Bayraktar said the agreement is a step “towards making Turkish Petroleum a company that produces 1 million barrels of oil and natural gas per day.” Following completion of the transaction, which is subject to regulatory approvals, bp will remain the majority shareholder and a key participant in BP ECKL (bp 43%, ConocoPhillips 42%, TPAO 15%).

Read More »

EIA: US crude oil inventories down 7.2 million bbl

US crude oil inventories for the week ended July 24, excluding the Strategic Petroleum Reserve, decreased by 7.2 million bbl from the previous week, according to data from the US Energy Information Administration (EIA). At 404.5 million bbl, US crude oil inventories are about 7% below the 5-year average for this time of year, the EIA report indicated. EIA said total motor gasoline inventories increased slightly from last week and are 6% below the 5-year average for this time of year. Finished gasoline inventories increased while blending components inventories decreased last week. Distillate fuel inventories increased by 1.1 million bbl last week and are about 9% below the 5-year average for this time of year. Propane-propylene inventories increased by 2.5 million bbl from last week and are 34% above the 5-year average for this time of year, EIA said. US crude oil refinery inputs averaged 17.3 million b/d for the week ended July 24, which was 271,000 b/d more than the previous week’s average. Refineries operated at 97.2% of capacity. Gasoline production increased, averaging 9.9 million b/d. Distillate fuel production increased, averaging 5.4 million b/d. US crude oil imports averaged 5.7 million b/d, down 124,000 b/d from the previous week. Over the last 4 weeks, crude oil imports averaged about 5.7 million b/d, 6.9% less than the same 4-week period last year. Total motor gasoline imports averaged 659,000 b/d. Distillate fuel imports averaged 98,000 b/d.

Read More »

Cosmo lets well engineering contract for Block 4 offshore Abu Dhabi

@import url(‘https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap’); .ebm-page__main h1, .ebm-page__main h2, .ebm-page__main h3, .ebm-page__main h4, .ebm-page__main h5, .ebm-page__main h6 { font-family: Inter; } body { line-height: 150%; letter-spacing: 0.025em; } button, .ebm-button-wrapper { font-family: Inter; } .label-style { text-transform: uppercase; color: var(–color-grey); font-weight: 600; font-size: 0.75rem; } .caption-style { font-size: 0.75rem; opacity: .6; } #onetrust-pc-sdk [id*=btn-handler], #onetrust-pc-sdk [class*=btn-handler] { background-color: #c19a06 !important; border-color: #c19a06 !important; } #onetrust-policy a, #onetrust-pc-sdk a, #ot-pc-content a { color: #c19a06 !important; } #onetrust-consent-sdk #onetrust-pc-sdk .ot-active-menu { border-color: #c19a06 !important; } #onetrust-consent-sdk #onetrust-accept-btn-handler, #onetrust-banner-sdk #onetrust-reject-all-handler, #onetrust-consent-sdk #onetrust-pc-btn-handler.cookie-setting-link { background-color: #c19a06 !important; border-color: #c19a06 !important; } #onetrust-consent-sdk .onetrust-pc-btn-handler { color: #c19a06 !important; border-color: #c19a06 !important; } Cosmo E&P Albahriya Ltd. has let a well engineering services contract to CB&I’s Asset Solutions (formerly part of Petrofac) for Block 4 offshore north of Abu Dhabi, UAE. Offshore Block 4 covers an area of 4,865 sq km in the shallow waters of the Arabian Gulf. Cosmo was awarded the block in Abu Dhabi’s second Block Bid Round in 2021 and is operator of the block (100%). Since then, operations in the area have focused on oil exploration.

Read More »

Repsol farms out 50% stake in deepwater Gulf of Mexico block to Talos Energy

@import url(‘https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap’); .ebm-page__main h1, .ebm-page__main h2, .ebm-page__main h3, .ebm-page__main h4, .ebm-page__main h5, .ebm-page__main h6 { font-family: Inter; } body { line-height: 150%; letter-spacing: 0.025em; } button, .ebm-button-wrapper { font-family: Inter; } .label-style { text-transform: uppercase; color: var(–color-grey); font-weight: 600; font-size: 0.75rem; } .caption-style { font-size: 0.75rem; opacity: .6; } #onetrust-pc-sdk [id*=btn-handler], #onetrust-pc-sdk [class*=btn-handler] { background-color: #c19a06 !important; border-color: #c19a06 !important; } #onetrust-policy a, #onetrust-pc-sdk a, #ot-pc-content a { color: #c19a06 !important; } #onetrust-consent-sdk #onetrust-pc-sdk .ot-active-menu { border-color: #c19a06 !important; } #onetrust-consent-sdk #onetrust-accept-btn-handler, #onetrust-banner-sdk #onetrust-reject-all-handler, #onetrust-consent-sdk #onetrust-pc-btn-handler.cookie-setting-link { background-color: #c19a06 !important; border-color: #c19a06 !important; } #onetrust-consent-sdk .onetrust-pc-btn-handler { color: #c19a06 !important; border-color: #c19a06 !important; } Repsol SA will farm out a 50% working interest to Talos Energy Inc. in Block 29 in the Salinas-Sureste basin, offshore Mexico. Under the agreement, Talos Energy will make a contingent $30-million payment at final investment decision (FID), Talos said in a July 27 release. Terms also include a cash-carry of up to $20 million on the next exploration well and reimbursement of certain pre-closing costs, subject to customary terms and conditions, including Mexico’s regulatory approvals. Upon closing, Repsol will remain operator and retain a 50% interest alongside Talos’ 50% working interest.  The companies anticipate advancing the project toward FID in 2027. Block 29 development Block 29 contains the Polok and Chinwol oil discoveries, estimated to hold more than 200 MMboe of gross recoverable resources. Oil was discovered by the Polok-1 and Chinwol-1 wells, which encountered net oil columns of more than 200 m and 150 m, respectively. <!–> –><!–> –> May 5, 2020 <!–> –><!–> –> Feb. 8, 2023 <!–> –><!–> –> Dec. 3, 2024 The 3,254-sq-km block lies about 88 km offshore Tabasco. Polok and Chinwol fields are about 16 km apart in water depths of 460-600 m. The potential development concept centers on

Read More »

Data center energy constraints and moratoriums are mounting. Expect to see stalled AI projects

Fuel cells are more efficient, he says, and don’t emit particulates, but they’re more expensive and less reliable than generators and have other operational issues. One company that recently decided to go with fuel cells is Oracle, which will use 2.45 gigawatts worth of fuel cells to power its Project Jupiter data center in New Mexico, replacing the previous plan to use gas turbines and diesel generators. According to Oracle, the fuel cells will significantly reduce emissions, use only a “negligible” amount of water, and be quieter than turbines and generators. Plus, the on-site power generation will help protect energy rates of area residents. “If you want to build a data center, there’s a better way to build it,” says Natalie Sunderland, chief marketing and communications officer at Bloom Energy, which makes the fuel cells that Oracle plans to deploy. And companies aren’t about to scale back on their AI ambitions or reduce their demands for data centers, she says.

Read More »

Nvidia’s Next Move? Financing AI

The report argues that AI infrastructure spending is on track to exceed $2 trillion annually by 2028, with cumulative investment reaching roughly $11.1 trillion between 2024 and 2029. Financing those projects will require a massive expansion of credit markets, which could result in a cumulative collective AI-related debt of $7 trillion by the end of the decade. With deals reaching into the multibillion-dollar range, banks and venture funds simply don’t have that kind of money. Enter Nvidia. As of the first fiscal quarter of 2027 ended April 26, 2026, Nvidia was sitting on roughly $80.5 billion in cash, cash equivalents, and short-term investments. After data center capacity constrained AI expansion in 2025 and chip supply became the limiting factor in early 2026, financing has emerged as the next major obstacle to scaling AI infrastructure. “It is clear that financing will now be one of the most significant obstacles to ramping large-scale compute broadly available to everyone,” the authors wrote.

Read More »

The Gigawatt Buildout Faces the Execution Test

Demand remains abundant across the data center and AI infrastructure market. Alphabet has raised its capital spending forecast again. OpenAI has unveiled a 3.2-gigawatt project in Georgia. Hut 8 has signed another multibillion-dollar lease in Texas, while BlackRock and its partners have acquired Aligned Data Centers for approximately $40 billion. Oracle, meanwhile, could face a $7 billion collateral requirement in Wisconsin, Meta is paying more to finance a $12 billion Texas project, and proposed developments are drawing resistance across North America and beyond. Together, these developments describe a market moving into a more demanding phase. Land, power and capital remain available, but not on the same terms everywhere. The projects most likely to move are those that combine a credible customer, a durable power path, institutional financing and a development strategy capable of surviving public scrutiny. Hyperscaler Spending Keeps Rising After Google Cloud revenue grew 82% year over year to $24.8 billion in the second quarter, Alphabet increased its expected 2026 capital expenditures to between $195 billion and $205 billion. That was $15 billion above its previous forecast and more than twice the $91.5 billion the company spent in 2025. The cloud growth explains the spending without removing its financial pressure. The largest platforms are committing unprecedented cash to facilities, chips, networks and power systems whose economics will be measured over many years. OpenAI’s Project Camellia in Effingham County, Georgia, extends the scale further. OpenAI says it is designing and developing the campus itself and has contracted with Georgia Power for 3.2 GW to be delivered in phases from 2028 through 2032. Local reporting places the initial investment at at least $20 billion across roughly 1,400 acres. The 25-year power supply agreement may be as important as the campus size. OpenAI says it will cover the infrastructure costs, protect residential

Read More »

AI Clusters and the New Economics of Data Center Optics: A Conversation with Cisco’s Bill Gartner

Three Networks Inside the AI Factory Understanding the optical challenge begins with recognizing that an AI cluster contains several distinct networking environments. Gartner divided AI infrastructure into three broad tiers: scale-up, scale-out and scale-across. Each operates over a different distance, carries a different level of traffic and creates a different set of requirements for the interconnect. Scale-up describes the connections within a rack, where operators place as many GPUs as possible inside servers and then pack those servers into the available rack footprint. Gartner estimated that the bandwidth within this environment can be approximately 500 times that of a traditional wide-area network application. Scale-up connections still rely heavily on electrical interfaces because electrical interconnects remain relatively inexpensive and power efficient over short distances. Once the compute capacity of a rack has been exhausted, the cluster must expand into additional racks. This is the scale-out network, where 400G and 800G pluggable optics connect large numbers of GPU systems operating in parallel. Gartner characterized scale-out bandwidth as roughly 50 times the capacity associated with a conventional WAN environment. The third tier, scale-across, emerges when a data center reaches its practical power limit and the AI infrastructure must extend into another facility. Those data centers may be separated by tens or hundreds of kilometers, requiring coherent optical technology capable of carrying extremely high-capacity signals over longer distances. Scale-across networks can represent approximately 14 times traditional WAN bandwidth, according to Gartner. Taken together, the three tiers illustrate why optics has become inseparable from the AI infrastructure discussion. Network capacity must expand inside the rack, across rows of racks and increasingly between separate data centers—all without consuming an untenable share of the power budget or introducing failures that leave GPUs idle. When One Link Slows the Whole Cluster The reliability requirement for AI networks differs

Read More »

Meta’s Canadian AI Data Center: A New Model for Infrastructure and Energy Integration

Canada’s expansion as an artificial intelligence infrastructure market received its strongest endorsement yet on July 8, when Meta broke ground on a data center campus representing an investment of more than C$13 billion. The project, located in Sturgeon County north of Edmonton, will be Meta’s first data center in Canada and the 33rd facility in its global portfolio. Planned initially at 1 GW of power capacity, the AI-optimized campus could eventually scale to 1.8 GW, placing it among the largest data center developments under construction anywhere outside the United States. The announcement follows the Canadian federal government’s May launch of consultations on a forthcoming National Electricity Strategy, which identifies AI data centers as a major source of future electricity demand.  Approximately 3,000 construction workers are expected to be on the site at peak activity, while more than 300 permanent employees will operate the campus after completion. Meta is also committing approximately C$60 million to improvements involving local roads, water systems and other community infrastructure. The Meta announcement illustrates a fundamental change in Canadian data center construction. Rather than selecting a building site and applying for an ordinary utility connection, Meta and its partners have spent years coordinating the data center with a purpose-built 932 MW generating station, grid upgrades and long-term natural-gas transportation agreements. The project effectively combines a data center, a power plant and an infrastructure development program into a single construction ecosystem. Construction Has Begun on the Canadian Campus Meta describes the Sturgeon County project as an AI-optimized facility intended to support the computing demands of its core platforms, AI services and connected devices. The company said the buildout will occur in phases rather than delivering the entire gigawatt at once. Alberta’s major-project registry estimates a roughly three-year construction period. That timeline will require a sustained deployment of

Read More »

Nuclear Momentum Meets the Megawatt Test

Valar then supplied the most visible connection between the criticality program and data center technology. After reaching criticality, Valar advanced Ward 250 to approximately 10 kilowatts of thermal output and conducted a separate demonstration in which power from the reactor was used to run Nvidia Blackwell-based computing hardware. On July 1, Valar and Nvidia also announced that they were exploring a small Utah data center using closed-loop cooling and behind-the-meter advanced nuclear generation. The demonstration load was microscopic beside a hyperscale campus that may require hundreds of megawatts. Nvidia described the work as an exploration of how behind-the-meter advanced nuclear systems could support future AI factories, not as an agreement to purchase a specified quantity of electricity. Deployable Energy became the third developer to achieve zero-power criticality when its Unity reactor completed its experiment at Idaho National Laboratory on June 30. DOE announced the result July 1, noting that the three companies had satisfied the administration’s objective of achieving three advanced reactor criticality milestones by July 4. The commercial follow-up came quickly. On July 7, Deployable Energy and energy-infrastructure facilitator GridMarket announced a partnership aimed at data centers, hyperscalers and industrial customers. The agreement includes a committed pilot project and priority access to future Unity capacity. The companies said they were targeting 500 megawatts of annual deployments from 2030 through 2035 and more than 3 gigawatts cumulatively. The companies have not publicly named the pilot host or end customers. Even so, the committed pilot and access provisions put the arrangement ahead of a conventional memorandum of understanding. GridMarket is attempting to assemble sites, customers, technology and capital before commercial Unity units become available. Aalo Atomics completed the fourth criticality experiment on July 4, with DOE announcing the achievement July 6. Aalo-X went from groundbreaking to a sustained chain reaction in

Read More »

Microsoft will invest $80B in AI data centers in fiscal 2025

And Microsoft isn’t the only one that is ramping up its investments into AI-enabled data centers. Rival cloud service providers are all investing in either upgrading or opening new data centers to capture a larger chunk of business from developers and users of large language models (LLMs).  In a report published in October 2024, Bloomberg Intelligence estimated that demand for generative AI would push Microsoft, AWS, Google, Oracle, Meta, and Apple would between them devote $200 billion to capex in 2025, up from $110 billion in 2023. Microsoft is one of the biggest spenders, followed closely by Google and AWS, Bloomberg Intelligence said. Its estimate of Microsoft’s capital spending on AI, at $62.4 billion for calendar 2025, is lower than Smith’s claim that the company will invest $80 billion in the fiscal year to June 30, 2025. Both figures, though, are way higher than Microsoft’s 2020 capital expenditure of “just” $17.6 billion. The majority of the increased spending is tied to cloud services and the expansion of AI infrastructure needed to provide compute capacity for OpenAI workloads. Separately, last October Amazon CEO Andy Jassy said his company planned total capex spend of $75 billion in 2024 and even more in 2025, with much of it going to AWS, its cloud computing division.

Read More »

John Deere unveils more autonomous farm machines to address skill labor shortage

Join our daily and weekly newsletters for the latest updates and exclusive content on industry-leading AI coverage. Learn More Self-driving tractors might be the path to self-driving cars. John Deere has revealed a new line of autonomous machines and tech across agriculture, construction and commercial landscaping. The Moline, Illinois-based John Deere has been in business for 187 years, yet it’s been a regular as a non-tech company showing off technology at the big tech trade show in Las Vegas and is back at CES 2025 with more autonomous tractors and other vehicles. This is not something we usually cover, but John Deere has a lot of data that is interesting in the big picture of tech. The message from the company is that there aren’t enough skilled farm laborers to do the work that its customers need. It’s been a challenge for most of the last two decades, said Jahmy Hindman, CTO at John Deere, in a briefing. Much of the tech will come this fall and after that. He noted that the average farmer in the U.S. is over 58 and works 12 to 18 hours a day to grow food for us. And he said the American Farm Bureau Federation estimates there are roughly 2.4 million farm jobs that need to be filled annually; and the agricultural work force continues to shrink. (This is my hint to the anti-immigration crowd). John Deere’s autonomous 9RX Tractor. Farmers can oversee it using an app. While each of these industries experiences their own set of challenges, a commonality across all is skilled labor availability. In construction, about 80% percent of contractors struggle to find skilled labor. And in commercial landscaping, 86% of landscaping business owners can’t find labor to fill open positions, he said. “They have to figure out how to do

Read More »

2025 playbook for enterprise AI success, from agents to evals

Join our daily and weekly newsletters for the latest updates and exclusive content on industry-leading AI coverage. Learn More 2025 is poised to be a pivotal year for enterprise AI. The past year has seen rapid innovation, and this year will see the same. This has made it more critical than ever to revisit your AI strategy to stay competitive and create value for your customers. From scaling AI agents to optimizing costs, here are the five critical areas enterprises should prioritize for their AI strategy this year. 1. Agents: the next generation of automation AI agents are no longer theoretical. In 2025, they’re indispensable tools for enterprises looking to streamline operations and enhance customer interactions. Unlike traditional software, agents powered by large language models (LLMs) can make nuanced decisions, navigate complex multi-step tasks, and integrate seamlessly with tools and APIs. At the start of 2024, agents were not ready for prime time, making frustrating mistakes like hallucinating URLs. They started getting better as frontier large language models themselves improved. “Let me put it this way,” said Sam Witteveen, cofounder of Red Dragon, a company that develops agents for companies, and that recently reviewed the 48 agents it built last year. “Interestingly, the ones that we built at the start of the year, a lot of those worked way better at the end of the year just because the models got better.” Witteveen shared this in the video podcast we filmed to discuss these five big trends in detail. Models are getting better and hallucinating less, and they’re also being trained to do agentic tasks. Another feature that the model providers are researching is a way to use the LLM as a judge, and as models get cheaper (something we’ll cover below), companies can use three or more models to

Read More »

OpenAI’s red teaming innovations define new essentials for security leaders in the AI era

Join our daily and weekly newsletters for the latest updates and exclusive content on industry-leading AI coverage. Learn More OpenAI has taken a more aggressive approach to red teaming than its AI competitors, demonstrating its security teams’ advanced capabilities in two areas: multi-step reinforcement and external red teaming. OpenAI recently released two papers that set a new competitive standard for improving the quality, reliability and safety of AI models in these two techniques and more. The first paper, “OpenAI’s Approach to External Red Teaming for AI Models and Systems,” reports that specialized teams outside the company have proven effective in uncovering vulnerabilities that might otherwise have made it into a released model because in-house testing techniques may have missed them. In the second paper, “Diverse and Effective Red Teaming with Auto-Generated Rewards and Multi-Step Reinforcement Learning,” OpenAI introduces an automated framework that relies on iterative reinforcement learning to generate a broad spectrum of novel, wide-ranging attacks. Going all-in on red teaming pays practical, competitive dividends It’s encouraging to see competitive intensity in red teaming growing among AI companies. When Anthropic released its AI red team guidelines in June of last year, it joined AI providers including Google, Microsoft, Nvidia, OpenAI, and even the U.S.’s National Institute of Standards and Technology (NIST), which all had released red teaming frameworks. Investing heavily in red teaming yields tangible benefits for security leaders in any organization. OpenAI’s paper on external red teaming provides a detailed analysis of how the company strives to create specialized external teams that include cybersecurity and subject matter experts. The goal is to see if knowledgeable external teams can defeat models’ security perimeters and find gaps in their security, biases and controls that prompt-based testing couldn’t find. What makes OpenAI’s recent papers noteworthy is how well they define using human-in-the-middle

Read More »