秋·风

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  276 随笔 :: 0 文章 :: 305 评论 :: 19万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
使用lazarus自带fphttpclient(注意:访问https要加opensslsockets这个单元)现实DeepSeek API的调用,Demo的代码只是简单使用API。

2025-02-19更新:
发现国内的大模型基本是兼容OpenAI的API,只需要更换一下就可以使用,如果使用kimi(moonshot)大模型,只需:
1、将model的deepseek-chat改为:moonshot-v1-8k
2、将https://api.deepseek.com/v1/chat/completions改为https://api.moonshot.cn/v1/chat/completions
3、使用kimi的APIKey(在这申请APIKey:Moonshot AI - 开放平台)

windows:
libeay32.dll 和 ssleay32.dll(注意区分64/32位的dll)放程序目录
Linux安装:
sudo apt-get install openssl libssl-dev

API详见:

首次调用 API | DeepSeek API Docs
注意:
先到DeepSeek 开放平台申请API Key

 直接上代码:

复制代码
unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, fphttpclient, fpjson,
  jsonparser, StdCtrls,opensslsockets;

type

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    Edit2: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
private

  public

  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);
var
  HttpClient: TFPHttpClient;
  RequestBody: TStringStream;
  Response: String;
  JSONRequest, JSONResponse: TJSONObject;
begin
  try
    // 初始化 HTTP 客户端
    HttpClient := TFPHttpClient.Create(nil);
    RequestBody := TStringStream.Create('', TEncoding.UTF8);
    JSONRequest := TJSONObject.Create;

    try
      // 构建请求 JSON
      JSONRequest.Add('model', 'deepseek-chat');
      JSONRequest.Add('stream', false);

      JSONRequest.Add('messages', TJSONArray.Create([
        TJSONObject.Create(['role', 'user', 'content', Edit2.Text])
      ]));
      JSONRequest.Add('temperature', 0.7);

      // 设置请求头和 URL
      HttpClient.AddHeader('Content-Type', 'application/json');
      HttpClient.AddHeader('Accept', 'application/json');
      HttpClient.AddHeader('Authorization','Bearer '+ Edit1.Text);
      RequestBody.WriteString(JSONRequest.AsJSON);
      HttpClient.RequestBody:=RequestBody;
      HttpClient.AllowRedirect := True;

      // 发送 POST 请求
      Response :=
      HttpClient.Post('https://api.deepseek.com/v1/chat/completions');

      // 解析响应
      JSONResponse := TJSONObject(GetJSON(Response));
      if JSONResponse<>nil then
      Memo1.Lines.Text := JSONResponse.GetPath('choices[0].message.content').AsString
      Else
       Memo1.Lines.Text:='调用失败';
    finally
      HttpClient.Free;
      RequestBody.Free;
      JSONRequest.Free;
      JSONResponse.Free;
    end;
  except
    on E: Exception do
      ShowMessage('请求失败: ' + E.Message);
  end;
end;

end.
复制代码

 

posted on   秋·风  阅读(179)  评论(5编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示