使用 Delphi 构建 AI 大模型 Agent
基本概念
Agent 是运行在本地电脑上的程序,允许大模型调用并执行代码。程序将执行结果反馈给大模型,使其能够理解上下文。
实现思路
AI 大模型的输入和输出均为字符串。聊天模式下人脑可理解 AI 输出,但 Delphi 程序需明确 AI 意图:如何识别调用的函数?如何执行该函数?
Delphi WebService 框架
WebService 底层基于 SOAP 调用,通讯协议为 XML 字符串。
测试验证
1. 构造 WebService 服务器端
使用 Delphi 创建 WebService 服务器端程序,接口定义如下:
type TMyArrayInt = Array Of Integer;
IIMyTest = interface(IInvokable)
['{10981E31-3C5C-4611-BB68-5964025D690F}']
function Hello(const S: string): string; stdcall;
procedure HelloWord(const S: string; var MyResult: string); stdcall;
function TestArray(A: TIntegerSOAPArray): TIntegerSOAPArray; stdcall;
function XPlusY(const X, Y: Integer): Integer; stdcall;
end;
聚焦 XPlusY 函数实现:
function TIMyTest.XPlusY(const X, Y: Integer): Integer;
begin
Result := X + Y;
end;
2. WebService 客户端验证
创建标准 WebService 客户端程序调用服务器 XPlusY 函数:
procedure TFmMain.Button3Click(Sender: TObject);
var Intf: IIMyTest; X, Y, Z: Integer;
begin
Intf := HTTPRIO1 as IIMyTest;
X := 10; Y := 33;
Z := Intf.XPlusY(X, Y);
ShowMessage(Z.ToString);
end;
运行后成功收到服务器返回结果(43)。
3. 拦截通讯内容
通过 HTTPRIO1.OnBeforeExecute 事件拦截请求内容:
procedure TFmMain.HTTPRIO1BeforeExecute(const MethodName: string; SOAPRequest: TStream);
var S: TStringStream; SS: string;
begin
S := TStringStream.Create;
try
SoapRequest.Position := 0;
S.CopyFrom(SoapRequest);
S.Position := 0;
SS := S.ReadString(S.Size);
Log(SS);
finally
S.Free;
end;
end;
拦截到的 SOAP 请求 XML 示例:
<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ...>
<SOAP-ENV:Body><NS1:XPlusY>1033

