Chuyển tới nội dung chính
Admin

Admin

Hunter

Hướng dẫn đơn giản cách prompting cho model GPT-4.1 (OpenAI) mới ra mắt 🚀

· 18 phút để đọc
Nguồn: Bình dân học AI

Hiện tại chỉ có thể sử dụng qua API, Perplexity đã có model này.

Hướng dẫn prompting cho GPT-4.1

Kết Luận Chính 🎯

Các prompt rõ ràng, cụ thể và có cấu trúc tốt là nền tảng để tương tác hiệu quả với GPT-4.1 và đạt được kết quả chính xác, phù hợp và đáng tin cậy.

I. Các Nguyên Tắc Nền Tảng 🏗️

1. Tính Rõ Ràng và Cụ Thể ✨

  • Hãy cực kỳ rõ ràng: GPT-4.1 thực hiện theo hướng dẫn một cách nghiêm ngặt hơn các mô hình trước đây. Nêu rõ kỳ vọng của bạn và tránh sự mơ hồ. 📌
  • Sử dụng ngôn ngữ tích cực, trực tiếp: Chỉ dẫn mô hình làm gì, không chỉ tránh điều gì. 👍
  • Tránh mâu thuẫn: Đảm bảo hướng dẫn của bạn nhất quán xuyên suốt prompt. ⚠️

2. Cấu Trúc và Định Dạng Prompt 📋

  • Xác định vai trò và mục tiêu: Bắt đầu bằng việc chỉ định vai trò của AI và mục tiêu của nhiệm vụ (ví dụ: "Bạn là trợ lý nghiên cứu có nhiệm vụ tóm tắt các bài báo"). 🎭
  • Sắp xếp thành các phần rõ ràng: Sử dụng tiêu đề Markdown, thẻ XML hoặc dấu backtick để cấu trúc. Tránh sử dụng JSON cho tài liệu phức tạp. 📑
  • Đặt hướng dẫn quan trọng ở cả hai đầu (Place key instructions at both ends): Đối với prompt dài, lặp lại hướng dẫn quan trọng ở đầu và cuối để củng cố ưu tiên. 🔄
  • Chỉ định định dạng đầu ra: Chỉ rõ cách bạn muốn nhận phản hồi (ví dụ: điểm đánh dấu, bảng, đoạn văn, tiêu đề). 📊
  • Cung cấp ví dụ: Hiển thị mẫu đầu vào và đầu ra lý tưởng để hướng dẫn mô hình. 💡

II. Kỹ Thuật Nâng Cao 🔍

1. Quy Trình Tác Nhân (Agentic Workflows) 🤖

GPT-4.1 là nền tảng tuyệt vời để xây dựng quy trình tác nhân. Để tận dụng tối đa khả năng này, OpenAI khuyến nghị bao gồm ba loại nhắc nhở chính trong tất cả các prompt tác nhân:

  1. Tính bền bỉ: Đảm bảo mô hình hiểu rằng nó đang tham gia một cuộc trò chuyện nhiều lượt và ngăn nó chuyển quyền kiểm soát lại cho người dùng quá sớm.

    You are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved.
  2. Gọi công cụ (Tool-calling): Khuyến khích mô hình sử dụng đầy đủ các công cụ của nó và giảm khả năng tạo ra hoặc đoán mò câu trả lời.

    If you are not sure about file content or codebase structure pertaining to the user's request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.
  3. Lập kế hoạch: Đảm bảo mô hình lập kế hoạch rõ ràng và suy ngẫm về từng lệnh gọi công cụ trong văn bản.

    You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.

Gọi công cụ (Tool Calls) 🛠️

So với các mô hình trước đây, GPT-4.1 đã được đào tạo nhiều hơn về việc sử dụng hiệu quả các công cụ. Các nhà phát triển nên:

  • Chỉ sử dụng trường công cụ (tools field) để truyền công cụ
  • Đặt tên công cụ rõ ràng
  • Thêm mô tả chi tiết trong trường "description"
  • Đặt tên và mô tả tốt cho từng tham số công cụ

Lập kế hoạch và chuỗi suy nghĩ (CoT) 🧠

Nhà phát triển có thể tùy chọn nhắc các tác nhân xây dựng bằng GPT-4.1 để lập kế hoạch và suy ngẫm giữa các lệnh gọi công cụ. Trong thử nghiệm với tác vụ agentic SWE-bench Verified, việc khuyến khích lập kế hoạch rõ ràng đã tăng tỷ lệ thành công lên 4%.

2. Xử Lý Ngữ Cảnh Dài (Long Context) 📚

