Skip to content

Instantly share code, notes, and snippets.

@wtsnjp
Created December 22, 2024 14:48
Show Gist options
  • Save wtsnjp/02aaaadc749b05d394b9938b2f82ef01 to your computer and use it in GitHub Desktop.
Save wtsnjp/02aaaadc749b05d394b9938b2f82ef01 to your computer and use it in GitHub Desktop.
Using OpenAI API in a LuaTeX document
% +++
% latex = "lualatex -shell-escape"
% max_repeat = 1
% +++
\documentclass[a4paper]{jlreq}
\usepackage[verb]{bxghost}
\usepackage{luacode}
\usepackage{luapackageloader}
% lua code
\begin{luacode*}
local HOME = os.getenv('HOME')
local LIB_PATH = HOME .. '/.luarocks/share/lua/5.4/'
local CLIB_PATH = HOME .. '/.luarocks/lib/lua/5.3/'
package.path = LIB_PATH .. '?.lua;' .. LIB_PATH .. '?/init.lua;' .. package.path
package.cpath = CLIB_PATH .. '?.so;' .. package.cpath
local openai = require 'openai'
local client = openai.new(os.getenv('OPENAI_API_KEY'), {http_provider = 'ssl.https'})
local sys_prompt = [[You are a Japanese TeX/LaTeX expert.
Return your answers as LaTeX codes, not Markdown.
You only need to produce paragraphs. You don't have to write \begin{document} or \section.
Do not include anything except LaTeX code.
Use commands \TeX{} and \LaTeX{} for TeX-related names.
Please be aware that you have to use \verb to escape TeX commands within your explanation.
Try not to produce invalid LaTeX code.
]]
local function showall(tab)
for k, v in pairs(tab) do
print(k, v)
end
end
function gen_content(message)
local status, response = client:chat({
{role = 'system', content = sys_prompt},
{role = 'user', content = message}
}, {
model = 'gpt-4o-mini',
temperature = 0.5
})
if status == 200 then
return response.choices[1].message.content
else
print('Request error: ' .. status)
showall(response.error)
end
end
\end{luacode*}
% doc body
\begin{document}
\title{すごいレポート}
\author{GPT-4o mini}
\maketitle
\section{\TeX{}と\LaTeX{}の違い}
\directlua{tex.sprint(gen_content('TeXとLaTeXの違いを説明してください'))}
\section{\TeX{}言語の楽しさ}
\directlua{tex.sprint(gen_content('TeX言語の面白さを教えてください。特に、展開制御や少ないレジスタを工夫して有効活用するテクニックに着目してください'))}
\section{本質的なこと}
\directlua{tex.sprint(gen_content('ゆきだるまがいかにかわいくて素晴らしいかを力説してください'))}
\end{document}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment