from openai import OpenAI
from IPython.display import Markdown, display
client = OpenAI()
response = client.responses.create(
model="gpt-4.1-nano",input="Write a proper blog on getting rich.")
Markdown(response.output_text)技术支持
GPT-4.1 Nano 模型给出了格式良好且简洁的回复。
2. 使用 GPT-4.1 Mini 模型进行图像理解
接下来,我们将向 GPT-4.1 Mini 模型提供一张图片 URL,并让它以哲学风格描述该图像。
response = client.responses.create(
model="gpt-4.1-mini",input=[{"role":"user","content":[{"type":"input_text","text":"Please describe the image as a philosopher would."},{"type":"input_image","image_url":"https://thumbs.dreamstime.com/b/lucha-de-dos-vacas-56529466.jpg",},],}],)print(response.output_text)技术支持
GPT-4.1 Mini 模型对图像给出了细致而富有创意的描述,展现了其对视觉内容的理解能力。
3. 使用 GPT-4.1(完整)模型生成代码
现在,我们将使用“完整”版本的 GPT-4.1 模型生成代码。
在此示例中,我们将向模型提供系统指令和用户提示,并启用流式响应。
import sys
# Request a streamed response from the model.
stream = client.responses.create(
model="gpt-4.1",
instructions="You are a machine learning engineer, which is an expert in creating model inference.",input="Create a FastAPI app for image classification",
stream=True,)# Iterate over stream events and print text as soon as it's received.for event in stream:# Check if the event includes a text delta.ifhasattr(event,"delta")and event.delta:
sys.stdout.write(event.delta)
sys.stdout.flush()技术支持
import base64
from openai import OpenAI
client = OpenAI()withopen("main.py","rb")as f:
data = f.read()
base64_string = base64.b64encode(data).decode("utf-8")
response = client.responses.create(
model="gpt-4.1",input=[{"role":"user","content":[{"type":"input_file","filename":"main.py","file_data":f"data:text/x-python;base64,{base64_string}",},{"type":"input_text","text":"Enhance the code by incorporating additional features to improve the user experience.",},],},])
Markdown(response.output_text)技术支持
import os
defsearch_codebase(directory:str, keywords:list, allowed_extensions:list)->list:"""
Search for code snippets in the codebase that match any of the given keywords.
Returns a list of dictionaries with file path, the line number where a match was found,
and a code snippet that includes 2 lines of context before and after the matched line.
"""
matches =[]for root, _, files in os.walk(directory):forfilein files:iffile.endswith(tuple(allowed_extensions)):
file_path = os.path.join(root,file)try:withopen(file_path,"r", encoding="utf-8", errors="ignore")as f:
lines = f.readlines()for i, line inenumerate(lines):# Check if any keyword is in the current line (case insensitive)ifany(keyword in line.lower()for keyword in keywords):
snippet ={"file": file_path,"line_number": i +1,"code":"".join(lines[max(0, i -2): i +3]),}
matches.append(snippet)except Exception as e:print(f"Skipping file {file_path}: {e}")return matches技术支持
import os
from openai import OpenAI
defquery_gpt(question:str, matches:list):"""
Queries GPT-4.1 with the developer's question and the relevant code snippets,
then returns the generated explanation.
"""ifnot matches:return"No code snippets found to generate an explanation."# Combine all matches into a formatted string
code_context ="\n\n".join([f"File: {match['file']} (Line {match['line_number']}):\n{match['code']}"formatchin matches
])# Create the GPT-4.1 prompt
system_message ="You are a helpful coding assistant that explains code based on provided snippets."
user_message =f"""A developer asked the following question:
"{question}"
Here are the relevant code snippets:
{code_context}
Based on the code snippets, answer the question clearly and concisely.
"""# Load API key from environment variable
api_key = os.environ.get("OPENAI_API_KEY")ifnot api_key:return"Error: OPENAI_API_KEY environment variable is not set."# Create an OpenAI client using the API key
client = OpenAI(api_key=api_key)try:# Return the stream object for the caller to processreturn client.responses.create(
model="gpt-4.1",input=[{"role":"system","content": system_message},{"role":"user","content": user_message},],
stream=True,)except Exception as e:returnf"Error generating explanation: {e}"技术支持
import argparse
from gpt_explainer import query_gpt
from searcher import search_codebase
defprint_streaming_response(stream):"""Print the streaming response from GPT-4.1"""print("\nGPT-4.1 Response:")for event in stream:# Check if the event includes a text delta.ifhasattr(event,"delta")and event.delta:print(event.delta, end="")print("\n")defmain():
parser = argparse.ArgumentParser(
description="Keyword-Based Code Search with GPT-4.1")
parser.add_argument("--path", required=True,help="Path to the codebase")
args = parser.parse_args()
allowed_extensions =[".py",".js",".txt",".md",".html",".css",".sh"]print("Welcome to the Code Search Chatbot!")print("Ask questions about your codebase or type 'quit' to exit.")whileTrue:
question =input("\nEnter your question about the codebase: ")if question.lower()=="quit":print("Exiting chatbot. Goodbye!")break# Extract keywords from the question and remove stop words
stop_words ={'a','an','the','and','or','but','is','are','was','were','in','on','at','to','for','with','by','about','like','from','of','as','how','what','when','where','why','who'}
keywords =[word for word in question.lower().split()if word notin stop_words][:5]print("Searching codebase...")
matches = search_codebase(args.path, keywords, allowed_extensions)ifnot matches:print("No relevant code snippets found.")continueprint("Querying GPT-4.1...")
stream = query_gpt(question, matches)
print_streaming_response(stream)if __name__ =="__main__":
main()技术支持
Welcome to the Code Search Chatbot!
Ask questions about your codebase or type 'quit' to exit.
Enter your question about the codebase: help me improve the training script技术支持
应用会在代码库中搜索相关片段,并查询 GPT-4.1 以生成回复。
Searching codebase...
Querying GPT-4.1...
GPT-4.1 Response:
Certainly! Based on the provided snippets, here's how you can **improve the training script (`train.py`)** for your phishing email classification proje...........技术支持
您可以继续追问以了解整个项目。
Enter your question about the codebase: help me understand the project技术支持
这一详细说明有助于开发者理解项目的目的、功能与结构。
Searching codebase...
Querying GPT-4.1...
GPT-4.1 Response:
Certainly! Here's a concise overview of the project based on your code snippets:
## Project Purpose**Phishing Email Classification App with Redis**
This project classifies emails as "Phishing" or "Safe" using machine learning and serves predictions via a web API. It also uses Redis for caching predictions to optimize performance…………技术支持
最近,OpenAI 发布了 GPT-4.1 系列,包括三个变体:GPT-4.1、GPT-4.1 Mini 和 GPT-4.1 Nano。这些模型在编码与指令执行任务上表现出色,相较前代有显著提升。
其中一大亮点是将上下文窗口扩展到最多 100 万个 token——是 GPT-4 的八倍以上。此增强使模型能够处理超大输入,例如整个代码仓库或多文档工作流。
在本教程中,我们将通过构建一个项目来探索 GPT-4.1 的能力:该项目允许用户根据提示中的关键词搜索整个代码仓库。随后,我们会将仓库中的相关内容与用户的提示一并提供给 GPT-4.1 模型。
最终,我们将创建一个交互式应用,让用户能够与其代码仓库对话,并使用 GPT-4.1 分析与改进完整代码源。
我们通过每周五发布的免费通讯 The Median,为读者带来最新 AI 动态,精炼解读一周要闻。订阅即可每周用几分钟保持前沿:
开始使用 GPT-4.1 模型
在着手构建项目之前,建议先测试 GPT-4.1 各版本并体验新的
responsesAPI。该高级 API支持将先前输出作为输入进行有状态交互,支持文本和图像等多模态输入,并通过内置的文件搜索、网页搜索和函数调用连接外部系统等工具扩展模型能力。首先,请确保已安装最新版 OpenAI Python 客户端。您可以在终端运行以下命令:
1. 使用 GPT-4.1 Nano 模型生成文本
在此示例中,我们将使用针对速度与成本优化的 GPT-4.1 Nano 模型来生成文本。
首先,我们初始化 OpenAI 客户端,并通过响应 API 生成回复。
GPT-4.1 Nano 模型给出了格式良好且简洁的回复。
2. 使用 GPT-4.1 Mini 模型进行图像理解
接下来,我们将向 GPT-4.1 Mini 模型提供一张图片 URL,并让它以哲学风格描述该图像。
GPT-4.1 Mini 模型对图像给出了细致而富有创意的描述,展现了其对视觉内容的理解能力。
3. 使用 GPT-4.1(完整)模型生成代码
现在,我们将使用“完整”版本的 GPT-4.1 模型生成代码。
在此示例中,我们将向模型提供系统指令和用户提示,并启用流式响应。
我们使用系统级输出(
sys.stdout)实时显示流式响应。4. 使用 GPT-4.1 模型结合文件输入生成代码
最后,我们将通过向 GPT-4.1 模型提供一个 Python 文件来测试其大上下文窗口能力。该文件以 Base64 格式编码,并与用户指令一起发送给模型。
GPT-4.1 模型基于上下文提出了改进代码的建议,展示了其处理大规模输入的能力。
如果您在运行上述代码时遇到问题,请参考 DataLab 工作簿:Playing with GPT-4.1 API — DataLab。
构建基于关键词的代码搜索应用
基于关键词的代码搜索应用旨在帮助开发者高效地在代码库中按特定关键词查找相关片段,然后使用 GPT-4.1 对代码进行讲解或给出见解。
该应用由三个主要部分组成:
1. 搜索代码库
应用的第一步是搜索代码库中与开发者查询相匹配的相关片段。这通过
search_codebase函数实现,该函数会在指定目录中扫描文件,查找包含目标关键词的行。searcher.py:2. GPT 4.1 查询
识别出相关代码片段后,下一步是查询 GPT-4.1,让其生成关于代码的讲解或见解。
query_gpt函数接收开发者的问题与匹配到的代码片段作为输入,并返回详细回复。gpt_explainer.py:3. 基于关键词的代码搜索聊天应用
应用的最后一部分是交互式聊天机器人,它将上述流程整合起来。它允许开发者就其代码库提出问题,从查询中提取关键词,搜索相关代码片段,并将这些内容连同用户的问题一并发送给 GPT-4.1 生成回复。
main.py:该聊天机器人为开发者提供了顺畅的使用体验,使其能够与代码库交互并获取由 AI 提供的洞见。
该项目还包含一个代码仓库(kingabzpro/Keyword-Code-Search),其中包含源代码及其使用说明。
测试基于关键词的代码搜索应用
本节我们将在终端中运行该应用并体验其功能。
要运行该应用,您需要提供要分析的代码仓库路径。本示例中我们使用“Redis ML 项目”。
您将看到欢迎信息与使用说明。直接输入您关于代码的提问,或请它改进代码库的某个部分。
应用会在代码库中搜索相关片段,并查询 GPT-4.1 以生成回复。
您可以继续追问以了解整个项目。
这一详细说明有助于开发者理解项目的目的、功能与结构。
要退出应用,只需输入“quit”:
基于关键词的代码搜索应用虽小却强大,能让开发者与其代码仓库对话。它将高效的关键词代码搜索与 GPT-4.1 生成上下文感知回复的能力相结合。无论您需要改进代码库的某一部分,还是想理解整个项目,该应用都能提供顺畅直观的体验。
结语
整个 AI 领域正在远离炒作与表面基准,转而专注于提供真正的价值而非幻象。GPT-4.1 系列让开发者体验更进一步,使大语言模型能够直接生成高准确度且可运行的代码。此外,这些模型具备大上下文窗口,能够一次性理解整个代码仓库。
如果您想亲手实践 OpenAI API,请查看我们的课程Working with the OpenAI API,开始开发 AI 驱动的应用。您也可以查看我们关于Responses API 的教程,进一步了解全新的 o4-mini 推理模型。