openai-cookbook/examples/gpt4-1_prompting_guide.ipynb
2025-04-14 11:51:16 -05:00

1149 lines
60 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# GPT-4.1 Prompting Guide\n",
"\n",
"The GPT-4.1 family of models represents a significant step forward from GPT-4o in capabilities across coding, instruction following, and long context. In this prompting guide, we collate a series of important prompting tips derived from extensive internal testing to help developers fully leverage the improved abilities of this new model family. \n",
"\n",
"Many typical best practices still apply to GPT-4.1, such as providing context examples, making instructions as specific and clear as possible, and inducing planning via prompting to maximize model intelligence. However, we expect that getting the most out of this model will require some prompt migration. GPT-4.1 is trained to follow instructions more closely and more literally than its predecessors, which tended to more liberally infer intent from user and system prompts. This also means, however, that GPT-4.1 is highly steerable and responsive to well-specified prompts - if model behavior is different from what you expect, a single sentence firmly and unequivocally clarifying your desired behavior is almost always sufficient to steer the model on course.\n",
"\n",
"Please read on for prompt examples you can use as a reference, and remember that while this guidance is widely applicable, no advice is one-size-fits-all. AI engineering is inherently an empirical discipline, and large language models inherently nondeterministic; in addition to following this guide, we advise building informative evals and iterating often to ensure your prompt engineering changes are yielding benefits for your use case."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1. Agentic Workflows\n",
"\n",
"GPT-4.1 is a great place to build agentic workflows. In model training we emphasized providing a diverse range of agentic problem-solving trajectories, and our agentic harness for the model achieves state-of-the-art performance for non-reasoning models on SWE-bench Verified, solving 55% of problems. \n",
"\n",
"\n",
"## System Prompt Reminders\n",
"\n",
"In order to fully utilize the agentic capabilities of GPT-4.1, we recommend including three key types of reminders in all agent prompts. The following prompts are optimized specifically for the agentic coding workflow, but can be easily modified for general agentic use cases.\n",
"\n",
"1. Persistence: this ensures the model understands it is entering a multi-message turn, and prevents it from prematurely yielding control back to the user. Our example is the following:\n",
"\n",
"```\n",
"You are an agent - please keep going until the users 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.\n",
"```\n",
"\n",
"2. Tool-calling: this encourages the model to make full use of its tools, and reduces its likelihood of hallucinating or guessing an answer. Our example is the following:\n",
"\n",
"```\n",
"If you are not sure about file content or codebase structure pertaining to the users request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.\n",
"```\n",
"\n",
"3. Planning \\[optional\\]: if desired, this ensures the model explicitly plans and reflects upon each tool call in text, instead of completing the task by chaining together a series of only tool calls. Our example is the following:\n",
"\n",
"```\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.\n",
"```\n",
"\n",
"GPT-4.1 is trained to respond very closely to both user instructions and system prompts in the agentic setting. The model adhered closely to these three simple instructions and increased our internal SWE-bench Verified score by close to 20% \\- so we highly encourage starting any agent prompt with clear reminders covering the three categories listed above. As a whole, we find that these three instructions transform the model from a chatbot-like state into a much more “eager” agent, driving the interaction forward autonomously and independently. \n",
"\n",
"## Tool Calls\n",
"\n",
"Compared to previous models, GPT-4.1 has undergone more training on effectively utilizing tools passed as arguments in an OpenAI API request. We encourage developers to exclusively use the tools field to pass tools, rather than manually injecting tool descriptions into your prompt and writing a separate parser for tool calls, as some have reported doing in the past. This is the best way to minimize errors and ensure the model remains in distribution during tool-calling trajectories \\- in our own experiments, we observed a 2% increase in SWE-bench Verified pass rate when using API-parsed tool descriptions versus manually injecting the schemas into the system prompt.\n",
"\n",
"Developers should name tools clearly to indicate their purpose and add a clear, detailed description in the \"description\" field of the tool. Similarly, for each tool param, lean on good naming and descriptions to ensure appropriate usage. If your tool is particularly complicated and you'd like to provide examples of tool usage, we recommend that you create an `# Examples` section in your system prompt and place the examples there, rather than adding them into the \"description' field, which should remain thorough but relatively concise. Providing examples can be helpful to indicate when to use tools, whether to include user text alongside tool calls, and what parameters are appropriate for different inputs. Remember that you can use “Generate Anything” in the [Prompt Playground](https://platform.openai.com/playground) to get a good starting point for your new tool definitions.\n",
"\n",
"## Prompting-Induced Planning & Chain-of-Thought\n",
"\n",
"As mentioned already, developers can optionally prompt agents built with GPT-4.1 to plan and reflect between tool calls, instead of silently calling tools in an unbroken sequence. GPT-4.1 is not a reasoning model \\- meaning that it does not produce an internal chain of thought before answering \\- but in the prompt, a developer can induce the model to produce an explicit, step-by-step plan by using any variant of the Planning prompt component shown above. This can be thought of as the model “thinking out loud.” In our experimentation with the SWE-bench Verified agentic task, inducing explicit planning increased the pass rate by 4%. \n",
"\n",
"## Sample Prompt: SWE-bench Verified\n",
"\n",
"Below, we share the agentic prompt that we used to achieve our highest score on SWE-bench Verified, which features detailed instructions about workflow and problem-solving strategy. This general pattern can be used for any agentic task."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"SYS_PROMPT_SWEBENCH = \"\"\"\n",
"You will be tasked to fix an issue from an open-source repository.\n",
"\n",
"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.\n",
"\n",
"You MUST iterate and keep going until the problem is solved.\n",
"\n",
"You 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.\n",
"\n",
"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.\n",
"\n",
"THE PROBLEM CAN DEFINITELY BE SOLVED WITHOUT THE INTERNET.\n",
"\n",
"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.\n",
"\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.\n",
"\n",
"# Workflow\n",
"\n",
"## High-Level Problem Solving Strategy\n",
"\n",
"1. Understand the problem deeply. Carefully read the issue and think critically about what is required.\n",
"2. Investigate the codebase. Explore relevant files, search for key functions, and gather context.\n",
"3. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps.\n",
"4. Implement the fix incrementally. Make small, testable code changes.\n",
"5. Debug as needed. Use debugging techniques to isolate and resolve issues.\n",
"6. Test frequently. Run tests after each change to verify correctness.\n",
"7. Iterate until the root cause is fixed and all tests pass.\n",
"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.\n",
"\n",
"Refer to the detailed sections below for more information on each step.\n",
"\n",
"## 1. Deeply Understand the Problem\n",
"Carefully read the issue and think hard about a plan to solve it before coding.\n",
"\n",
"## 2. Codebase Investigation\n",
"- Explore relevant files and directories.\n",
"- Search for key functions, classes, or variables related to the issue.\n",
"- Read and understand relevant code snippets.\n",
"- Identify the root cause of the problem.\n",
"- Validate and update your understanding continuously as you gather more context.\n",
"\n",
"## 3. Develop a Detailed Plan\n",
"- Outline a specific, simple, and verifiable sequence of steps to fix the problem.\n",
"- Break down the fix into small, incremental changes.\n",
"\n",
"## 4. Making Code Changes\n",
"- Before editing, always read the relevant file contents or section to ensure complete context.\n",
"- If a patch is not applied correctly, attempt to reapply it.\n",
"- Make small, testable, incremental changes that logically follow from your investigation and plan.\n",
"\n",
"## 5. Debugging\n",
"- Make code changes only if you have high confidence they can solve the problem\n",
"- When debugging, try to determine the root cause rather than addressing symptoms\n",
"- Debug for as long as needed to identify the root cause and identify a fix\n",
"- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening\n",
"- To test hypotheses, you can also add test statements or functions\n",
"- Revisit your assumptions if unexpected behavior occurs.\n",
"\n",
"## 6. Testing\n",
"- Run tests frequently using `!python3 run_tests.py` (or equivalent).\n",
"- After each change, verify correctness by running relevant tests.\n",
"- If tests fail, analyze failures and revise your patch.\n",
"- Write additional tests if needed to capture important behaviors or edge cases.\n",
"- Ensure all tests pass before finalizing.\n",
"\n",
"## 7. Final Verification\n",
"- Confirm the root cause is fixed.\n",
"- Review your solution for logic correctness and robustness.\n",
"- Iterate until you are extremely confident the fix is complete and all tests pass.\n",
"\n",
"## 8. Final Reflection and Additional Testing\n",
"- Reflect carefully on the original intent of the user and the problem statement.\n",
"- Think about potential edge cases or scenarios that may not be covered by existing tests.\n",
"- Write additional tests that would need to pass to fully validate the correctness of your solution.\n",
"- Run these new tests and ensure they all pass.\n",
"- Be aware that there are additional hidden tests that must also pass for the solution to be successful.\n",
"- 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.\n",
"\"\"\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 2. Long context\n",
"\n",
"GPT-4.1 has a performant 1M token input context window, and is useful for a variety of long context tasks, including structured document parsing, re-ranking, selecting relevant information while ignoring irrelevant context, and performing multi-hop reasoning using context.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Optimal Context Size\n",
"\n",
"We observe very good performance on needle-in-a-haystack evaluations up to our full 1M token context, and weve observed very strong performance at complex tasks with a mix of both relevant and irrelevant code and other documents. However, long context performance can degrade as more items are required to be retrieved, or perform complex reasoning that requires knowledge of the state of the entire context (like performing a graph search, for example).\n",
"\n",
"## Tuning Context Reliance\n",
"\n",
"Consider the mix of external vs. internal world knowledge that might be required to answer your question. Sometimes its important for the model to use some of its own knowledge to connect concepts or make logical jumps, while in others its desirable to only use provided context\n",
"\n",
"```\n",
"# Instructions\n",
"// for internal knowledge\n",
"- 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.\n",
"// For internal and external knowledge\n",
"- 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.\n",
"```\n",
"\n",
"## Prompt Organization\n",
"\n",
"Especially in long context usage, placement of instructions and context can impact performance. If you have long context in your prompt, ideally place your instructions at both the beginning and end of the provided context, as we found this to perform better than only above or below. If youd prefer to only have your instructions once, then above the provided context works better than below."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 3. Chain of Thought\n",
"\n",
"As mentioned above, GPT-4.1 is not a reasoning model, but prompting the model to think step by step (called “chain of thought”) can be an effective way for a model to break down problems into more manageable pieces, solve them, and improve overall output quality, with the tradeoff of higher cost and latency associated with using more output tokens. The model has been trained to perform well at agentic reasoning about and real-world problem solving, so it shouldnt require much prompting to perform well.\n",
"\n",
"We recommend starting with this basic chain-of-thought instruction at the end of your prompt:\n",
"\n",
"```\n",
"...\n",
"\n",
"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.\n",
"```\n",
"\n",
"From there, you should improve your chain-of-thought (CoT) prompt by auditing failures in your particular examples and evals, and addressing systematic planning and reasoning errors with more explicit instructions. In the unconstrained CoT prompt, there may be variance in the strategies it tries, and if you observe an approach that works well, you can codify that strategy in your prompt. Generally speaking, errors tend to occur from misunderstanding user intent, insufficient context gathering or analysis, or insufficient or incorrect step by step thinking, so watch out for these and try to address them with more opinionated instructions.\n",
"\n",
"Here is an example prompt instructing the model to focus more methodically on analyzing user intent and considering relevant context before proceeding to answer.\n",
"\n",
"```\n",
"# Reasoning Strategy\n",
"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.\n",
"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:\n",
"\ta. Analysis: An analysis of how it may or may not be relevant to answering the query.\n",
"\tb. Relevance rating: [high, medium, low, none]\n",
"3. Synthesis: summarize which documents are most relevant and why, including all documents with a relevance rating of medium or higher.\n",
"\n",
"# User Question\n",
"{user_question}\n",
"\n",
"# External Context\n",
"{external_context}\n",
"\n",
"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.\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 4. Instruction Following\n",
"\n",
"GPT-4.1 exhibits outstanding instruction-following performance, which developers can leverage to precisely shape and control the outputs for their particular use cases. Developers often extensively prompt for agentic reasoning steps, response tone and voice, tool calling information, output formatting, topics to avoid, and more. However, since the model follows instructions more literally, developers may need to include explicit specification around what to do or not to do. Furthermore, existing prompts optimized for other models may not immediately work with this model, because existing instructions are followed more closely and implicit rules are no longer being as strongly inferred."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Recommended Workflow\n",
"\n",
"Here is our recommended workflow for developing and debugging instructions in prompts:\n",
"\n",
"1. Start with an overall “Response Rules” or “Instructions” section with high-level guidance and bullet points. \n",
"2. If youd like to change a more specific behavior, add a section to specify more details for that category, like `# Sample Phrases`. \n",
"3. If there are specific steps youd like the model to follow in its workflow, add an ordered list and instruct the model to follow these steps.\n",
"4. If behavior still isnt working as expected: \n",
" 1. Check for conflicting, underspecified, or wrong instructions and examples. If there are conflicting instructions, GPT-4.1 tends to follow the one closer to the end of the prompt.\n",
" 2. Add examples that demonstrate desired behavior; ensure that any important behavior demonstrated in your examples are also cited in your rules.\n",
" 3. Its generally not necessary to use all-caps or other incentives like bribes or tips, but developers can experiment with this for extra emphasis if so desired.\n",
"\n",
"*Note that using your preferred AI-powered IDE can be very helpful for iterating on prompts, including checking for consistency or conflicts, adding examples, or making cohesive updates like adding an instruction and updating instructions to demonstrate that instruction.*\n",
"\n",
"## Common Failure Modes\n",
"\n",
"These failure modes are not unique to GPT-4.1, but we share them here for general awareness and ease of debugging.\n",
"\n",
"* Instructing a model to always follow a specific behavior can occasionally induce adverse effects. For instance, if told “you must call a tool before responding to the user,” models may hallucinate tool inputs or call the tool with null values if they do not have enough information. Adding “if you dont have enough information to call the tool, ask the user for the information you need” should mitigate this.\n",
"* When provided sample phrases, models can use those quotes verbatim and start to sound repetitive to users. Ensure you instruct the model to vary them as necessary.\n",
"* Without specific instructions, some models can be eager to provide additional prose to explain their decisions, or output more formatting in responses than may be desired. Provide instructions and potentially examples to help mitigate."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example Prompt: Customer Service\n",
"\n",
"This demonstrates best practices for a fictional customer service agent. Observe the diversity of rules, the specificity, the use of additional sections for greater detail, and an example to demonstrate precise behavior that incorporates all prior rules.\n",
"\n",
"Try running the following notebook cell - you should see both a user message and tool call, and the user message should start with a greeting, then echo back their answer, then mention they're about to call a tool. Try changing the instructions to shape the model behavior, or trying other user messages, to test instruction following performance."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'id': 'msg_67fc8e208ce88191a8511546572ef8a502938f4dcc4628bb',\n",
" 'content': [{'annotations': [],\n",
" 'text': \"Hi, you've reached NewTelco, how can I help you? 😊💬\\n\\nYoud like to know why your last bill was higher than expected. To help you with that, I'll just need to verify your account information. Could you please provide your phone number associated with your account? 📱\",\n",
" 'type': 'output_text'}],\n",
" 'role': 'assistant',\n",
" 'status': 'completed',\n",
" 'type': 'message'}]"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from openai import OpenAI\n",
"import os\n",
"\n",
"client = OpenAI(\n",
" api_key=os.environ.get(\n",
" \"OPENAI_API_KEY\", \"<your OpenAI API key if not set as env var>\"\n",
" )\n",
")\n",
"\n",
"SYS_PROMPT_CUSTOMER_SERVICE = \"\"\"You are a helpful customer service agent working for NewTelco, helping a user efficiently fulfill their request while adhering closely to provided guidelines.\n",
"\n",
"# Instructions\n",
"- Always greet the user with \"Hi, you've reached NewTelco, how can I help you?\"\n",
"- 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.\n",
" - However, if you don't have enough information to properly call the tool, ask the user for the information you need.\n",
"- Escalate to a human if the user requests.\n",
"- 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).\n",
"- 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.\n",
"- Always follow the provided output format for new messages, including citations for any factual statements from retrieved policy documents.\n",
"- If you're going to call a tool, always message the user with an appropriate message before and after calling the tool.\n",
"- Maintain a professional and concise tone in all responses, and use emojis between sentences.\n",
"- If you've resolved the user's request, ask if there's anything else you can help with\n",
"\n",
"# Precise Response Steps (for each response)\n",
"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.\n",
"2. In your response to the user\n",
" a. Use active listening and echo back what you heard the user ask for.\n",
" b. Respond appropriately given the above guidelines.\n",
"\n",
"# Sample Phrases\n",
"## Deflecting a Prohibited Topic\n",
"- \"I'm sorry, but I'm unable to discuss that topic. Is there something else I can help you with?\"\n",
"- \"That's not something I'm able to provide information on, but I'm happy to help with any other questions you may have.\"\n",
"\n",
"## Before calling a tool\n",
"- \"To help you with that, I'll just need to verify your information.\"\n",
"- \"Let me check that for you—one moment, please.\"\n",
"- \"I'll retrieve the latest details for you now.\"\n",
"\n",
"## After calling a tool\n",
"- \"Okay, here's what I found: [response]\"\n",
"- \"So here's what I found: [response]\"\n",
"\n",
"# Output Format\n",
"- Always include your final response to the user.\n",
"- When providing factual information from retrieved context, always include citations immediately after the relevant statement(s). Use the following citation format:\n",
" - For a single source: [NAME](ID)\n",
" - For multiple sources: [NAME](ID), [NAME](ID)\n",
"- 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.\n",
"\n",
"# Example\n",
"## User\n",
"Can you tell me about your family plan options?\n",
"\n",
"## Assistant\n",
"```\n",
"{\n",
" \"role\": \"assistant\",\n",
" \"content\": \"Hi, you've reached NewTelco, how can I help you? 😊🎉\\n\\nYou'd like to know about our family plan options. 🤝 Let me check that for you—one moment, please. 🚀\",\n",
" \"tool_calls\": [\n",
" {\n",
" \"id\": \"call-1\",\n",
" \"type\": \"function\",\n",
" \"function\": {\n",
" \"name\": \"lookup_policy_document\",\n",
" \"arguments\": \"{\\\"topic\\\": \\\"family plan options\\\"}\"\n",
" }\n",
" }\n",
" ]\n",
"}\n",
"```\n",
"\n",
"// After tool call, the assistant would follow up with:\n",
"\n",
"{\n",
" \"role\": \"assistant\",\n",
" \"content\": \"Okay, here's what I found: 🎉 Our family plan allows up to 5 lines with shared data and a 10% discount for each additional line [Family Plan Policy](ID-010). 📱 Is there anything else I can help you with today? 😊\"\n",
"}\n",
"```\n",
"\"\"\"\n",
"\n",
"get_policy_doc = {\n",
" \"type\": \"function\",\n",
" \"name\": \"lookup_policy_document\",\n",
" \"description\": \"Tool to look up internal documents and policies by topic or keyword.\",\n",
" \"parameters\": {\n",
" \"strict\": True,\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"topic\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The topic or keyword to search for in company policies or documents.\",\n",
" },\n",
" },\n",
" \"required\": [\"topic\"],\n",
" \"additionalProperties\": False,\n",
" },\n",
"}\n",
"\n",
"get_user_acct = {\n",
" \"type\": \"function\",\n",
" \"name\": \"get_user_account_info\",\n",
" \"description\": \"Tool to get user account information\",\n",
" \"parameters\": {\n",
" \"strict\": True,\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"phone_number\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"Formatted as '(xxx) xxx-xxxx'\",\n",
" },\n",
" },\n",
" \"required\": [\"phone_number\"],\n",
" \"additionalProperties\": False,\n",
" },\n",
"}\n",
"\n",
"response = client.responses.create(\n",
" instructions=SYS_PROMPT_CUSTOMER_SERVICE,\n",
" model=\"gpt-4.1-2025-04-14\",\n",
" tools=[get_policy_doc, get_user_acct],\n",
" input=\"Why was my last bill so high?\"\n",
" # input=\"How much will it cost for international service? I'm traveling to France.\",\n",
")\n",
"\n",
"response.to_dict()[\"output\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 5. General Advice\n",
"\n",
"## Prompt Structure\n",
"\n",
"For reference, here is a good starting point for structuring your prompts.\n",
"\n",
"```\n",
"# Role and Objective\n",
"\n",
"# Instructions\n",
"\n",
"## Sub-categories for more detailed instructions\n",
"\n",
"# Reasoning Steps\n",
"\n",
"# Output Format\n",
"\n",
"# Examples\n",
"## Example 1\n",
"\n",
"# Context\n",
"\n",
"# Final instructions and prompt to think step by step\n",
"```\n",
"\n",
"Add or remove sections to suit your needs, and experiment to determine whats optimal for your usage.\n",
"\n",
"## Delimiters\n",
"\n",
"Here are some general guidelines for selecting the best delimiters for your prompt. Please refer to the Long Context section for special considerations for that context type.\n",
"\n",
"1. Markdown: We recommend starting here, and using markdown titles for major sections and subsections (including deeper hierarchy, to H4+). Use inline backticks or backtick blocks to precisely wrap code, and standard numbered or bulleted lists as needed. \n",
"2. XML: These also perform well, and we have improved adherence to information in XML with this model. XML is convenient to precisely wrap a section including start and end, add metadata to the tags for additional context, and enable nesting. Here is an example of using XML tags to nest examples in an example section, with inputs and outputs for each:\n",
"\n",
"```\n",
"<examples>\n",
"<example1 type=\"Abbreviate\">\n",
"<input>San Francisco</input>\n",
"<output>- SF</output>\n",
"</example1>\n",
"</examples>\n",
"```\n",
"\n",
"3. JSON is highly structured and well understood by the model particularly in coding contexts. However it can be more verbose, and require character escaping that can add overhead.\n",
"\n",
"Guidance specifically for adding a large number of documents or files to context:\n",
"\n",
"* XML performed well in our long context testing. \n",
" * Example: `<doc id=1 title=”The Fox”>The quick brown fox jumps over the lazy dog</doc>` \n",
"* This format, proposed by Lee et al. ([ref](https://arxiv.org/pdf/2406.13121)), also performed well in our long context testing. \n",
" * Example: `ID: 1 | TITLE: The Fox | CONTENT: The quick brown fox jumps over the lazy dog` \n",
"* JSON performed particularly poorly. \n",
" * Example: `[{“id”: 1, “title”: “The Fox”, “content”: “The quick brown fox jumped over the lazy dog”}]`\n",
"\n",
"The model is trained to robustly understand structure in a variety of formats. Generally, use your judgement and think about what will provide clear information and “stand out” to the model. For example, if youre retrieving documents that contain lots of XML, an XML-based delimiter will likely be less effective. \n",
"\n",
"## Caveats\n",
"\n",
"* In some isolated cases we have observed the model being resistant to producing very long, repetitive outputs, for example, analyzing hundreds of items one by one. If this is necessary for your use case, instruct the model strongly to output this information in full, and consider breaking down the problem or using a more concise approach. \n",
"* We have seen some rare instances of parallel tool calls being incorrect. We advise testing this, and considering setting the [parallel\\_tool\\_calls](https://platform.openai.com/docs/api-reference/responses/create#responses-create-parallel_tool_calls) param to false if youre seeing issues."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Appendix: Generating and Applying File Diffs\n",
"\n",
"Developers have provided us feedback that accurate and well-formed diff generation is a critical capability to power coding-related tasks. To this end, the GPT-4.1 family features substantially improved diff capabilities relative to previous GPT models. Moreover, while GPT-4.1 has strong performance generating diffs of any format given clear instructions and examples, we open-source here one recommended diff format, on which the model has been extensively trained. We hope that in particular for developers just starting out, that this will take much of the guesswork out of creating diffs yourself. \n",
"\n",
"## Apply Patch\n",
"\n",
"See the example below for a prompt that applies our recommended tool call correctly."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"APPLY_PATCH_TOOL_DESC = \"\"\"This is a custom utility that makes it more convenient to add, remove, move, or edit code files. `apply_patch` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the `apply_patch` command, you should pass a message of the following structure as \"input\":\n",
"\n",
"%%bash\n",
"apply_patch <<\"EOF\"\n",
"*** Begin Patch\n",
"[YOUR_PATCH]\n",
"*** End Patch\n",
"EOF\n",
"\n",
"Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.\n",
"\n",
"*** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.\n",
"For each snippet of code that needs to be changed, repeat the following:\n",
"[context_before] -> See below for further instructions on context.\n",
"- [old_code] -> Precede the old code with a minus sign.\n",
"+ [new_code] -> Precede the new, replacement code with a plus sign.\n",
"[context_after] -> See below for further instructions on context.\n",
"\n",
"For instructions on [context_before] and [context_after]:\n",
"- By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first changes [context_after] lines in the second changes [context_before] lines.\n",
"- If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:\n",
"@@ class BaseClass\n",
"[3 lines of pre-context]\n",
"- [old_code]\n",
"+ [new_code]\n",
"[3 lines of post-context]\n",
"\n",
"- If a code block is repeated so many times in a class or function such that even a single @@ statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple `@@` statements to jump to the right context. For instance:\n",
"\n",
"@@ class BaseClass\n",
"@@ \tdef method():\n",
"[3 lines of pre-context]\n",
"- [old_code]\n",
"+ [new_code]\n",
"[3 lines of post-context]\n",
"\n",
"Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as \"input\" to this function, in order to apply a patch, is shown below.\n",
"\n",
"%%bash\n",
"apply_patch <<\"EOF\"\n",
"*** Begin Patch\n",
"*** Update File: pygorithm/searching/binary_search.py\n",
"@@ class BaseClass\n",
"@@ def search():\n",
"- pass\n",
"+ raise NotImplementedError()\n",
"\n",
"@@ class Subclass\n",
"@@ def search():\n",
"- pass\n",
"+ raise NotImplementedError()\n",
"\n",
"*** End Patch\n",
"EOF\n",
"\"\"\"\n",
"\n",
"APPLY_PATCH_TOOL = {\n",
" \"name\": \"apply_patch\",\n",
" \"description\": APPLY_PATCH_TOOL_DESC,\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"input\": {\n",
" \"type\": \"string\",\n",
" \"description\": \" The apply_patch command that you wish to execute.\",\n",
" }\n",
" },\n",
" \"required\": [\"input\"],\n",
" },\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Reference Implementation: apply\\_patch.py\n",
"\n",
"Heres a reference implementation of the apply\\_patch tool that we used as part of model training. Youll need to make this an executable and available as \\`apply\\_patch\\` from the shell where the model will execute commands:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#!/usr/bin/env python3\n",
"import os\n",
"from dataclasses import dataclass, field\n",
"from enum import Enum\n",
"from typing import Callable, Dict, List, NoReturn, Optional, Tuple, Union\n",
"\n",
"\n",
"class ActionType(str, Enum):\n",
" ADD = \"add\"\n",
" DELETE = \"delete\"\n",
" UPDATE = \"update\"\n",
"\n",
"\n",
"@dataclass\n",
"class FileChange:\n",
" type: ActionType\n",
" old_content: Optional[str] = None\n",
" new_content: Optional[str] = None\n",
" move_path: Optional[str] = None\n",
"\n",
"\n",
"@dataclass\n",
"class Commit:\n",
" changes: Dict[str, FileChange] = field(default_factory=dict)\n",
"\n",
"\n",
"def assemble_changes(\n",
" orig: Dict[str, Optional[str]],\n",
" updated_files: Dict[str, Optional[str]],\n",
") -> Commit:\n",
" commit = Commit()\n",
" for path, new_content in updated_files.items():\n",
" old_content = orig.get(path)\n",
" if old_content == new_content:\n",
" continue\n",
" if old_content is not None and new_content is not None:\n",
" commit.changes[path] = FileChange(\n",
" type=ActionType.UPDATE,\n",
" old_content=old_content,\n",
" new_content=new_content,\n",
" )\n",
" elif new_content is not None:\n",
" commit.changes[path] = FileChange(\n",
" type=ActionType.ADD,\n",
" new_content=new_content,\n",
" )\n",
" elif old_content is not None:\n",
" commit.changes[path] = FileChange(\n",
" type=ActionType.DELETE,\n",
" old_content=old_content,\n",
" )\n",
" else:\n",
" assert False\n",
" return commit\n",
"\n",
"\n",
"@dataclass\n",
"class Chunk:\n",
" orig_index: int = -1 # line index of the first line in the original file\n",
" del_lines: List[str] = field(default_factory=list)\n",
" ins_lines: List[str] = field(default_factory=list)\n",
"\n",
"\n",
"@dataclass\n",
"class PatchAction:\n",
" type: ActionType\n",
" new_file: Optional[str] = None\n",
" chunks: List[Chunk] = field(default_factory=list)\n",
" move_path: Optional[str] = None\n",
"\n",
"\n",
"@dataclass\n",
"class Patch:\n",
" actions: Dict[str, PatchAction] = field(default_factory=dict)\n",
"\n",
"\n",
"@dataclass\n",
"class Parser:\n",
" current_files: Dict[str, str] = field(default_factory=dict)\n",
" lines: List[str] = field(default_factory=list)\n",
" index: int = 0\n",
" patch: Patch = field(default_factory=Patch)\n",
" fuzz: int = 0\n",
"\n",
" def is_done(self, prefixes: Optional[Tuple[str, ...]] = None) -> bool:\n",
" if self.index >= len(self.lines):\n",
" return True\n",
" if prefixes and self.lines[self.index].startswith(prefixes):\n",
" return True\n",
" return False\n",
"\n",
" def startswith(self, prefix: Union[str, Tuple[str, ...]]) -> bool:\n",
" assert self.index < len(self.lines), f\"Index: {self.index} >= {len(self.lines)}\"\n",
" if self.lines[self.index].startswith(prefix):\n",
" return True\n",
" return False\n",
"\n",
" def read_str(self, prefix: str = \"\", return_everything: bool = False) -> str:\n",
" assert self.index < len(self.lines), f\"Index: {self.index} >= {len(self.lines)}\"\n",
" if self.lines[self.index].startswith(prefix):\n",
" if return_everything:\n",
" text = self.lines[self.index]\n",
" else:\n",
" text = self.lines[self.index][len(prefix) :]\n",
" self.index += 1\n",
" return text\n",
" return \"\"\n",
"\n",
" def parse(self) -> NoReturn:\n",
" while not self.is_done((\"*** End Patch\",)):\n",
" path = self.read_str(\"*** Update File: \")\n",
" if path:\n",
" if path in self.patch.actions:\n",
" raise DiffError(f\"Update File Error: Duplicate Path: {path}\")\n",
" move_to = self.read_str(\"*** Move to: \")\n",
" if path not in self.current_files:\n",
" raise DiffError(f\"Update File Error: Missing File: {path}\")\n",
" text = self.current_files[path]\n",
" action = self.parse_update_file(text)\n",
" action.move_path = move_to\n",
" self.patch.actions[path] = action\n",
" continue\n",
" path = self.read_str(\"*** Delete File: \")\n",
" if path:\n",
" if path in self.patch.actions:\n",
" raise DiffError(f\"Delete File Error: Duplicate Path: {path}\")\n",
" if path not in self.current_files:\n",
" raise DiffError(f\"Delete File Error: Missing File: {path}\")\n",
" self.patch.actions[path] = PatchAction(\n",
" type=ActionType.DELETE,\n",
" )\n",
" continue\n",
" path = self.read_str(\"*** Add File: \")\n",
" if path:\n",
" if path in self.patch.actions:\n",
" raise DiffError(f\"Add File Error: Duplicate Path: {path}\")\n",
" if path in self.current_files:\n",
" raise DiffError(f\"Add File Error: File already exists: {path}\")\n",
" self.patch.actions[path] = self.parse_add_file()\n",
" continue\n",
" raise DiffError(f\"Unknown Line: {self.lines[self.index]}\")\n",
" if not self.startswith(\"*** End Patch\"):\n",
" raise DiffError(\"Missing End Patch\")\n",
" self.index += 1\n",
"\n",
" def parse_update_file(self, text: str) -> PatchAction:\n",
" action = PatchAction(\n",
" type=ActionType.UPDATE,\n",
" )\n",
" lines = text.split(\"\\n\")\n",
" index = 0\n",
" while not self.is_done(\n",
" (\n",
" \"*** End Patch\",\n",
" \"*** Update File:\",\n",
" \"*** Delete File:\",\n",
" \"*** Add File:\",\n",
" \"*** End of File\",\n",
" )\n",
" ):\n",
" def_str = self.read_str(\"@@ \")\n",
" section_str = \"\"\n",
" if not def_str:\n",
" if self.lines[self.index] == \"@@\":\n",
" section_str = self.lines[self.index]\n",
" self.index += 1\n",
" if not (def_str or section_str or index == 0):\n",
" raise DiffError(f\"Invalid Line:\\n{self.lines[self.index]}\")\n",
" if def_str.strip():\n",
" found = False\n",
" if not [s for s in lines[:index] if s == def_str]:\n",
" # def str is a skip ahead operator\n",
" for i, s in enumerate(lines[index:], index):\n",
" if s == def_str:\n",
" index = i + 1\n",
" found = True\n",
" break\n",
" if not found and not [s for s in lines[:index] if s.strip() == def_str.strip()]:\n",
" # def str is a skip ahead operator\n",
" for i, s in enumerate(lines[index:], index):\n",
" if s.strip() == def_str.strip():\n",
" index = i + 1\n",
" self.fuzz += 1\n",
" found = True\n",
" break\n",
" next_chunk_context, chunks, end_patch_index, eof = peek_next_section(\n",
" self.lines, self.index\n",
" )\n",
" next_chunk_text = \"\\n\".join(next_chunk_context)\n",
" new_index, fuzz = find_context(lines, next_chunk_context, index, eof)\n",
" if new_index == -1:\n",
" if eof:\n",
" raise DiffError(f\"Invalid EOF Context {index}:\\n{next_chunk_text}\")\n",
" else:\n",
" raise DiffError(f\"Invalid Context {index}:\\n{next_chunk_text}\")\n",
" self.fuzz += fuzz\n",
" for ch in chunks:\n",
" ch.orig_index += new_index\n",
" action.chunks.append(ch)\n",
" index = new_index + len(next_chunk_context)\n",
" self.index = end_patch_index\n",
" continue\n",
" return action\n",
"\n",
" def parse_add_file(self) -> PatchAction:\n",
" lines = []\n",
" while not self.is_done(\n",
" (\"*** End Patch\", \"*** Update File:\", \"*** Delete File:\", \"*** Add File:\")\n",
" ):\n",
" s = self.read_str()\n",
" if not s.startswith(\"+\"):\n",
" raise DiffError(f\"Invalid Add File Line: {s}\")\n",
" s = s[1:]\n",
" lines.append(s)\n",
" return PatchAction(\n",
" type=ActionType.ADD,\n",
" new_file=\"\\n\".join(lines),\n",
" )\n",
"\n",
"\n",
"def find_context_core(lines: List[str], context: List[str], start: int) -> Tuple[int, int]:\n",
" if not context:\n",
" return start, 0\n",
"\n",
" # Prefer identical\n",
" for i in range(start, len(lines)):\n",
" if lines[i : i + len(context)] == context:\n",
" return i, 0\n",
" # RStrip is ok\n",
" for i in range(start, len(lines)):\n",
" if [s.rstrip() for s in lines[i : i + len(context)]] == [s.rstrip() for s in context]:\n",
" return i, 1\n",
" # Fine, Strip is ok too.\n",
" for i in range(start, len(lines)):\n",
" if [s.strip() for s in lines[i : i + len(context)]] == [s.strip() for s in context]:\n",
" return i, 100\n",
" return -1, 0\n",
"\n",
"\n",
"def find_context(lines: List[str], context: List[str], start: int, eof: bool) -> Tuple[int, int]:\n",
" if eof:\n",
" new_index, fuzz = find_context_core(lines, context, len(lines) - len(context))\n",
" if new_index != -1:\n",
" return new_index, fuzz\n",
" new_index, fuzz = find_context_core(lines, context, start)\n",
" return new_index, fuzz + 10000\n",
" return find_context_core(lines, context, start)\n",
"\n",
"\n",
"def peek_next_section(lines: List[str], index: int) -> Tuple[List[str], List[Chunk], int, bool]:\n",
" old: List[str] = []\n",
" del_lines: List[str] = []\n",
" ins_lines: List[str] = []\n",
" chunks: List[Chunk] = []\n",
" mode = \"keep\"\n",
" orig_index = index\n",
" while index < len(lines):\n",
" s = lines[index]\n",
" if s.startswith(\n",
" (\n",
" \"@@\",\n",
" \"*** End Patch\",\n",
" \"*** Update File:\",\n",
" \"*** Delete File:\",\n",
" \"*** Add File:\",\n",
" \"*** End of File\",\n",
" )\n",
" ):\n",
" break\n",
" if s == \"***\":\n",
" break\n",
" elif s.startswith(\"***\"):\n",
" raise DiffError(f\"Invalid Line: {s}\")\n",
" index += 1\n",
" last_mode = mode\n",
" if s == \"\":\n",
" s = \" \"\n",
" if s[0] == \"+\":\n",
" mode = \"add\"\n",
" elif s[0] == \"-\":\n",
" mode = \"delete\"\n",
" elif s[0] == \" \":\n",
" mode = \"keep\"\n",
" else:\n",
" raise DiffError(f\"Invalid Line: {s}\")\n",
" s = s[1:]\n",
" if mode == \"keep\" and last_mode != mode:\n",
" if ins_lines or del_lines:\n",
" chunks.append(\n",
" Chunk(\n",
" orig_index=len(old) - len(del_lines),\n",
" del_lines=del_lines,\n",
" ins_lines=ins_lines,\n",
" )\n",
" )\n",
" del_lines = []\n",
" ins_lines = []\n",
" if mode == \"delete\":\n",
" del_lines.append(s)\n",
" old.append(s)\n",
" elif mode == \"add\":\n",
" ins_lines.append(s)\n",
" elif mode == \"keep\":\n",
" old.append(s)\n",
" if ins_lines or del_lines:\n",
" chunks.append(\n",
" Chunk(\n",
" orig_index=len(old) - len(del_lines),\n",
" del_lines=del_lines,\n",
" ins_lines=ins_lines,\n",
" )\n",
" )\n",
" del_lines = []\n",
" ins_lines = []\n",
" if index < len(lines) and lines[index] == \"*** End of File\":\n",
" index += 1\n",
" return old, chunks, index, True\n",
" if index == orig_index:\n",
" raise DiffError(f\"Nothing in this section - {index=} {lines[index]}\")\n",
" return old, chunks, index, False\n",
"\n",
"\n",
"def text_to_patch(text: str, orig: Dict[str, str]) -> Tuple[Patch, int]:\n",
" lines = text.strip().split(\"\\n\")\n",
" if len(lines) < 2 or not lines[0].startswith(\"*** Begin Patch\") or lines[-1] != \"*** End Patch\":\n",
" raise DiffError(\"Invalid patch text\")\n",
"\n",
" parser = Parser(\n",
" current_files=orig,\n",
" lines=lines,\n",
" index=1,\n",
" )\n",
" parser.parse()\n",
" return parser.patch, parser.fuzz\n",
"\n",
"\n",
"def identify_files_needed(text: str) -> List[str]:\n",
" lines = text.strip().split(\"\\n\")\n",
" result = set()\n",
" for line in lines:\n",
" if line.startswith(\"*** Update File: \"):\n",
" result.add(line[len(\"*** Update File: \") :])\n",
" if line.startswith(\"*** Delete File: \"):\n",
" result.add(line[len(\"*** Delete File: \") :])\n",
" return list(result)\n",
"\n",
"\n",
"def identify_files_added(text: str) -> List[str]:\n",
" lines = text.strip().split(\"\\n\")\n",
" result = set()\n",
" for line in lines:\n",
" if line.startswith(\"*** Add File: \"):\n",
" result.add(line[len(\"*** Add File: \") :])\n",
" return list(result)\n",
"\n",
"\n",
"def _get_updated_file(text: str, action: PatchAction, path: str) -> str:\n",
" assert action.type == ActionType.UPDATE\n",
" orig_lines = text.split(\"\\n\")\n",
" dest_lines = []\n",
" orig_index = 0\n",
" dest_index = 0\n",
" for chunk in action.chunks:\n",
" # Process the unchanged lines before the chunk\n",
" if chunk.orig_index > len(orig_lines):\n",
" raise DiffError(\n",
" f\"_get_updated_file: {path}: chunk.orig_index {chunk.orig_index} > len(lines) {len(orig_lines)}\"\n",
" )\n",
" if orig_index > chunk.orig_index:\n",
" raise DiffError(\n",
" f\"_get_updated_file: {path}: orig_index {orig_index} > chunk.orig_index {chunk.orig_index}\"\n",
" )\n",
" assert orig_index <= chunk.orig_index\n",
" dest_lines.extend(orig_lines[orig_index : chunk.orig_index])\n",
" delta = chunk.orig_index - orig_index\n",
" orig_index += delta\n",
" dest_index += delta\n",
" # Process the inserted lines\n",
" if chunk.ins_lines:\n",
" for i in range(len(chunk.ins_lines)):\n",
" dest_lines.append(chunk.ins_lines[i])\n",
" dest_index += len(chunk.ins_lines)\n",
" orig_index += len(chunk.del_lines)\n",
" # Final part\n",
" dest_lines.extend(orig_lines[orig_index:])\n",
" delta = len(orig_lines) - orig_index\n",
" orig_index += delta\n",
" dest_index += delta\n",
" assert orig_index == len(orig_lines)\n",
" assert dest_index == len(dest_lines)\n",
" return \"\\n\".join(dest_lines)\n",
"\n",
"\n",
"def patch_to_commit(patch: Patch, orig: Dict[str, str]) -> Commit:\n",
" commit = Commit()\n",
" for path, action in patch.actions.items():\n",
" if action.type == ActionType.DELETE:\n",
" commit.changes[path] = FileChange(type=ActionType.DELETE, old_content=orig[path])\n",
" elif action.type == ActionType.ADD:\n",
" commit.changes[path] = FileChange(type=ActionType.ADD, new_content=action.new_file)\n",
" elif action.type == ActionType.UPDATE:\n",
" new_content = _get_updated_file(text=orig[path], action=action, path=path)\n",
" commit.changes[path] = FileChange(\n",
" type=ActionType.UPDATE,\n",
" old_content=orig[path],\n",
" new_content=new_content,\n",
" move_path=action.move_path,\n",
" )\n",
" return commit\n",
"\n",
"\n",
"class DiffError(ValueError):\n",
" pass\n",
"\n",
"\n",
"def load_files(paths: List[str], open_fn: Callable) -> Dict[str, str]:\n",
" orig = {}\n",
" for path in paths:\n",
" orig[path] = open_fn(path)\n",
" return orig\n",
"\n",
"\n",
"def apply_commit(commit: Commit, write_fn: Callable, remove_fn: Callable) -> None:\n",
" for path, change in commit.changes.items():\n",
" if change.type == ActionType.DELETE:\n",
" remove_fn(path)\n",
" elif change.type == ActionType.ADD:\n",
" write_fn(path, change.new_content)\n",
" elif change.type == ActionType.UPDATE:\n",
" if change.move_path:\n",
" write_fn(change.move_path, change.new_content)\n",
" remove_fn(path)\n",
" else:\n",
" write_fn(path, change.new_content)\n",
"\n",
"\n",
"def process_patch(text: str, open_fn: Callable, write_fn: Callable, remove_fn: Callable) -> str:\n",
" assert text.startswith(\"*** Begin Patch\")\n",
" paths = identify_files_needed(text)\n",
" orig = load_files(paths, open_fn)\n",
" patch, fuzz = text_to_patch(text, orig)\n",
" commit = patch_to_commit(patch, orig)\n",
" apply_commit(commit, write_fn, remove_fn)\n",
" return \"Done!\"\n",
"\n",
"\n",
"def open_file(path: str) -> str:\n",
" with open(path, \"rt\") as f:\n",
" return f.read()\n",
"\n",
"\n",
"def write_file(path: str, content: str) -> None:\n",
" if \"/\" in path:\n",
" parent = \"/\".join(path.split(\"/\")[:-1])\n",
" os.makedirs(parent, exist_ok=True)\n",
" with open(path, \"wt\") as f:\n",
" f.write(content)\n",
"\n",
"\n",
"def remove_file(path: str) -> None:\n",
" os.remove(path)\n",
"\n",
"\n",
"def main() -> None:\n",
" import sys\n",
"\n",
" patch_text = sys.stdin.read()\n",
" if not patch_text:\n",
" print(\"Please pass patch text through stdin\")\n",
" return\n",
" try:\n",
" result = process_patch(patch_text, open_file, write_file, remove_file)\n",
" except DiffError as e:\n",
" print(str(e))\n",
" return\n",
" print(result)\n",
"\n",
"\n",
"if __name__ == \"__main__\":\n",
" main()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Other Effective Diff Formats\n",
"\n",
"If you want to try using a different diff format, we found in testing that the SEARCH/REPLACE diff format used in Aiders polyglot benchmark, as well as a pseudo-XML format with no internal escaping, both had high success rates.\n",
"\n",
"These diff formats share two key aspects: (1) they do not use line numbers, and (2) they provide both the exact code to be replaced, and the exact code with which to replace it, with clear delimiters between the two."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"SEARCH_REPLACE_DIFF_EXAMPLE = \"\"\"\n",
"path/to/file.py\n",
"```\n",
">>>>>>> SEARCH\n",
"def search():\n",
" pass\n",
"=======\n",
"def search():\n",
" raise NotImplementedError()\n",
"<<<<<<< REPLACE\n",
"\"\"\"\n",
"\n",
"PSEUDO_XML_DIFF_EXAMPLE = \"\"\"\n",
"<edit>\n",
"<file>\n",
"path/to/file.py\n",
"</file>\n",
"<old_code>\n",
"def search():\n",
" pass\n",
"</old_code>\n",
"<new_code>\n",
"def search():\n",
" raise NotImplementedError()\n",
"</new_code>\n",
"</edit>\n",
"\"\"\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.8"
}
},
"nbformat": 4,
"nbformat_minor": 4
}