Perl 调用 DeepSeek API 脚本

chat.deepseek.com 提问:请将这个 python 脚本翻译为 perl 语言脚本

参阅:Python 调用 DeepSeek API 完整指南

将 Python 脚本翻译为 Perl 语言脚本时,需要注意两种语言之间的语法差异。以下是将给定的 Python 脚本翻译为 Perl 的版本: test_deepseek_v1.pl

perl 复制代码
use strict;
use warnings;
use utf8;
use JSON;
use LWP::UserAgent;
use HTTP::Request::Common;
use POSIX qw(strftime);
use Encode qw(encode decode);

# 保存对话内容到文件
sub save_to_file {
    my ($file, $content, $is_question) = @_;
    my $timestamp = strftime("%Y-%m-%d %H:%M:%S", localtime);
    if ($is_question) {
        print $file "\n[$timestamp] Question:\n$content\n\n[$timestamp] Answer:\n";
    } else {
        print $file $content;
    }
}

# 主函数
sub main {
    # 配置
    my $url = "https://api.siliconflow.cn/v1/chat/completions";
    my $headers = {
        "Content-Type" => "application/json",
        "Authorization" => "Bearer YOUR_API_KEY"  # 替换为你的 API Key
    };

    # 打开文件用于保存对话
    open(my $file, '>>:encoding(UTF-8)', "conversation.txt") or die "无法打开文件: $!";

    while (1) {
        # 获取用户输入
        print "\n请输入您的问题 (输入 q 退出): ";
        my $question = <STDIN>;
        chomp($question);
        $question =~ s/^\s+|\s+$//g;

        if (lc($question) eq 'q') {
            print "程序已退出\n";
            last;
        }

        # 保存问题
        save_to_file($file, $question, 1);

        # 准备请求数据
        my $data = {
            "model" => "deepseek-ai/DeepSeek-V3",
            "messages" => [
                {
                    "role" => "user",
                    "content" => $question
                }
            ],
            "stream" => JSON::true,
            "max_tokens" => 2048,
            "temperature" => 0.7,
            "top_p" => 0.7,
            "top_k" => 50,
            "frequency_penalty" => 0.5,
            "n" => 1,
            "response_format" => {
                "type" => "text"
            }
        };

        my $ua = LWP::UserAgent->new;
        my $request = POST($url, $headers, Content => encode_json($data));

        try {
            # 发送流式请求
            my $response = $ua->request($request);

            if ($response->is_success) {
                # 处理流式响应
                my @lines = split /\n/, $response->decoded_content;
                foreach my $line (@lines) {
                    if ($line) {
                        if ($line =~ /^data: /) {
                            if ($line eq 'data: [DONE]') {
                                next;
                            }

                            my $json_str = substr($line, 6);  # 去掉 'data: ' 前缀
                            my $content = decode_json($json_str);
                            if ($content->{choices}[0]{delta}{content}) {
                                my $chunk = $content->{choices}[0]{delta}{content};
                                print $chunk;
                                print $file $chunk;
                                $file->flush();
                            }
                        }
                    }
                }

                # 添加分隔符
                print "\n----------------------------------------\n";
                print $file "\n----------------------------------------\n";
                $file->flush();
            } else {
                die "请求失败: " . $response->status_line;
            }
        } catch {
            my $error_msg = "请求错误: $_\n";
            print $error_msg;
            print $file $error_msg;
            $file->flush();
        }
    }

    close($file);
}

# 执行主函数
main();

运行 cmd

chcp 65001

perl test_deepseek_v1.pl

说明:

  1. 模块导入 :Perl 使用 use 来导入模块,例如 use JSON;use LWP::UserAgent;

  2. 文件操作 :Perl 使用 openclose 来打开和关闭文件。

  3. JSON 处理 :Perl 使用 JSON 模块来处理 JSON 数据。

  4. HTTP 请求 :Perl 使用 LWP::UserAgent 来发送 HTTP 请求。

  5. 异常处理 :Perl 使用 trycatch 来处理异常(需要 Try::Tiny 模块,但在这个例子中简化了异常处理)。

  6. 流式处理:Perl 通过逐行处理响应内容来模拟流式处理。

注意事项:

  • Perl 的 trycatch 语法需要 Try::Tiny 模块,如果没有安装,可以使用 eval 来替代。

  • Perl 的 printflush 操作与 Python 类似,但需要显式调用 flush 来确保数据写入文件。

相关推荐
AC赳赳老秦29 分钟前
接口测试自动化:用 OpenClaw 对接 Postman,实现批量回归测试、测试报告自动生成与推送
java·人工智能·python·算法·elasticsearch·deepseek·openclaw
DO_Community31 分钟前
DigitalOcean VPC 网络故障排查 Runbook 实战指南
人工智能·aigc·claude·deepseek
可观测性用观测云1 小时前
FUNC 平台函数 API 认证最佳实践
api
cooldream20094 小时前
DeepSeek V4 与 LangChain 集成:从入门到生产级应用
langchain·deepseek
CIO_Alliance5 小时前
2026年生成式引擎优化(GEO)解决方案选型指南|幂链科技的实战可验证与全链路合规
人工智能·geo·deepseek·ai搜索优化·幂链geo·豆包ai
青山如墨雨如画10 小时前
【2026年5月5日】Win11最新版VSCode下的Claude+Deepseek-V4[1m]安装与配置
ai·claude·deepseek·authropic
YJlio11 小时前
OpenClaw v2026.4.24 更新了哪些内容?Google Meet、DeepSeek V4、实时语音与浏览器自动化深度解析
人工智能·开源项目·版本更新·ai agent·deepseek·openclaw·v4 自动化运维
maxmaxma1 天前
Claude Code集成DeepSeek-V4-pro全栈开发
claude·wsl·deepseek
sulikey1 天前
如何付费使用DeepSeek-V4满血版!包括DeepSeek官网与硅基流动平台教程!Cherry Studio使用教程!
教程·deepseek·cherry studio·deepseek v4·api接入·cherry教程
eastyuxiao1 天前
文心一言和DeepSeek V4哪个更好?
人工智能·大模型·文心一言·deepseek·deepseek-v4·deepseek‑v4