Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add model_name as a parameter to call_openai and calculate_perplexity #6

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions betterprompt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
import os


model_name: str = "text-davinci-003"

def get_from_dict_or_env(env_key: str) -> str:
"""Get a value from a dictionary or an environment variable."""
if env_key in os.environ and os.environ[env_key]:
Expand All @@ -18,27 +16,28 @@ def get_from_dict_or_env(env_key: str) -> str:
)


def call_openai(prompt: str):
def call_openai(prompt: str, model_name: str = "text-davinci-003"):
openai_api_key = get_from_dict_or_env("OPENAI_API_KEY")
openai.api_key = openai_api_key
#GET THE LOGPROB OF THE PROMPT
response = openai.Completion.create(
model="text-davinci-003",
model=model_name,
prompt=prompt,
max_tokens=0,
echo=True,
logprobs=0
)
return response["choices"][0]["logprobs"]["token_logprobs"]

def calculate_perplexity(prompt: str):
def calculate_perplexity(prompt: str, model_name: str = "text-davinci-003"):
nlls = []

token_logprobs = call_openai(prompt)
token_logprobs = call_openai(prompt, model_name)
for neg_log_likelihood in token_logprobs:
if neg_log_likelihood == None: #default to -100, handles the initial token case
neg_log_likelihood = -100
nlls.append(neg_log_likelihood)

perplexity = math.exp(sum(nlls)/len(token_logprobs))
return perplexity
return perplexity