openai/openai-python

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.10.3

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/codex/backtranslation.py

187lines · modeblame

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