首先,去阿里百炼官网,去申请一个 API KEY。
然后,在 Delphi 里面创建一个新的 VCL 工程。拖一个 TNetHTTPClient 控件到页面上,用它来执行 http post 去访问阿里大模型。
以下是代码:
代码一:保证多线程底下输出日志到 TMemo:
procedure TForm1.Log(const S: string);
begin
if GetCurrentThreadId = MainThreadID then
begin
// 已经在主线程,直接执行
Memo1.Lines.Add(S);
end
else
begin
// 在后台线程,通过队列调用
TThread.Queue(nil,
procedure
begin
Memo1.Lines.Add(S);
end
);
end;
end;
代码二,使用 TNetHTTPClient 去访问 AP
procedure TForm1.CahtQWen;
var
S, URL, Response: string;
Prompt: UTF8String;
AResponseContent, SrcContent: TStringStream;
begin
//以下代码,测试通过
URL := 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions';
S := '{"model": "qwen-plus", "messages": [{"role": "user", "content": "你好, 你是谁?"}]}';
Prompt := UTF8Encode(S);
SrcContent := TStringStream.Create(Prompt, TEncoding.UTF8);
AResponseContent := TStringStream.Create('', TEncoding.UTF8);
NetHTTPClient1.CustomHeaders['Authorization'] := 'Bearer sk-ws-H.RPXYRIH.ndo1.MEUCICsx9FbzZrsDxZn-tyxxx...xx..xx...';
NetHTTPClient1.ContentType := 'application/json';
TTask.Run(
procedure
begin
NetHTTPClient1.Post(URL, SrcContent, AResponseContent);
Response := AResponseContent.DataString;
Log(Response);
Log('结束!');
end
);
end;
上述代码需要注意的地方是:
1. NetHTTPClient1.CustomHeaders 这一行,把 API KEY 写进去。注意 API KEY 字符串前面需要多一个 Bearer 单词。
2. 注意 URL,这个 URL 是阿里官方大模型的访问地址。
3. 注意 model 的名字。阿里大模型有好多种不同的模型,有不同的名称,看你想用哪个。
上述代码执行结果:
{"model":"qwen-plus","id":"chatcmpl-9b2f1fbd-597e-9852-88b0-2d40bb79770b","choices":[{"message":{"content":"你好!我是通义千问(Qwen),阿里巴巴集团旗下的超大规模语言模型。我可以回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!😊","role":"assistant"},"index":0,"finish_reason":"stop"}],"created":1782229447,"object":"chat.completion","usage":{"total_tokens":79,"completion_tokens":65,"prompt_tokens":14,"prompt_tokens_details":{"cached_tokens":0}}}
721

被折叠的 条评论
为什么被折叠?



