feat: add support for Claude 3 tool use (function calling) #1587
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
close #1572, close #1258, close #1504, close #1299, close #1374, close #1520 (claude)
我已确认该 PR 已自测通过,相关截图如下:
分叉情况
在流式消息下存在一些与 OpenAI 分叉的情况
为了便于理解这些差异,以下引用了来自 Claude 官方文档中的流式工具使用响应示例:https://docs.anthropic.com/en/api/messages-streaming#streaming-request-with-tool-use
Arguments 为空
Claude Request Body:
Claude Response:
OpenAI Request Body:
OpenAI Response:
在 OpenAI 流式函数调用 没有 arguments 的情况下,会响应一个
{}
,在 Claude 流式中则 什么都不响应 (经过请求测试content_block_delta
第一个partial_json
始终为""
,content_block_start
tool_use
的input
始终为{}
)commit d16cd615 针对这一情况,当
finish_reason
时,且arguments
为空的情况下,添加一个{}
以便更好地与 OpenAI 的行为保持一致,兼容一些应用 (如 LobeChat,若不添加{}
则无法调用时钟时间)多余的响应
Claude 在流式响应中包含了
ping
,content_block_stop
,message_stop
等事件,这可能导致流式传输中出现额外输出。尽管在 LobeChat 的测试中,这些多余的输出并未对函数调用的使用造成影响,但仍可以 由社区讨论确定是否有必要通过过滤逻辑来去除这些额外响应,尤其是当它们开始干扰某些应用功能使用时已知的问题
在进行请求转换 (
ConvertRequest
) 时,Claude 的role
枚举仅能包含user
,assistant
refer: https://docs.anthropic.com/en/api/messages然而 OpenAI 使用 role
tool
传递函数调用的结果给模型 refer: https://platform.openai.com/docs/guides/function-callingClaude 通过
user
来传递tool_result
refer: https://docs.anthropic.com/en/docs/build-with-claude/tool-use#handling-tool-use-and-tool-result-content-blocks同时 Claude 中 role 需要交替组合,以 LobeChat 的时钟时间调用为例
Request Body:
在 convert 后,
tool
会被替换为user
此时出现了连续多个
role
为user
的情况,报错由于客户端侧的情况复杂多样,如果在服务端中重新 convert 请求,可能会引发更多的问题
考虑到函数调用主要是为了向模型提供外部结果,增强其能力和扩展应用场景,对函数调用结果不包含
AI-generated content
属于边缘情形,只会影响特定场景下的使用该已知问题与 #1135 #1187 相关