使用 gptel-request 封装一个翻译方法
文章介绍了一个在Emacs中使用gptel-request实现的翻译函数spike-leung/translate-region-to-english,用于将选中文本或当前行/段落翻译成英文,并支持自定义模型和后端配置。 2025-4-15 00:0:0 Author: taxodium.ink(查看原文) 阅读量:4 收藏

demo.gif
图1  一个 GIF 图,演示了选中中文,然后调用 spike-leung/translate-region-to-english 翻译成英文。

最近用 LLM 挺多的,尝试用英文写 prompt,但有时我不知道怎么写(英文比较菜)就想着翻译一下。

当然 Emacs 中的翻译的工具很多 1,写这个函数只是分享一下 gptel-request 的一种实现。

逻辑都是 LLM 写的,大体的逻辑是:2 , 3

  1. 找到当前选中区域,或者基于当前 point 获取对应的行/段落,作为要翻译的内容。
  2. 绑定一些本地变量,如 model,backend,因为翻译只需要一个快速便宜的模型。
  3. 调用 gptel-request ,写一个翻译的 prompt,发起请求,得到响应后覆盖第 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:\n\n%s" text)
          :callback (lambda (response _)
                      (when response
                        (save-excursion
                          (delete-region start end)
                          (goto-char start)
                          (insert response)))))))))

利用 gptel-request ,封装一些 prompt,可以方便地解决平时一些重复的、可以使用 LLM 解决的任务。

Date: 2025-04-15 Tue 00:00

Last Modified: 2025-04-15 Tue 19:14

License: CC BY-NC 4.0


文章来源: https://taxodium.ink//use-gptel-request-to-translate.html
如有侵权请联系:admin#unsafe.sh