如何使用GPT-4.1構建RAG代理?

如何使用GPT-4.1構建RAG代理?

檢索增強生成(RAG)系統透過整合外部文件檢索來生成語境豐富的響應,從而增強了人工智慧的生成能力。隨著 GPT 4.1 的釋出,構建代理 RAG 系統變得更加強大、高效和易於使用。在本文中,我們將瞭解 GPT-4.1 的強大之處,並學習如何使用 GPT-4.1 mini 構建代理 RAG 系統。

GPT 4.1概述

GPT 4.1 在其前代產品的基礎上進行了重大改進,在以下方面取得了巨大進步:

  • 編碼:在 SWE-bench 驗證中達到 55% 的成功率,大大超過 GPT 4o。
  • 指令跟蹤:增強了有效處理複雜、多步驟和細微指令的能力。
  • 長上下文:支援多達 100 萬個標記的上下文視窗,適用於廣泛的資料分析。不過,檢索準確率會隨著語境的延長而略有下降。
  • 成本效益:與 GPT-4o 相比,GPT-4.1 的成本降低了 83%,延遲降低了 50%。

GPT 4.1有哪些新功能?

OpenAI 推出了 GPT-4.1 系列,包括三種模型: GPT-4.1、GPT-4.1 Mini 和 GPT-4.1 Nano。以下是其提供的功能:

1. 1M令牌內涵:大思維提示

最重要的功能之一是100 萬個令牌上下文視窗 – 這是 OpenAI 的首創。現在,您可以一次性輸入大量程式碼塊、研究論文或整個文件集。儘管如此,雖然它的處理規模令人印象深刻,但隨著輸入的增加,精確度也會下降,因此它最好用於廣泛的上下文理解,而不是精確的外科手術。

2. 編碼升級:更智慧、多語言、更準確

SWE BENCH基準

在程式設計方面,GPT-4.1 有著明顯的優勢:

  • Python 基準測試:它在 SWE 基準測試中的得分率為 55%,超過了 GPT-4o。
  • 多語言程式碼任務:得益於 Polyglot 基準,它能比以前更好地處理多種語言。
  • 非常適合自動生成程式碼、除錯,甚至協助全棧構建。

3. 更好的指令跟蹤

指令跟蹤基準

GPT-4.1 現在能更好地響應多步驟指令和細微的格式規則。無論是設計工作流程還是構建人工智慧代理,該模型都能更好地滿足您的實際需求。

4. 速度與成本:一半的延遲,幾分之一的價格

GPT-4.1速度與成本表現

該版本針對效能和經濟性進行了最佳化:

  • 響應時間快 50
  • 比 GPT-4o 便宜 83
  • Nano 模型特別適合高頻率、預算敏感型應用–非常適合利潤空間狹小的擴充套件應用。
  • GPT-4.1 mini 模型旨在平衡智慧、速度和成本。它具有高智慧和高速度的特點,適合多種使用情況。
    • 定價:每輸入輸出 0.4 – 1.6 美元。
    • 輸入:文字和影像。
    • 輸出:文字。
    • 上下文視窗:1,047,576 個 token(處理能力大)。
    • 最大輸出:32,768 個片語。
    • 知識截止日期:2024 年 6 月 1 日。

GPT-4.1 mini模型

GPT系列模型基準對比

閱讀本文,瞭解更多有關GPT-4.1資訊

使用GPT 4.1 mini構建代理RAG

我正在使用 GPT 4.1 mini 構建一個多文件、代理式 RAG 系統。工作流程如下

  1. 輸入兩份長 PDF(ML 和 GenAI 經濟學)。
  2. 將它們分塊成重疊的片段(chunk_size=5000,chunk_overlap=300)–旨在保留上下文。
  3. 使用 OpenAI 的 text-embedding-3-small 模型嵌入這些塊。
  4. 將它們儲存在兩個獨立的 Chroma 向量儲存區中,以便進行高效的基於相似性的檢索。
  5. 將檢索+LLM 提示邏輯打包成兩個鏈(每個主題一個)。
  6. 將這些鏈作為工具提供給 LangChain Zero-Shot Agent,後者會將查詢路由到正確的上下文。
  7. 由於採用了大塊和高質量檢索,像“Why is Self-Attention used?”或“How will marketing change with GenAI?”這樣的查詢都能得到準確且符合上下文的回答。

1. 設定和安裝

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
!pip install langchain==0.3.23
!pip install -U langchain-openai
!pip install langchain-community==0.3.11
!pip install langchain-chroma==0.1.4
!pip install pypdf
!pip install langchain==0.3.23 !pip install -U langchain-openai !pip install langchain-community==0.3.11 !pip install langchain-chroma==0.1.4 !pip install pypdf
!pip install langchain==0.3.23
!pip install -U langchain-openai
!pip install langchain-community==0.3.11
!pip install langchain-chroma==0.1.4
!pip install pypdf

安裝必要的匯入程式

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_chroma import Chroma
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
from langchain.agents import AgentType, Tool, initialize_agent
from langchain_community.document_loaders import PyPDFLoader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_chroma import Chroma from langchain_openai import ChatOpenAI, OpenAIEmbeddings from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import RunnablePassthrough from langchain_core.output_parsers import StrOutputParser from langchain.agents import AgentType, Tool, initialize_agent
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_chroma import Chroma
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
from langchain.agents import AgentType, Tool, initialize_agent

我正在鎖定特定版本的 LangChain 軟體包和相關依賴項,以實現相容性–明智之舉。

2. OpenAI API金鑰

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from getpass import getpass
OPENAI_KEY = getpass('Enter Open AI API Key: ')
import os
os.environ['OPENAI_API_KEY'] = OPENAI_KEY
from getpass import getpass OPENAI_KEY = getpass('Enter Open AI API Key: ') import os os.environ['OPENAI_API_KEY'] = OPENAI_KEY
from getpass import getpass
OPENAI_KEY = getpass('Enter Open AI API Key: ')
import os
os.environ['OPENAI_API_KEY'] = OPENAI_KEY

3. 使用PyPDFLoader載入PDF

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
pdf_dir = "/content/document_pdf"
machinelearning_paper = os.path.join(pdf_dir, "Machinelearningalgorithm.pdf")
genai_paper = os.path.join(pdf_dir, "the-economic-potential-of-generative-ai-
the-next-productivity-frontier.pdf")
# Load individual PDF documents
print("Loading ml pdf...")
ml_loader = PyPDFLoader(machinelearning_paper)
ml_documents = ml_loader.load()
print("Loading genai pdf...")
genai_loader = PyPDFLoader(genai_paper)
genai_documents = genai_loader.load()
pdf_dir = "/content/document_pdf" machinelearning_paper = os.path.join(pdf_dir, "Machinelearningalgorithm.pdf") genai_paper = os.path.join(pdf_dir, "the-economic-potential-of-generative-ai- the-next-productivity-frontier.pdf") # Load individual PDF documents print("Loading ml pdf...") ml_loader = PyPDFLoader(machinelearning_paper) ml_documents = ml_loader.load() print("Loading genai pdf...") genai_loader = PyPDFLoader(genai_paper) genai_documents = genai_loader.load()
pdf_dir = "/content/document_pdf"
machinelearning_paper = os.path.join(pdf_dir, "Machinelearningalgorithm.pdf")
genai_paper = os.path.join(pdf_dir, "the-economic-potential-of-generative-ai-
the-next-productivity-frontier.pdf")
# Load individual PDF documents
print("Loading ml pdf...")
ml_loader = PyPDFLoader(machinelearning_paper)
ml_documents = ml_loader.load()
print("Loading genai pdf...")
genai_loader = PyPDFLoader(genai_paper)
genai_documents = genai_loader.load()

將 PDF 檔案載入到 LangChain 文件物件中。每一頁成為一個文件。

3. 使用RecursiveCharacterTextSplitter分塊

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Split the documents
text_splitter = RecursiveCharacterTextSplitter(chunk_size=5000, chunk_overlap=300)
ml_splits = text_splitter.split_documents(ml_documents)
genai_splits = text_splitter.split_documents(genai_documents)
print(f"Created {len(ml_splits)} splits for ml PDF")
print(f"Created {len(genai_splits)} splits for genai PDF")
# Split the documents text_splitter = RecursiveCharacterTextSplitter(chunk_size=5000, chunk_overlap=300) ml_splits = text_splitter.split_documents(ml_documents) genai_splits = text_splitter.split_documents(genai_documents) print(f"Created {len(ml_splits)} splits for ml PDF") print(f"Created {len(genai_splits)} splits for genai PDF")
# Split the documents
text_splitter = RecursiveCharacterTextSplitter(chunk_size=5000, chunk_overlap=300)
ml_splits = text_splitter.split_documents(ml_documents)
genai_splits = text_splitter.split_documents(genai_documents)
print(f"Created {len(ml_splits)} splits for ml PDF")
print(f"Created {len(genai_splits)} splits for genai PDF")

這是處理長上下文的核心。這個工具

  • 將語塊保持在 5000 個位元組以下。
  • 保留 300 個重疊的上下文。

遞迴分割器會嘗試分割段落 → 句子 → 字元,儘可能保留語義結構。

Ml_splits[:3]

Ml_splits[:3]

genai_splits[:5]

genai_splits[:5]

4. 使用OpenAIEmbedding進行嵌入

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# details here: https://openai.com/blog/new-embedding-models-and-api-updates
openai_embed_model = OpenAIEmbeddings(model='text-embedding-3-small')
# details here: https://openai.com/blog/new-embedding-models-and-api-updates openai_embed_model = OpenAIEmbeddings(model='text-embedding-3-small')
# details here: https://openai.com/blog/new-embedding-models-and-api-updates
openai_embed_model = OpenAIEmbeddings(model='text-embedding-3-small')

我使用的是 2024 text-embedding-3-small 模型:

  • 與舊模型相比,體積更小、速度更快、精度更高。
  • 非常適合進行高價效比、高質量的檢索。

5. 儲存在Chroma向量儲存器中

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Create separate vectorstores
ml_vectorstore = Chroma.from_documents(
documents=ml_splits,
embedding=openai_embed_model,
collection_metadata={"hnsw:space": "cosine"},
collection_name="ml-knowledge"
)
genai_vectorstore = Chroma.from_documents(
documents=genai_splits,
embedding=openai_embed_model,
collection_metadata={"hnsw:space": "cosine"},
collection_name="genai-knowledge"
)
# Create separate vectorstores ml_vectorstore = Chroma.from_documents( documents=ml_splits, embedding=openai_embed_model, collection_metadata={"hnsw:space": "cosine"}, collection_name="ml-knowledge" ) genai_vectorstore = Chroma.from_documents( documents=genai_splits, embedding=openai_embed_model, collection_metadata={"hnsw:space": "cosine"}, collection_name="genai-knowledge" )
# Create separate vectorstores
ml_vectorstore = Chroma.from_documents(
   documents=ml_splits,
   embedding=openai_embed_model,
   collection_metadata={"hnsw:space": "cosine"},
   collection_name="ml-knowledge"
)
genai_vectorstore = Chroma.from_documents(
   documents=genai_splits,
   embedding=openai_embed_model,
   collection_metadata={"hnsw:space": "cosine"},
   collection_name="genai-knowledge"
)

在這裡,我建立了兩個向量儲存空間:

  • 一個用於儲存與 ML 相關的資料塊
  • 一個用於與 GenAI 相關的資料塊

使用餘弦相似性進行檢索:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
ml_retriever = ml_vectorstore.as_retriever(search_type="similarity_score_threshold",search_kwargs={"k": 5,"score_threshold": 0.3})
genai_retriever = genai_vectorstore.as_retriever(search_type="similarity_score_threshold",search_kwargs={"k": 5,"score_threshold": 0.3})
ml_retriever = ml_vectorstore.as_retriever(search_type="similarity_score_threshold",search_kwargs={"k": 5,"score_threshold": 0.3}) genai_retriever = genai_vectorstore.as_retriever(search_type="similarity_score_threshold",search_kwargs={"k": 5,"score_threshold": 0.3})
ml_retriever = ml_vectorstore.as_retriever(search_type="similarity_score_threshold",search_kwargs={"k": 5,"score_threshold": 0.3})
genai_retriever = genai_vectorstore.as_retriever(search_type="similarity_score_threshold",search_kwargs={"k": 5,"score_threshold": 0.3})

只返回相似度足夠高的前 5 塊。使答案保持緊湊。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
query = "what are ML algorithms?"
top3_docs = ml_retriever.invoke(query)
top3_docs
query = "what are ML algorithms?" top3_docs = ml_retriever.invoke(query) top3_docs
query = "what are ML algorithms?"
top3_docs = ml_retriever.invoke(query)
top3_docs

儲存在Chroma向量儲存器中

6. 檢索和建立提示

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Create the prompt templates
ml_prompt = ChatPromptTemplate.from_template(
"""
You are an expert in machine learning algorithms with deep technical knowledge of the field.
Answer the following question based solely on the provided context extracted from relevant machine learning research documents.
Context:
{context}
Question:
{question}
If the answer cannot be found in the context, please respond with: "I don't have enough information to answer this question based on the provided context."
"""
)
genai_prompt = ChatPromptTemplate.from_template(
"""
You are an expert in the economic impact and potential of generative AI technologies across industries and markets.
Answer the following question based only on the provided context related to the economic aspects of generative AI.
Context:
{context}
Question:
{question}
If the answer cannot be found in the context, please state "I don't have enough information to answer this question based on the provided context."
"""
)
# Create the prompt templates ml_prompt = ChatPromptTemplate.from_template( """ You are an expert in machine learning algorithms with deep technical knowledge of the field. Answer the following question based solely on the provided context extracted from relevant machine learning research documents. Context: {context} Question: {question} If the answer cannot be found in the context, please respond with: "I don't have enough information to answer this question based on the provided context." """ ) genai_prompt = ChatPromptTemplate.from_template( """ You are an expert in the economic impact and potential of generative AI technologies across industries and markets. Answer the following question based only on the provided context related to the economic aspects of generative AI. Context: {context} Question: {question} If the answer cannot be found in the context, please state "I don't have enough information to answer this question based on the provided context." """ )
# Create the prompt templates
ml_prompt = ChatPromptTemplate.from_template(
   """
   You are an expert in machine learning algorithms with deep technical knowledge of the field.
   Answer the following question based solely on the provided context extracted from relevant machine learning research documents.
   Context:
   {context}
   Question:
   {question}
   If the answer cannot be found in the context, please respond with: "I don't have enough information to answer this question based on the provided context."
   """
)
genai_prompt = ChatPromptTemplate.from_template(
   """
   You are an expert in the economic impact and potential of generative AI technologies across industries and markets.
   Answer the following question based only on the provided context related to the economic aspects of generative AI.
   Context:
   {context}
   Question:
   {question}
    If the answer cannot be found in the context, please state "I don't have enough information to answer this question based on the provided context."
   """
)

在這裡,我建立的是針對具體語境的提示:

  • ML QA 系統:詢問演算法、訓練等。
  • GenAI QA 系統:關注經濟影響和跨行業使用。

這些提示還可以防止出現幻覺:

“If the answer cannot be found in the context… respond with: ‘I don’t have enough information…’”

完美的可靠性。

7. LCEL鏈

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model_name='gpt-4.1-mini-2025-04-14', temperature=0)
from langchain_openai import ChatOpenAI llm = ChatOpenAI(model_name='gpt-4.1-mini-2025-04-14', temperature=0)
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model_name='gpt-4.1-mini-2025-04-14', temperature=0)
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
def format_docs(docs): return "\n\n".join(doc.page_content for doc in docs)
def format_docs(docs):
   return "\n\n".join(doc.page_content for doc in docs)
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Create the RAG chains using LCEL
ml_chain = (
{
"context": lambda question: format_docs(ml_retriever.get_relevant_documents(question)),
"question": RunnablePassthrough()
}
| ml_prompt
| llm
| StrOutputParser()
)
genai_chain = (
{
"context": lambda question: format_docs(genai_retriever.get_relevant_documents(question)),
"question": RunnablePassthrough()
}
| genai_prompt
| llm
| StrOutputParser()
)
# Create the RAG chains using LCEL ml_chain = ( { "context": lambda question: format_docs(ml_retriever.get_relevant_documents(question)), "question": RunnablePassthrough() } | ml_prompt | llm | StrOutputParser() ) genai_chain = ( { "context": lambda question: format_docs(genai_retriever.get_relevant_documents(question)), "question": RunnablePassthrough() } | genai_prompt | llm | StrOutputParser() )
# Create the RAG chains using LCEL
ml_chain = (
   {
       "context": lambda question: format_docs(ml_retriever.get_relevant_documents(question)),
       "question": RunnablePassthrough()
   }
   | ml_prompt
   | llm
   | StrOutputParser()
)
genai_chain = (
   {
       "context": lambda question: format_docs(genai_retriever.get_relevant_documents(question)),
       "question": RunnablePassthrough()
   }
   | genai_prompt
   | llm
   | StrOutputParser()
)

