openai/openai-python

Public

mirrored from https://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.15.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/codex/backtranslation.py

189lines · modeblame

7febb755Boris Power4 years ago1from typing import List, Union
2
62f8d40fMadeleine Thompson4 years ago3from smokey import Smokey
4
5import openai
6
7febb755Boris Power4 years ago7
8def get_candidates(
9prompt: str,
10stop: List[str],
11temperature: float,
12priming_prefix: str,
13engine: str,
14n: int = 5,
15) -> List[str]:
16"""
17Generate N candidate completions based on the prompt, generated with a specific temperature.
18
19:param prompt: The prompt to start the conversation with.
20:param stop: A list of tokens that indicate the end of the generation.
21:param temperature: The temperature of the generation.
22:param priming_prefix: The prefix to use for the priming.
23:param engine: The engine to use for the generation.
24:param n: The number of completions to generate.
25:return: A list of completions.
26"""
27response = openai.Completion.create(
28engine=engine,
29prompt=prompt,
30temperature=temperature,
31max_tokens=150,
32top_p=1,
33frequency_penalty=0,
34presence_penalty=0,
35stop=stop,
36n=n,
37)
38responses = [priming_prefix + choice.text for choice in response.choices]
39return responses
40
41
42def rindex(lst: List, value: str) -> int:
43"""
44Return the index of the last occurence of a value in a list.
45
46:param lst: The list to search in.
47:param value: The value to search for.
48:return: The index of the last occurence of the value.
49"""
50try:
51return len(lst) - lst[::-1].index(value) - 1
52except ValueError:
53raise ValueError(f"Answer start token `{value}` not found in the eval template")
54
55
56def eval_candidate(
57candidate_answer: str,
58original_instruction: str,
59eval_template: str,
60answer_start_token: str,
61engine: str,
62) -> float:
63"""
64Evaluate a candidate answer by calculating the average log probability
65of the original instruction, given the candidate answer with a specific
66evaluation template, aimed at reconstructing the original instruction.
67
68:param candidate_answer: The candidate answer to evaluate.
69:param original_instruction: The original instruction.
70:param eval_template: The template to use for the evaluation.
71:param answer_start_token: The token to use to indicate the start of the answer.
72:param engine: The engine to use for the evaluation.
73:return: The evaluation of the candidate answer.
74"""
75response = openai.Completion.create(
76engine=engine,
77prompt=eval_template.format(candidate_answer, original_instruction),
78temperature=0,
79max_tokens=0,
80top_p=1,
81frequency_penalty=0,
82presence_penalty=0,
83logprobs=1,
84echo=True,
85)
86
87answer_start = rindex(
88response["choices"][0]["logprobs"]["tokens"], answer_start_token
89)
90logprobs = response["choices"][0]["logprobs"]["token_logprobs"][answer_start + 1 :]
91return sum(logprobs) / len(logprobs)
92
93
94def backtranslation(
95prompt_template: str,
96additional_info: str,
97instruction: str,
98eval_template: str,
99priming_prefix: str = "SELECT",
100stop1: List[str] = ["#", ";"],
101answer_start_token: str = "--",
102n: int = 5,
103temperature: float = 0.5,
104return_all_results: bool = False,
105engine: str = "davinci-codex",
106) -> Union[str, List[str, float]]:
107"""
108Generate a number of SQL queries given a natural language instruction,
109and pick the best one based on the average log probability of explaining the
110candidate SQL query with the exact original instruction, when prompted for
111a natural language explanation of the candidate SQL query.
112
113:param prompt_template: The template to use for the prompt to generate SQL.
114:param additional_info: Additional information to include in the prompt
115(SQL Tables, and their properties).
116:param instruction: The instruction in natural language.
117:param eval_template: The template to use for the evaluation.
118:param priming_prefix: The prefix to use for the priming of the SQL query.
119:param stop1: A list of tokens that indicate the end of the generation.
120:param answer_start_token: The token to use to indicate the start of the
121natural answer.
122:param n: The number of candidates to generate.
123:param temperature: The temperature of the generation.
124:param return_all_results: Whether to return all results or just the best one.
125:param engine: The engine to use for the generation and evaluation.
126:return: The best SQL query, or a list of all scored generated SQL queries.
127"""
128prompt_template = prompt_template.format(
129additional_info, instruction, priming_prefix
130)
131
132candidates = []
133responses = get_candidates(
134prompt_template, stop1, temperature, priming_prefix, engine=engine, n=n
135)
136for i in range(n):
137quality = eval_candidate(
138responses[i],
139instruction,
140eval_template,
141answer_start_token,
142engine=engine,
143)
144candidates.append((responses[i], quality))
145
146candidates.sort(key=lambda x: x[1], reverse=True)
147if return_all_results:
148return candidates
149return candidates[0][0]
150
151
152def main(
153nl_query: str = "Return the name of each department that had more than 10 employees in June 2021",
154eval_template: str = "{};\n-- Explanation of the above query in human readable format\n-- {}",
155table_definitions: str = "# Employee(id, name, department_id)\n# Department(id, name, address)\n# Salary_Payments(id, employee_id, amount, date)\n",
156prompt_template: str = "### Postgres SQL tables, with their properties:\n#\n{}#\n### {}\n{}",
157n: int = 3,
158temperature: float = 0.3,
159engine: str = "davinci-codex",
160):
161"""
162Generate a number of SQL queries given a natural language instruction,
163and pick the best one based on the highest backtranslation score.
164
165:param nl_query: The natural language query.
166:param eval_template: The template to use for the evaluation.
167:param table_definitions: The definitions of the tables used in the query.
168:param prompt_template: The template to use for the prompt to generate SQL.
169:param n: The number of candidates to generate.
170:param temperature: The temperature of the generation.
171:param engine: The engine to use for the generation and evaluation.
172:return: The best SQL query, or a list of all scored generated SQL queries.
173"""
174
175result = backtranslation(
176prompt_template,
177table_definitions,
178nl_query,
179eval_template,
180priming_prefix="SELECT",
181temperature=temperature,
182n=n,
183engine=engine,
184)
185print(result)
186
187
188if __name__ == "__main__":
189Smokey(main)