Skip to content

Instantly share code, notes, and snippets.

@mattneary
Created July 27, 2024 22:24
Show Gist options
  • Save mattneary/c2ea7c77d4ec097c989139823550540c to your computer and use it in GitHub Desktop.
Save mattneary/c2ea7c77d4ec097c989139823550540c to your computer and use it in GitHub Desktop.
#lang racket
(require json
syntax/parse/define
net/url
(for-syntax racket/base json net/url))
;; Replace YOUR_API_KEY with your actual OpenAI API key
(define-for-syntax api-key "YOUR_API_KEY")
;; Function to read all data from a port
(define-for-syntax (read-all-from-port port)
(let loop ([lines '()]
[next-line (read-line port)])
(if (eof-object? next-line)
(apply string-append (reverse (map (lambda (line) (string-append line "\n")) lines)))
(loop (cons next-line lines) (read-line port)))))
;; Function to make OpenAI API call
(define-for-syntax (openai-api-call api-key instr)
(let* ([url (string->url "https://api.openai.com/v1/chat/completions")]
[headers (list (format "Authorization: Bearer ~a" api-key)
"Content-Type: application/json")]
[data (hasheq 'model "gpt-4"
'messages (list (hasheq 'role "system"
'content "Given a description of the desired functionality, you return a valid racket lambda expression that computes the result. The result should be formatted as a single valid racket lambda expression, without any other formatting or explanation. The first character should be a parentheses.")
(hasheq 'role "user"
'content instr)))]
[post-data (jsexpr->bytes data)]
[port (post-pure-port url post-data headers)]
[response (read-all-from-port port)])
(close-input-port port)
response))
;; Macro to replace an instruction with its implementation
(define-syntax (auto-code stx)
(syntax-case stx ()
[(_ instr)
(let* ([response (openai-api-call api-key (syntax->datum #'instr))]
[parsed-response (string->jsexpr response)]
[code (hash-ref (hash-ref (car (hash-ref parsed-response 'choices)) 'message) 'content)]
[expr (read (open-input-string code))])
#`(begin #,expr))]))
(define fib (auto-code "return the nth fibonacci number"))
(print (fib 7))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment