最近用 LLM 挺多的,尝试用英文写 prompt,但有时我不知道怎么写(英文菜)就想着翻译一下,当然翻译的工具很多。
这个函数只是分享一下 gptel-request 的一种实现。(本来是想玩玩 gptel-tool,但还没玩明白)
逻辑都是 LLM 写的,大体的逻辑是:
- 找到当前选中区域,或者基于当前 point 获取对应的行/段落,作为要翻译的内容
- 绑定一些本地变量,如 model,backend,因为翻译只需要一个快速便宜的模型
- 调用
gptel-request
发起请求,得到响应后覆盖第 1 步选中的内容
(defun spike-leung/translate-region-to-english ()
"Translate the selected region to English using gptel and replace it in the buffer.
If no region is active, try to guess the sentence or paragraph at point."
(interactive)
(let* ((has-region (use-region-p))
(bounds
(cond
(has-region
(cons (region-beginning) (region-end)))
((use-region-p)
(cons (region-beginning) (region-end)))
((and (fboundp 'bounds-of-thing-at-point))
(or (bounds-of-thing-at-point 'sentence)
(bounds-of-thing-at-point 'paragraph)
(bounds-of-thing-at-point 'line)
(cons (point) (point))))
(t (cons (point) (point)))))
(start (car bounds))
(end (cdr bounds))
(text (buffer-substring-no-properties start end))
(model 'openai/gpt-4.1-nano)
(backend (gptel-make-openai "OpenRouter"
:host "openrouter.ai"
:endpoint "/api/v1/chat/completions"
:stream t
:key (spike-leung/get-openrouter-api-key)
:models spike-leung/openrouter-models)))
(if (string-blank-p text)
(user-error "No text to translate")
(let ((gptel-backend backend)
(gptel-model model)
(gptel-use-tools nil)
(gptel-use-context nil))
(gptel-request
(format "Translate the following text to English:
%s" text)
:callback (lambda (response _)
(when response
(save-excursion
(delete-region start end)
(goto-char start)
(insert response)))))))))
定义一个方法包装 prompt 和 gptel-request,感觉可以利用 LLM 解决很多重复的小任务。
(顺便水了篇博客 https://taxodium.ink/use-gptel-request-to-translate.html )