Dwootton commited on
Commit
a5eff80
·
verified ·
1 Parent(s): 24f5b30

Add prompt_builder.py

Browse files
Files changed (1) hide show
  1. pipeline/prompt_builder.py +95 -0
pipeline/prompt_builder.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prompt builder for StableToolBench ReAct evaluation.
2
+
3
+ Constructs system + user prompts for each P2P condition, with pluggable
4
+ tool descriptions and in-context examples.
5
+ """
6
+ import json
7
+ from typing import Dict, List, Optional, Any
8
+
9
+
10
+ def build_task_description(tool_descriptions):
11
+ """Build the task description that lists available tools (from StableToolBench rapidapi.py)."""
12
+ desc = ('You should use functions to help handle the real time user querys. Remember:\n'
13
+ '1.ALWAYS call "Finish" function at the end of the task. And the final answer '
14
+ 'should contain enough information to show to the user,If you can\'t handle the '
15
+ 'task, or you find that function calls always fail(the function is not valid now), '
16
+ 'use function Finish->give_up_and_restart.\n'
17
+ '2.Do not use origin tool names, use only subfunctions\' names.\n'
18
+ 'You have access of the following tools:\n')
19
+ seen = {}
20
+ for std_name, tool_des in tool_descriptions:
21
+ if std_name not in seen: seen[std_name] = tool_des
22
+ for k, (std_name, tool_des) in enumerate(seen.items()):
23
+ striped = (tool_des[:512].replace('\n', '').strip()) if tool_des else "None"
24
+ if not striped: striped = "None"
25
+ desc += f"{k+1}.{std_name}: {striped}\n"
26
+ return desc
27
+
28
+
29
+ def build_system_prompt(task_description):
30
+ """Build the system message for ReAct (FORMAT_INSTRUCTIONS_SYSTEM_FUNCTION)."""
31
+ return ("You are AutoGPT, you can use many tools(functions) to do the following task.\n"
32
+ "First I will give you the task description, and your task start.\n"
33
+ "At each step, you need to give your thought to analyze the status now and "
34
+ "what to do next, with a function call to actually excute your step.\n"
35
+ "After the call, you will get the call result, and you are now in a new state.\n"
36
+ "Then you will analyze your status now, then decide what to do next...\n"
37
+ "After many (Thought-call) pairs, you finally perform the task, then you can "
38
+ "give your finial answer.\nRemember: \n"
39
+ "1.the state change is irreversible, you can't go back to one of the former state, "
40
+ 'if you want to restart the task, say "I give up and restart".\n'
41
+ "2.All the thought is short, at most in 5 sentence.\n"
42
+ "3.You can do more then one trys, so if your plan is to continusly try some "
43
+ "conditions, you can do one of the conditions per try.\nLet's Begin!\n"
44
+ f"Task description: {task_description}")
45
+
46
+
47
+ def build_user_prompt(query, examples=None):
48
+ """Build the initial user message, optionally with in-context examples."""
49
+ prompt = ""
50
+ if examples:
51
+ prompt += "Here are some examples of how to use the available tools:\n\n"
52
+ for i, ex in enumerate(examples, 1):
53
+ prompt += f"Example {i}:\nUser: {ex['instruction']}\n"
54
+ prompt += f"Tool call: {json.dumps(ex['fn_call'])}\n"
55
+ prompt += f"Tool result: {str(ex['tool_results'])[:512]}\n"
56
+ prompt += f"Answer: {ex['answer']}\n\n"
57
+ prompt += "Now handle the following real task:\n\n"
58
+ prompt += f"{query}\nBegin!\n"
59
+ return prompt
60
+
61
+
62
+ def build_initial_messages(query, tool_descriptions, examples=None):
63
+ """Build the initial message list for a ReAct conversation."""
64
+ task_desc = build_task_description(tool_descriptions)
65
+ system = build_system_prompt(task_desc)
66
+ user = build_user_prompt(query, examples)
67
+ return [{"role": "system", "content": system}, {"role": "user", "content": user}]
68
+
69
+
70
+ def get_condition_config(condition, p2p_descriptions=None, p2p_examples=None):
71
+ """Get configuration for a P2P condition.
72
+
73
+ condition: One of 'baseline', 'p2p_desc', 'p2p_demo', 'p2p_full'
74
+ Returns dict with: use_custom_descriptions, custom_descriptions, use_examples, examples
75
+ """
76
+ configs = {
77
+ "baseline": {"use_custom_descriptions": False, "custom_descriptions": None, "use_examples": False, "examples": None},
78
+ "p2p_desc": {"use_custom_descriptions": True, "custom_descriptions": p2p_descriptions or {}, "use_examples": False, "examples": None},
79
+ "p2p_demo": {"use_custom_descriptions": False, "custom_descriptions": None, "use_examples": True, "examples": p2p_examples or {}},
80
+ "p2p_full": {"use_custom_descriptions": True, "custom_descriptions": p2p_descriptions or {}, "use_examples": True, "examples": p2p_examples or {}},
81
+ }
82
+ if condition not in configs:
83
+ raise ValueError(f"Unknown condition: {condition}. Must be one of {list(configs.keys())}")
84
+ return configs[condition]
85
+
86
+
87
+ def gather_examples_for_query(tool_names, api_name_reflect, functions, all_examples, max_per_tool=1):
88
+ """Gather in-context examples relevant to a specific query's tools."""
89
+ gathered = []
90
+ for func in functions:
91
+ func_name = func["function"]["name"]
92
+ if func_name == "Finish": continue
93
+ if func_name in all_examples:
94
+ gathered.extend(all_examples[func_name][:max_per_tool])
95
+ return gathered