xonsh / xontrib-template

Full-featured template for building extension (xontrib) for the xonsh shell.
MIT License
42 stars 12 forks source link

Idea: xontrib-codex - use OpenAI Codex to translate natural language to code #25

Closed anki-code closed 1 year ago

anki-code commented 1 year ago

We’ve created an improved version of OpenAI Codex, our AI system that translates natural language to code, and we are releasing it through our API in private beta starting today.

The example of code for catching key press and add text:

from prompt_toolkit import prompt
from prompt_toolkit.key_binding import KeyBindings

# Define key bindings to replace text on space key press
kb = KeyBindings()
@kb.add(' ')
def _(event):
    event.current_buffer.text = event.current_buffer.text + ' space :)'
    event.current_buffer.cursor_position += len(event.current_buffer.text)  # move coursor to the end

# Start a prompt session with key bindings
text = prompt('> ', key_bindings=kb)
print('You entered:', text)

Draft 1:

import openai

openai.api_key = "YOUR_API_KEY_HERE"  # https://platform.openai.com/account/api-keys

# Example prompt
prompt = "I love Python because"

# Example completion using the GPT-3 model
response = openai.Completion.create(
    engine="davinci", prompt=prompt, max_tokens=50
)

# Print the response
print(response.choices[0].text)

Draft 2:

import os
import requests
import json
import time

from prompt_toolkit.keys import Keys

$OPENAI_API_KEY = '...' # https://platform.openai.com/account/api-keys

@events.on_ptk_create
def custom_keybindings(bindings, **kw):
    @bindings.add('c-k')  # control+k
    def run(event):
        input = event.current_buffer.text
        print('\n# ...')

        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + __xonsh__.env.get('OPENAI_API_KEY'),
        }

        json_data = {
            'model': __xonsh__.env.get('OPENAI_MODEL', 'text-davinci-003'),
            'max_tokens': __xonsh__.env.get('OPENAI_MAX_TOKENS', 1000),
            'temperature': __xonsh__.env.get('OPENAI_TEMPERATURE', 0),
            'prompt': input,            
        }

        output_delay = __xonsh__.env.get('OPENAI_OUTPUT_DELAY', 0.01)

        try:
            response = requests.post('https://api.openai.com/v1/completions', headers=headers, json=json_data)     
        except Exception as e:
            print(f'\n# Error request: {str(e)}')
            return        

        if response.status_code != 200:
            print(f'\n# Error response: {response.status_code}')
            return

        try:
            j = response.json()
        except Exception as e:
            print(f'\n# Error response: {response}')
            print(f'\n# Error exception: {str(e)}')
            return

        output = j['choices'][0]['text']
        for w in output.split(' '):
            event.current_buffer.insert_text(w + ' ')
            event.current_buffer.validate()
            time.sleep(output_delay)

# git commit <control+k> 

For community

⬇️ Please click the 👍 reaction instead of leaving a +1 or 👍 comment

anki-code commented 1 year ago

https://github.com/anki-code/xontrib-openai