這正是 LangChain Expression Language (LCEL) 的優勢所在。

  1. 檢索語塊
  2. 將其格式化為上下文
  3. 注入提示符
  4. 傳送至 gpt-4.1-mini
  5. 解析響應字串

它優雅、可重用、模組化。

8. 定義代理工具

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Define the tools
tools = [
Tool(
name="ML Knowledge QA System",
func=ml_chain.invoke,
description="Useful for when you need to answer questions related to machine learning concepts, models, training techniques, evaluation metrics, algorithms and practical implementations. Covers supervised and unsupervised learning, model optimization, bias-variance tradeoff, feature engineering, and algorithm selection. Input should be a fully formed question."
),
Tool(
name="GenAI QA System",
func=genai_chain.invoke,
description="Useful for when you need to answer questions about the economic impact, market potential, and cross-industry implications of generative AI technologies. Input should be a fully formed question. Responses are based strictly on the provided context related to the economics of generative AI."
)
]
# Define the tools tools = [ Tool( name="ML Knowledge QA System", func=ml_chain.invoke, description="Useful for when you need to answer questions related to machine learning concepts, models, training techniques, evaluation metrics, algorithms and practical implementations. Covers supervised and unsupervised learning, model optimization, bias-variance tradeoff, feature engineering, and algorithm selection. Input should be a fully formed question." ), Tool( name="GenAI QA System", func=genai_chain.invoke, description="Useful for when you need to answer questions about the economic impact, market potential, and cross-industry implications of generative AI technologies. Input should be a fully formed question. Responses are based strictly on the provided context related to the economics of generative AI." ) ]
# Define the tools
tools = [
   Tool(
       name="ML Knowledge QA System",
       func=ml_chain.invoke,
       description="Useful for when you need to answer questions related to machine learning concepts, models, training techniques, evaluation metrics, algorithms and practical implementations. Covers supervised and unsupervised learning, model optimization, bias-variance tradeoff, feature engineering, and algorithm selection. Input should be a fully formed question."
       ),
   Tool(
       name="GenAI QA System",
       func=genai_chain.invoke,
       description="Useful for when you need to answer questions about the economic impact, market potential, and cross-industry implications of generative AI technologies. Input should be a fully formed question. Responses are based strictly on the provided context related to the economics of generative AI."
       )
]

