如何阻止Semantic Kernel函数自动填充未指定参数?
解决Semantic Kernel + ChatGPT-4自动填充可选函数参数的问题
以下是几种可行的解决方案:
- 明确参数元数据约束:修改
Subject参数的描述,清晰告知模型该参数为可选,未指定时必须留空,禁止自动生成内容:
[KernelFunction, Description("Send an email")] public async Task<bool> SendMessage( [Description("Email address")] EmailAddress EmailAddress, [Description("Content of the email")] string Content, [Description("Subject of email (optional: do NOT auto-generate if user doesn't specify, keep null)")] string? Subject) { var newMssage = new Services.Mailbox.Message() { RecipientEmailAddress = EmailAddress, Read = false, Content = Content, Subject = Subject , }; var response = await MessageService.Save(User.Identity, newMssage); return response; }
- 配置Kernel的严格参数绑定:在注册插件或调用函数时,强制模型遵循可选参数的规则,不自动填充未指定的参数。可以通过调整函数元数据的设置实现:
// 注册插件后获取目标函数 var emailPlugin = kernel.Plugins.AddFromType<YourEmailServiceClass>(); var sendMessageFunc = emailPlugin["SendMessage"]; // 明确标记Subject为非必填,且禁止自动填充 sendMessageFunc.Metadata.Parameters["Subject"].IsRequired = false; sendMessageFunc.Metadata.Parameters["Subject"].Description += " - Do NOT provide a value if user hasn't mentioned it explicitly.";
- 添加参数预处理逻辑:在调用函数前,根据用户输入判断是否需要填充
Subject,若用户未提及任何主题相关内容,则主动移除该参数,确保模型不会生成默认值:
// 假设userInput是原始用户输入内容 var args = new KernelArguments { ["EmailAddress"] = userProvidedEmail, ["Content"] = userProvidedContent }; // 检查用户输入是否包含主题相关关键词,未包含则不设置Subject if (!userInput.Contains("主题", StringComparison.OrdinalIgnoreCase) && !userInput.Contains("subject", StringComparison.OrdinalIgnoreCase)) { args.Remove("Subject"); } // 调用函数 var result = await kernel.InvokeAsync(sendMessageFunc, args);
- 强化系统提示词规则:更新ChatGPT-4的系统提示,明确函数调用的参数规则,比如:
调用函数时,所有标记为可选的参数,若用户未提供任何相关信息,必须保持为null,绝对不能自动生成内容填充。仅当用户明确提及该参数的内容时,才进行赋值。
内容的提问来源于stack exchange,提问作者FriedBrain
相关产品推荐
相关产品推荐

