AI-powered Code Autocompletion Python, AI

👤 Sharing: AI
```python
import openai
import os

def complete_code(prompt, model="gpt-3.5-turbo-instruct", temperature=0.0, max_tokens=256, stop=None):
    """
    Uses OpenAI's API to complete code based on a given prompt.

    Args:
        prompt (str): The initial code snippet or description to base the completion on.
        model (str): The OpenAI model to use. Defaults to "gpt-3.5-turbo-instruct". Other options include "code-davinci-002".
        temperature (float): Controls randomness. Lower values (e.g., 0.0) produce more deterministic output.  Higher values generate more creative but potentially less accurate results.
        max_tokens (int): The maximum number of tokens in the generated completion.
        stop (list of str, optional): Stop sequences that indicate the completion should stop.

    Returns:
        str: The completed code generated by the AI.  Returns None if an error occurs or if the API key is not set.
    """

    openai_api_key = os.environ.get("OPENAI_API_KEY")
    if not openai_api_key:
        print("Error: OpenAI API key not found.  Please set the OPENAI_API_KEY environment variable.")
        return None

    openai.api_key = openai_api_key

    try:
        response = openai.Completion.create(
            model=model,
            prompt=prompt,
            temperature=temperature,
            max_tokens=max_tokens,
            stop=stop
        )
        return response.choices[0].text.strip()
    except Exception as e:
        print(f"Error during code completion: {e}")
        return None



if __name__ == '__main__':
    # Example Usage
    my_prompt = """
    # Python function to calculate the factorial of a number
    def factorial(n):
        """
    completed_code = complete_code(my_prompt, stop=["\"\"\""])  # Stop at the docstring end.

    if completed_code:
        print(my_prompt + completed_code)
```
👁️ Viewed: 8

Comments