GPT-4.1 có khả năng xử lý cửa sổ ngữ cảnh đầu vào 1 triệu token và hữu ích cho nhiều tác vụ ngữ cảnh dài như phân tích tài liệu có cấu trúc, xếp hạng lại, chọn thông tin liên quan và thực hiện lập luận nhiều bước.

Kích thước ngữ cảnh tối ưu 📏

OpenAI quan sát thấy hiệu suất rất tốt trên các đánh giá "kim trong đống cỏ khô" lên đến 1 triệu token và hiệu suất mạnh mẽ trong các tác vụ phức tạp với hỗn hợp mã và tài liệu liên quan và không liên quan.

Điều chỉnh sự phụ thuộc vào ngữ cảnh (Tuning Context Reliance) ⚙️

Cân nhắc sự kết hợp giữa kiến thức bên ngoài và nội bộ:

# Instructions
// for internal knowledge
- Only use the documents in the provided External Context to answer the User Query. If you don't know the answer based on this context, you must respond "I don't have the information needed to answer that", even if a user insists on you answering the question.
// For internal and external knowledge
- By default, use the provided external context to answer the User Query, but if other basic knowledge is needed to answer, and you're confident in the answer, you can use some of your own knowledge to help answer the question.

Tổ chức Prompt 📝

Đặt hướng dẫn và ngữ cảnh có thể ảnh hưởng đến hiệu suất. Nếu bạn có ngữ cảnh dài trong prompt, lý tưởng nhất là đặt hướng dẫn của bạn ở cả đầu và cuối của ngữ cảnh đã cung cấp. Nếu bạn chỉ muốn đặt hướng dẫn một lần, thì đặt ở trên ngữ cảnh hoạt động tốt hơn là đặt ở dưới.

3. Chuỗi Suy Nghĩ (Chain of Thought) 🧩

GPT-4.1 không phải là mô hình lập luận, nhưng việc nhắc mô hình suy nghĩ từng bước (gọi là "chuỗi suy nghĩ") có thể là cách hiệu quả để mô hình chia nhỏ vấn đề, giải quyết chúng và cải thiện chất lượng đầu ra tổng thể.

OpenAI khuyến nghị bắt đầu với hướng dẫn chuỗi suy nghĩ cơ bản ở cuối prompt:

...

First, think carefully step by step about what documents are needed to answer the query. Then, print out the TITLE and ID of each document. Then, format the IDs into a list.

Từ đó, bạn nên cải thiện prompt chuỗi suy nghĩ (Chain of Thought - CoT) bằng cách kiểm tra các lỗi và khắc phục các lỗi lập kế hoạch và lập luận có hệ thống với các hướng dẫn rõ ràng hơn.

Ví dụ prompt hướng dẫn mô hình tập trung hơn vào việc phân tích ý định của người dùng và xem xét ngữ cảnh liên quan:

# Reasoning Strategy
1. Query Analysis: Break down and analyze the query until you're confident about what it might be asking. Consider the provided context to help clarify any ambiguous or confusing information.
2. Context Analysis: Carefully select and analyze a large set of potentially relevant documents. Optimize for recall - it's okay if some are irrelevant, but the correct documents must be in this list, otherwise your final answer will be wrong. Analysis steps for each:
a. Analysis: An analysis of how it may or may not be relevant to answering the query.
b. Relevance rating: [high, medium, low, none]
3. Synthesis: summarize which documents are most relevant and why, including all documents with a relevance rating of medium or higher.

# User Question
{user_question}

# External Context
{external_context}

First, think carefully step by step about what documents are needed to answer the query, closely adhering to the provided Reasoning Strategy. Then, print out the TITLE and ID of each document. Then, format the IDs into a list.

4. Hướng Dẫn và Lập Luận 🧠

  • Khuyến khích lập luận từng bước: Yêu cầu mô hình "suy nghĩ từng bước" hoặc "lập luận có phương pháp" cho các tác vụ phức tạp. 🧩
  • Yêu cầu chuỗi suy nghĩ rõ ràng: Nếu bạn muốn giải thích chi tiết, hãy yêu cầu trực tiếp, vì GPT-4.1 không mặc định hiển thị quá trình lập luận. 🔍
  • Hướng dẫn truy xuất thông tin: Khi làm việc với nhiều tài liệu, hướng dẫn mô hình xác định các nguồn liên quan trước khi trả lời. 📚

5. Quản Lý Ngữ Cảnh và Kiến Thức 🌐

  • Tận dụng cửa sổ ngữ cảnh lớn: GPT-4.1 có thể xử lý tới 1 triệu token, cho phép ngữ cảnh phong phú hơn và cuộc trò chuyện dài hơn. Tuy nhiên, hiệu suất có thể giảm nếu quá tải với quá nhiều truy xuất hoặc tác vụ lập luận. 📈
  • Kiểm soát việc sử dụng kiến thức: Chỉ định liệu mô hình nên chỉ sử dụng ngữ cảnh được cung cấp, kiến thức chung của nó, hoặc kết hợp cả hai. 🧩
  • Cân bằng ngữ cảnh và hướng dẫn: Để có kết quả tốt nhất, cấu trúc prompt với các phần dành cho ngữ cảnh, hướng dẫn và ví dụ. ⚖️

III. Thực Hành Tốt Nhất Cho Định Dạng và Cấu Trúc 📐

1. Định Dạng Phân Cách (Delimiters) 🏷️

Dưới đây là một số hướng dẫn chung để chọn các định dạng phân cách tốt nhất cho prompt của bạn:

  • Markdown: OpenAI khuyến nghị bắt đầu tại đây, sử dụng tiêu đề markdown cho các phần chính và phần phụ. Sử dụng dấu backtick hoặc khối backtick để bọc mã chính xác, và danh sách được đánh số hoặc dấu đầu dòng tiêu chuẩn khi cần.
  • XML: Các thẻ XML cũng hoạt động tốt, và GPT-4.1 đã cải thiện sự tuân thủ thông tin trong XML. XML thuận tiện để bọc chính xác một phần bao gồm bắt đầu và kết thúc, thêm metadata vào thẻ để bổ sung ngữ cảnh, và cho phép lồng ghép. Ví dụ về việc sử dụng thẻ XML để lồng các ví dụ trong một phần ví dụ, với đầu vào và đầu ra cho mỗi ví dụ:
    <examples>
    <example1 type="Abbreviate">
    <input>San Francisco</input>
    <o>- SF</o>
    </example1>
    </examples>
  • JSON có cấu trúc cao và được mô hình hiểu rõ, đặc biệt là trong ngữ cảnh lập trình. Tuy nhiên, nó có thể dài dòng hơn và yêu cầu escape ký tự có thể tạo thêm gánh nặng.

Hướng dẫn dành riêng cho việc thêm một số lượng lớn tài liệu hoặc tệp vào ngữ cảnh đầu vào:

  • XML hoạt động tốt trong kiểm tra ngữ cảnh dài của OpenAI. Ví dụ:
    <doc id=1 title="The Fox">The quick brown fox jumps over the lazy dog</doc>
  • Định dạng này, được đề xuất bởi Lee et al., cũng hoạt động tốt trong kiểm tra ngữ cảnh dài: Ví dụ:
    ID: 1 | TITLE: The Fox | CONTENT: The quick brown fox jumps over the lazy dog
  • JSON hoạt động đặc biệt kém. Ví dụ:
    [{"id": 1, "title": "The Fox", "content": "The quick brown fox jumped over the lazy dog"}]

2. Cấu Trúc Prompt Tham Khảo (Sample Prompt Structure) 📝

Dưới đây là một điểm khởi đầu tốt để cấu trúc prompt của bạn:

# Role and Objective

# Instructions

## Sub-categories for more detailed instructions

# Reasoning Steps

# Output Format

# Examples
## Example 1

# Context

# Final instructions and prompt to think step by step

Bạn có thể thêm hoặc bớt các phần cho phù hợp với nhu cầu của mình.

IV. Ví Dụ Cụ Thể 🌟

1. Ví Dụ: Prompt Dịch Vụ Khách Hàng (Customer Service) 👨‍💼

Dưới đây là một ví dụ về prompt tác nhân dịch vụ khách hàng cho một công ty viễn thông giả định:

You are a helpful customer service agent working for NewTelco, helping a user efficiently fulfill their request while adhering closely to provided guidelines.

# Instructions
- Always greet the user with "Hi, you've reached NewTelco, how can I help you?"
- Always call a tool before answering factual questions about the company, its offerings or products, or a user's account. Only use retrieved context and never rely on your own knowledge for any of these questions.
- However, if you don't have enough information to properly call the tool, ask the user for the information you need.
- Escalate to a human if the user requests.
- Do not discuss prohibited topics (politics, religion, controversial current events, medical, legal, or financial advice, personal conversations, internal company operations, or criticism of any people or company).
- Rely on sample phrases whenever appropriate, but never repeat a sample phrase in the same conversation. Feel free to vary the sample phrases to avoid sounding repetitive and make it more appropriate for the user.
- Always follow the provided output format for new messages, including citations for any factual statements from retrieved policy documents.
- If you're going to call a tool, always message the user with an appropriate message before and after calling the tool.
- Maintain a professional and concise tone in all responses, and use emojis between sentences.
- If you've resolved the user's request, ask if there's anything else you can help with