每個鏈都會成為 LangChain 中的一個工具。工具就像代理的即插即用功能。

9. 初始化代理

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Initialize the agent
agent = initialize_agent(
tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
# Initialize the agent agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True )
# Initialize the agent
agent = initialize_agent(
   tools,
   llm,
   agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
   verbose=True
)

我使用的是 Zero-Shot ReAct 代理,它可以解釋查詢,決定使用哪種工具(ML 或 GenAI),並相應地路由輸入。

10. 查詢時間!

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
result = agent.invoke("How marketing and sale could be transformed using Generative AI?")
result = agent.invoke("How marketing and sale could be transformed using Generative AI?")
result = agent.invoke("How marketing and sale could be transformed using Generative AI?")

查詢時間!

代理:

  1. 選擇 GenAI QA 系統
  2. 從 GenAI 向量儲存中檢索頂級上下文塊
  3. 格式化提示
  4. 傳送到 GPT-4.1
  5. 返回接地的、無幻覺的答案
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
result1 = agent.invoke("why Self-Attention is used?")
result1 = agent.invoke("why Self-Attention is used?")
result1 = agent.invoke("why Self-Attention is used?")

查詢時間!-2

代理:

  1. 選擇 ML QA 系統
  2. 從 ML 向量儲存中檢索頂級上下文塊
  3. 格式化提示
  4. 傳送到 GPT-4.1mini
  5. 返回接地的非幻聽答案
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
result2 = agent.invoke("what are Tree-based algorithms?")
result2 = agent.invoke("what are Tree-based algorithms?")
result2 = agent.invoke("what are Tree-based algorithms?")

查詢時間!-3

事實證明,GPT-4.1 在處理大型文件時非常有效,這要歸功於其擴充套件的上下文視窗,可容納多達 100 萬個標記。這一改進消除了以前的模型所面臨的長期限制,在以前的模型中,文件必須被大量分塊成小片段,往往會失去語義的連貫性。

由於 GPT-4.1 能夠處理大塊文件,例如這裡使用的 5000 個標記段,因此它可以對密集、資訊豐富的部分進行攝取和推理,而不會丟失跨段落或跨頁面的上下文連結。在涉及學術論文或行業白皮書等複雜文件的情況下,這一點尤為重要,因為對這些文件的理解往往取決於多頁的連續性。該模型能準確處理這些擴充套件的大塊內容,並提供基於上下文的響應,而不會產生幻覺,精心設計的檢索提示進一步增強了這一能力。

此外,在 RAG 管道中,響應的質量在很大程度上取決於模型一次能消耗多少有用的上下文。GPT-4.1 消除了以前的上限,使檢索和推理完整的概念單元而不是零散的摘錄成為可能。因此,您可以對冗長的文件提出深層次、細緻入微的問題,並得到精確、有理有據的回答,這使得 GPT-4.1 成為生產級文件分析和基於檢索的應用的變革者。

不僅僅是Needle in a Haystack

GPT-4.1 Needle in a Haystack基準

這是一個 needle-in-a-haystack 基準測試,用於評估不同模型在檢索或推理埋藏在冗長上下文(“haystack”)中的相關資訊(“needle”)方面的能力。

GPT-4.1 擅長在大型文件中查詢特定事實,但 OpenAI 透過 OpenAI-MRCR 基準進一步推動了這一工作,該基準測試多事實檢索:

  • 對於 2 個關鍵事實(“needles”),GPT-4.1 的表現優於 OpenAIMRCR: GPT-4.1 比 4.0 做得更好。
  • 對於 4 個或更多:像 GPT-4.5 這樣的大型模型仍佔優勢,尤其是在較短的輸入場景中。

8-needle 場景–即在較長的標記序列中嵌入 8 個相關資訊,測試模型準確檢索或引用這些資訊的能力。

因此,雖然 GPT-4.1 可以很好地處理基本的長語境任務,但它還不能完全勝任深度的、相互關聯的推理。

2 Needle

這通常是指任務的簡化版本,可能是類別更少或決策點更簡單。在這種情況下,“準確度”是根據模型在區分兩個類別或做出兩個不同決策時的表現來衡量的。

OpenAI MRCR 精確度 2needle Lightmode

Source: OpenAI

4 Needle

這將涉及一項更復雜的任務,需要預測四個不同的類別或結果。與“2 needle”相比,這對模型來說是一項更具挑戰性的任務,意味著模型必須做出更細微的區分。

OpenAI MRCR 精確度 4needle Lightmode

Source: OpenAI

8 Needle

這是一個更加複雜的場景,模型必須從八個不同的類別或結果中進行正確預測。needle 數越多,任務就越具有挑戰性,要求模型展現出更廣泛的理解力和準確性。

OpenAI MRCR 精確度 8needle Lightmode

來源:OpenAI

不過,根據你的使用情況(尤其是如果你正在處理 20 萬個以下的代幣),DeepSeek-R1 或 Gemini 2.5 等替代品可能會給你帶來更高的價效比。

但是,如果您的需求包括前沿推理或最新知識,那麼請關注 GPT-4.5 或 Gemini 等競爭對手。

GPT-4.1 可能不會徹底改變遊戲規則,但它是一次明智的進化,尤其是對開發者而言。OpenAI 將重點放在了實際改進上:更好的編碼支援、更長的上下文處理以及更低的成本,從而使模型更容易獲得。

不過,在基準透明度和知識新鮮度等方面,OpenAI 仍給競爭對手留下了躍躍欲試的空間。隨著競爭的加劇,GPT-4.1 證明了 OpenAI 正在傾聽–現在該谷歌、Anthropic 和其他公司行動了。

為什麼分塊法效果如此之好(5000 + 300 重疊)?

配置

  • chunk_size = 5000
  • chunk_overlap = 300

為什麼這對GPT-4.1有效?

  • GPT-4.1 支援 1M 標記上下文。現在,輸入更長的語塊終於有用了。較小的語塊會遺漏跨段落的觀點之間的語義粘合。
  • 5000 個標記的語塊可確保語義分割最小化,並捕捉到“Transformer 架構 ”或“GenAI 的經濟影響”等大型概念單元。
  • 300 個標記符號的重疊有助於保留跨塊上下文,防止出現割裂問題。

這可能就是你沒有看到遺漏或幻覺的原因–你為 LLM 提供的正是它所需的分塊上下文。

好了,讓我們透過一個分步指南來詳細說明如何使用 GPT-4.1 構建一個代理檢索-增強生成(RAG)管道,並透過對兩份大型 PDF 檔案(每份 50 多頁)進行分塊和索引來利用其 100 萬個令牌上下文視窗功能,從而檢索出準確的答案,且不會出現幻覺。

GPT 4.1的主要優勢和注意事項

  • 增強檢索功能:與 GPT-4.5 等大型模型相比,在單一事實檢索方面效能優越,但在複雜的多資訊綜合任務中效率略低。
  • 成本效益 :特別是 Nano 變體,非常適合對預算敏感的高吞吐量任務。
  • 對開發人員友好:非常適合編碼應用、法律檔案分析和冗長的上下文任務。

小結

GPT-4.1 Mini 是構建代理檢索-增強生成(RAG)系統的穩健而經濟的基礎。GPT-4.1 Mini 支援 100 萬個標記的上下文視窗,因此可以輸入大量語義豐富的文件塊,從而增強了模型提供基於上下文的準確響應的能力。

GPT-4.1 Mini 增強的指令跟蹤能力、長語境處理能力和經濟性使其成為開發複雜的生產級 RAG 應用程式的絕佳選擇。它的設計有利於與大量檔案進行深入、細緻的互動,使其成為人工智慧驅動的資訊檢索領域不斷發展的寶貴資產。

評論留言