Skip to content

Instantly share code, notes, and snippets.

@lbialy
Last active January 3, 2025 01:43
Show Gist options
  • Save lbialy/4efdeddad42f26bf49dc6229844e1474 to your computer and use it in GitHub Desktop.
Save lbialy/4efdeddad42f26bf49dc6229844e1474 to your computer and use it in GitHub Desktop.
I heard you like chatting with ChatGPT so I put ChatGPT inside of your Scala compilation so that you can chat with ChatGPT while you compile Scala
//> using lib "com.softwaremill.sttp.openai::core:0.0.6"
object ai:
import scala.quoted.*
import sttp.openai.OpenAISyncClient
import sttp.openai.requests.completions.chat.*
import sttp.openai.requests.completions.chat.ChatRequestBody.ChatBody
import sttp.openai.requests.completions.chat.ChatRequestBody.ChatCompletionModel
opaque type GPT[A <: String] <: String = String
object GPT:
inline def apply[A <: String]: GPT[A] = ${ callOpenAI[A] }
private def callOpenAI[A <: String](using t: Type[A], quotes: Quotes): Expr[String] =
import quotes.reflect.*
TypeRepr.of[A] match
case ConstantType(StringConstant(name)) =>
val token = sys.env.get("OPENAI_API_KEY").getOrElse {
report.errorAndAbort("OPENAI_API_KEY environment variable is not set!")
}
val bodyMessages = Seq(
Message(
role = Role.User,
content = name
)
)
val chatRequestBody = ChatBody(
model = ChatCompletionModel.GPT35Turbo,
messages = bodyMessages
)
val openAI = OpenAISyncClient(token)
val chatResponse = openAI.createChatCompletion(chatRequestBody)
val response = chatResponse.choices.map(_.message.content).mkString("\n")
report.info(response)
Expr(response)
case _ => report.errorAndAbort("The macro argument must be a known string literal")
import ai.*
object test:
val x: String = GPT["Write a haiku about Mikołaj not believing in the power of Scala"]
╭─lbialy at lbialy-MacBook-Pro in ⌁/Projects/foss/tmp/macroai (⎈ docker-desktop|default)
╰─λ scala-cli compile . --server=false
-- Info: /Users/lbialy/Projects/foss/tmp/macroai/main.scala:6:21 ---------------
6 | val x: String = GPT["Write a haiku about Mikołaj not believing in the power of Scala"]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| Mikołaj, skeptic heart,
| Scala's power he denies,
| Code's beauty unfolds.
@trixter99
Copy link

can you help me?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment