Skip to content
Open
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ cd AICodePal/src/python
pip install -r requirements.txt
```

3. Replace `YOUR_API_KEY` in the `ai_code_pal.py` file with your actual ChatGPT API key.
3. Set the environment variable `OPENAI_API_KEY` with your actual ChatGPT API key.

4. Now you can use the `get_chatgpt_suggestion` function from the `ai_code_pal.py` file in your project.

Expand Down
42 changes: 23 additions & 19 deletions src/python/ai_code_pal.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
import requests
import os
from typing import Tuple
import openai

def get_chatgpt_suggestion(code_snippet):
api_key = os.environ.get('OPENAI_API_KEY')
url = "https://api.openai.com/v1/engines/davinci-codex/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
data = {
"prompt": f"Improve the following Python code: {code_snippet}",
"max_tokens": 50,
"n": 1,
"stop": None,
"temperature": 0.7,
}
response = requests.post(url, headers=headers, json=data)
suggestion = response.json()['choices'][0]['text']
return suggestion.strip()

OPENAI_MODEL = "gpt-3.5-turbo"


def get_chatgpt_suggestion(code_snippet: str) -> Tuple[str, int]:
"""
Returns PR style feedback for the given code snippet, and the number of tokens used.
"""
system_prompt = f"""You are AI Code Pal. Suggest improvements to the provided Python code as in a code review."""

user_prompt = code_snippet
llm_response = openai.ChatCompletion.create(
model=OPENAI_MODEL,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
temperature=0.7,
)

return llm_response["choices"][0]["message"]["content"].strip(), llm_response["usage"]["total_tokens"]

3 changes: 1 addition & 2 deletions src/python/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
requests

openai