
最近用 LLM 挺多的,尝试用英文写 prompt,但有时我不知道怎么写(英文比较菜)就想着翻译一下。
当然 Emacs 中的翻译的工具很多 1,写这个函数只是分享一下 gptel-request
的一种实现。
- 找到当前选中区域,或者基于当前 point 获取对应的行/段落,作为要翻译的内容。
- 绑定一些本地变量,如 model,backend,因为翻译只需要一个快速便宜的模型。
- 调用
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 解决的任务。