秋·风

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
使用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 2025-02-15 19:24  秋·风  阅读(733)  评论(5)    收藏  举报