# Precise Response Steps (for each response)
1. If necessary, call tools to fulfill the user's desired action. Always message the user before and after calling a tool to keep them in the loop.
2. In your response to the user
a. Use active listening and echo back what you heard the user ask for.
b. Respond appropriately given the above guidelines.

# Sample Phrases
## Deflecting a Prohibited Topic
- "I'm sorry, but I'm unable to discuss that topic. Is there something else I can help you with?"
- "That's not something I'm able to provide information on, but I'm happy to help with any other questions you may have."

## Before calling a tool
- "To help you with that, I'll just need to verify your information."
- "Let me check that for you—one moment, please."
- "I'll retrieve the latest details for you now."

## After calling a tool
- "Okay, here's what I found: [response]"
- "So here's what I found: [response]"

# Output Format
- Always include your final response to the user.
- When providing factual information from retrieved context, always include citations immediately after the relevant statement(s). Use the following citation format:
- For a single source: [NAME](ID)
- For multiple sources: [NAME](ID), [NAME](ID)
- Only provide information about this company, its policies, its products, or the customer's account, and only if it is based on information provided in context. Do not answer questions outside this scope.

2. Ví Dụ: Prompt SWE-bench Verified 💻

Đây là một prompt mà OpenAI đã sử dụng để đạt điểm cao nhất trên SWE-bench Verified, với hướng dẫn chi tiết về quy trình làm việc và chiến lược giải quyết vấn đề:

You will be tasked to fix an issue from an open-source repository.

Your thinking should be thorough and so it's fine if it's very long. You can think step by step before and after each action you decide to take.

You MUST iterate and keep going until the problem is solved.

Your already have everything you need to solve this problem in the /testbed folder, even without internet connection. I want you to fully solve this autonomously before coming back to me.

Only terminate your turn when you are sure that the problem is solved. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn.

THE PROBLEM CAN DEFINITELY BE SOLVED WITHOUT THE INTERNET.

Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided.

You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.

# Workflow

## High-Level Problem Solving Strategy

1. Understand the problem deeply. Carefully read the issue and think critically about what is required.
2. Investigate the codebase. Explore relevant files, search for key functions, and gather context.
3. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps.
4. Implement the fix incrementally. Make small, testable code changes.
5. Debug as needed. Use debugging techniques to isolate and resolve issues.
6. Test frequently. Run tests after each change to verify correctness.
7. Iterate until the root cause is fixed and all tests pass.
8. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete.

Refer to the detailed sections below for more information on each step.

## 1. Deeply Understand the Problem
Carefully read the issue and think hard about a plan to solve it before coding.

## 2. Codebase Investigation
- Explore relevant files and directories.
- Search for key functions, classes, or variables related to the issue.
- Read and understand relevant code snippets.
- Identify the root cause of the problem.
- Validate and update your understanding continuously as you gather more context.

## 3. Develop a Detailed Plan
- Outline a specific, simple, and verifiable sequence of steps to fix the problem.
- Break down the fix into small, incremental changes.

## 4. Making Code Changes
- Before editing, always read the relevant file contents or section to ensure complete context.
- If a patch is not applied correctly, attempt to reapply it.
- Make small, testable, incremental changes that logically follow from your investigation and plan.

## 5. Debugging
- Make code changes only if you have high confidence they can solve the problem
- When debugging, try to determine the root cause rather than addressing symptoms
- Debug for as long as needed to identify the root cause and identify a fix
- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening
- To test hypotheses, you can also add test statements or functions
- Revisit your assumptions if unexpected behavior occurs.

## 6. Testing
- Run tests frequently using `!python3 run_tests.py` (or equivalent).
- After each change, verify correctness by running relevant tests.
- If tests fail, analyze failures and revise your patch.
- Write additional tests if needed to capture important behaviors or edge cases.
- Ensure all tests pass before finalizing.

## 7. Final Verification
- Confirm the root cause is fixed.
- Review your solution for logic correctness and robustness.
- Iterate until you are extremely confident the fix is complete and all tests pass.

## 8. Final Reflection and Additional Testing
- Reflect carefully on the original intent of the user and the problem statement.
- Think about potential edge cases or scenarios that may not be covered by existing tests.
- Write additional tests that would need to pass to fully validate the correctness of your solution.
- Run these new tests and ensure they all pass.
- Be aware that there are additional hidden tests that must also pass for the solution to be successful.
- Do not assume the task is complete just because the visible tests pass; continue refining until you are confident the fix is robust and comprehensive.