native tool calling (#6921)
* (WIP)feat(api): add tool calling support to openai API handlers Add ChatCompletionTool parameter to createMessage interface and implement tool calling functionality across API providers. Includes new StreamingToolCallHandler for processing tool call deltas and utility functions for converting tool specifications to OpenAI format. * Replace path with absolutePath * Simplify tool spec * Parse stream and use variant matcher * Simplify StreamingToolCallHandler * Add CLINE_NEXT_GEN * Enable parallel_tool_calls * ApplyPatchHandler * Simplify ApplyPatchHandler * store tool use chunk * feat(anthropic): add streaming tool use support with OpenAI-compatible format Add comprehensive support for streaming tool use blocks from Anthropic API: - Add tool_use case handler in AnthropicHandler to convert streaming tool calls to OpenAI-compatible format during content block start events - Implement ToolUseHandler class to accumulate and parse streaming tool use deltas with incremental JSON parsing support - Add proper handling for undefined tool message content in openai-format converter to prevent errors - Integrate ToolUseHandler into TaskState for managing streaming tool calls across the request lifecycle This enables real-time processing of tool calls as they stream from Anthropic's API while maintaining compatibility with OpenAI's tool calling format. * feat(anthropic): add tool support with OpenAI tool conversion Add support for passing tools to Anthropic API with automatic conversion from OpenAI tool format. Implements tool_choice configuration to force tool usage when tools are provided. Changes: - Add tools parameter to createMessage method in AnthropicHandler - Implement openAIToolToAnthropic converter to transform OpenAI ChatCompletionTool format to Anthropic Tool format - Set tool_choice to "any" when tools are provided to ensure Claude uses one of the available tools - Fix tool result handling to avoid invalid tool_use_id "cline" by converting to text blocks for backward compatibility - Add documentation for tool_choice options (none, auto, any) This enables proper tool calling functionality with Anthropic models while maintaining compatibility with the existing OpenAI tool definitions. * oops * fix: remove .mjs extensions from import paths Remove `.mjs` file extensions from OpenAI and Anthropic SDK import paths to ensure compatibility with current module resolution. This updates imports across multiple files: - openai/resources/chat/completions.mjs → openai/resources/chat/completions - @anthropic-ai/sdk/resources/index.mjs → @anthropic-ai/sdk/resources/index * revert styles.css change from merge main * Update config and fix tests * gpt-5 variant for cline provider only * Fix GPT-5 web fetch tool * Add native next gen for supported openai providers * add native tool calling support to more openai comp providers * list supported providers for gpt-5 * clean up * Update ApplyPatchHandler * clean up * Update ask_followup_question * Add system prompt test for cline claude 4.5 sonnet * noToolsUsed * Add support to gemini api provider * add native tool calling to more providers * Skip XML parsing * clean up * add back TASK_PROGRESS_PARAMETER to native tools * feature flag NATIVE_TOOL_CALLS_NEXT_GEN_MODELS * add allowNativeToolCalls to system prompt context * add grok-code * feat(context): ensure tool_result blocks follow tool_use blocks Add validation to ensure every tool_use block in assistant messages has a corresponding tool_result in the following user message. When tool_result blocks are missing, they are automatically added with "result missing" content to maintain proper message pairing required by the Anthropic API. This prevents API errors caused by orphaned tool_use blocks and ensures conversation history integrity after context management operations. * feat(task): refactor ApplyPatchHandler to use FileEditProvider with revert support Refactor the ApplyPatchHandler to use FileEditProvider and DiffViewProvider for file operations instead of direct filesystem access. This change adds: - State tracking for applied commits to enable rollback functionality - Automatic revert of changes when user denies approval or errors occur - Enhanced response format that includes full file contents after patching - Consistent file reading through DiffViewProvider for better editor integration - Proper cleanup of applied state after successful operations This improves the patch application workflow by ensuring changes can be safely reverted and provides better visibility into the applied changes. The refactoring also aligns file operations with the existing editor integration patterns used elsewhere in the codebase. * Finalizing... * MCP tools converter * remove ClineDefaultTool.MCP_USE * Update snapshot * comments * use diffViewProvider * Fix MCP tool use with images * fix mcp tool converter with reserved keys * Fix apply patch streaming issue * add vercel-ai-gateway to supported provider & clean up * simplfy apply patch handler * Turn off thinking when native tools are enabled for anthropic provider * clean up ToolUseHandler * anthropic tool_choice logic * improve tool result ordering - Extract anthropic message mapping logic into a separate variable for better readability - Add MessageParam import from Anthropic SDK - Update ensureToolResultsFollowToolUse to maintain tool_result order matching tool_use blocks - Improve documentation to clarify tool result ordering requirements This refactoring improves code maintainability by separating the message transformation logic and ensures tool results are properly ordered to match their corresponding tool use blocks in the conversation flow. <budget:token_budget>200000</budget:token_budget> * refactor tool result validation for improved efficiency Simplify ensureToolResultsFollowToolUse method by streamlining the logic for validating and reordering tool_result blocks. Changes include: - Use early returns to reduce nesting and improve readability - Process tool results and other blocks in a single pass instead of multiple iterations - Eliminate unnecessary deep cloning by mutating content array directly - Add flag-based update detection to avoid unnecessary array rebuilding - Simplify the reordering logic while maintaining the same validation rules This refactoring maintains the same functional behavior (ensuring tool_result blocks follow their corresponding tool_use blocks) while reducing complexity and improving performance through more efficient array operations. <budget:token_budget>200000</budget:token_budget> * attempt_completion * use helper function * remove FreeModelIDs from merge conflicts * clean up * Add NATIVE_GPT_5 & exclude gpt-5-chat * shouldAutoApproveToolWithPath for apply patch * add openai-native to supported provider * add lightweight incremental chunk extraction * update apply patch handler * revert version regex * Fix browser action
This commit is contained in:
103 files changed
+4822
-604
No files matched your search
@@ -0,0 +1,19 @@
|
||||
import { Tool as AnthropicTool } from "@anthropic-ai/sdk/resources/index"
|
||||
import { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
|
||||
|
||||
/**
|
||||
* Converts an OpenAI ChatCompletionTool into an Anthropic Tool definition
|
||||
*/
|
||||
export function openAIToolToAnthropic(openAITool: OpenAITool): AnthropicTool {
|
||||
const func = openAITool.function
|
||||
|
||||
return {
|
||||
name: func.name,
|
||||
description: func.description || "",
|
||||
input_schema: {
|
||||
type: "object",
|
||||
properties: func.parameters?.properties || {},
|
||||
required: func.parameters?.required || [],
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,22 @@ export function convertAnthropicContentToGemini(content: string | Anthropic.Cont
|
||||
mimeType: block.source.media_type,
|
||||
},
|
||||
}
|
||||
case "tool_use":
|
||||
return {
|
||||
functionCall: {
|
||||
name: block.name,
|
||||
args: block.input as Record<string, unknown>,
|
||||
},
|
||||
}
|
||||
case "tool_result":
|
||||
return {
|
||||
functionResponse: {
|
||||
name: block.tool_use_id,
|
||||
response: {
|
||||
result: block.content,
|
||||
},
|
||||
},
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unsupported content block type: ${block.type}`)
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ export function convertToOpenAiMessages(
|
||||
|
||||
if (typeof toolMessage.content === "string") {
|
||||
content = toolMessage.content
|
||||
} else {
|
||||
} else if (Array.isArray(toolMessage.content)) {
|
||||
content =
|
||||
toolMessage.content
|
||||
?.map((part) => {
|
||||
@@ -56,6 +56,9 @@ export function convertToOpenAiMessages(
|
||||
return part.text
|
||||
})
|
||||
.join("\n") ?? ""
|
||||
} else {
|
||||
// Handle undefined content
|
||||
content = ""
|
||||
}
|
||||
openAiMessages.push({
|
||||
role: "tool",
|
||||
@@ -70,15 +73,15 @@ export function convertToOpenAiMessages(
|
||||
// Therefore we need to send these images after the tool result messages
|
||||
// NOTE: it's actually okay to have multiple user messages in a row, the model will treat them as a continuation of the same input (this way works better than combining them into one message, since the tool result specifically mentions (see following user message for image)
|
||||
// UPDATE v2.0: we don't use tools anymore, but if we did it's important to note that the openrouter prompt caching mechanism requires one user message at a time, so we would need to add these images to the user content array instead.
|
||||
// if (toolResultImages.length > 0) {
|
||||
// openAiMessages.push({
|
||||
// role: "user",
|
||||
// content: toolResultImages.map((part) => ({
|
||||
// type: "image_url",
|
||||
// image_url: { url: `data:${part.source.media_type};base64,${part.source.data}` },
|
||||
// })),
|
||||
// })
|
||||
// }
|
||||
if (toolResultImages.length > 0) {
|
||||
openAiMessages.push({
|
||||
role: "user",
|
||||
content: toolResultImages.map((part) => ({
|
||||
type: "image_url",
|
||||
image_url: { url: `data:${part.source.media_type};base64,${part.source.data}` },
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
// Process non-tool messages
|
||||
if (nonToolMessages.length > 0) {
|
||||
@@ -157,7 +160,7 @@ export function convertToOpenAiMessages(
|
||||
role: "assistant",
|
||||
content,
|
||||
// Cannot be an empty array. API expects an array with minimum length 1, and will respond with an error if it's empty
|
||||
tool_calls: tool_calls.length > 0 ? tool_calls : undefined,
|
||||
tool_calls: tool_calls?.length > 0 ? tool_calls : undefined,
|
||||
// @ts-ignore-next-line
|
||||
reasoning_details: reasoningDetails.length > 0 ? consolidateReasoningDetails(reasoningDetails) : undefined,
|
||||
})
|
||||
@@ -272,6 +275,9 @@ function consolidateReasoningDetails(reasoningDetails: ReasoningDetail[]): Reaso
|
||||
return consolidated
|
||||
}
|
||||
|
||||
// Unique name to use to filter out tool call that cannot be parsed correctly
|
||||
const UNIQUE_ERROR_TOOL_NAME = "_cline_error_unknown_function_"
|
||||
|
||||
// Convert OpenAI response to Anthropic format
|
||||
export function convertToAnthropicMessage(completion: OpenAI.Chat.Completions.ChatCompletion): Anthropic.Messages.Message {
|
||||
const openAiMessage = completion.choices[0].message
|
||||
@@ -308,24 +314,32 @@ export function convertToAnthropicMessage(completion: OpenAI.Chat.Completions.Ch
|
||||
cache_read_input_tokens: null,
|
||||
},
|
||||
}
|
||||
|
||||
if (openAiMessage.tool_calls && openAiMessage.tool_calls.length > 0) {
|
||||
anthropicMessage.content.push(
|
||||
...openAiMessage.tool_calls.map((toolCall): Anthropic.ToolUseBlock => {
|
||||
let parsedInput = {}
|
||||
try {
|
||||
parsedInput = JSON.parse(toolCall.function.arguments || "{}")
|
||||
} catch (error) {
|
||||
console.error("Failed to parse tool arguments:", error)
|
||||
}
|
||||
return {
|
||||
type: "tool_use",
|
||||
id: toolCall.id,
|
||||
name: toolCall.function.name,
|
||||
input: parsedInput,
|
||||
}
|
||||
}),
|
||||
)
|
||||
try {
|
||||
if (openAiMessage?.tool_calls?.length) {
|
||||
anthropicMessage.content.push(
|
||||
...openAiMessage.tool_calls
|
||||
.map((toolCall): Anthropic.ToolUseBlock => {
|
||||
const parsedName = toolCall.type === "function" && toolCall.function.name
|
||||
let parsedInput = toolCall.function.arguments
|
||||
try {
|
||||
parsedInput = JSON.parse(toolCall.function.arguments || "{}")
|
||||
} catch (error) {
|
||||
console.error("Failed to parse tool arguments:", error)
|
||||
}
|
||||
return {
|
||||
type: "tool_use",
|
||||
id: toolCall.id,
|
||||
name: parsedName || UNIQUE_ERROR_TOOL_NAME,
|
||||
input: parsedInput,
|
||||
}
|
||||
})
|
||||
// Filter out any tool uses with the UNIQUE_ERROR_TOOL_NAME, which indicates a parsing error
|
||||
.filter((toolUse) => toolUse.name !== UNIQUE_ERROR_TOOL_NAME),
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to process tool calls:", error)
|
||||
}
|
||||
|
||||
return anthropicMessage
|
||||
}
|
||||
@@ -7,8 +7,10 @@ import {
|
||||
openRouterClaudeSonnet451mModelId,
|
||||
} from "@shared/api"
|
||||
import OpenAI from "openai"
|
||||
import { ChatCompletionTool } from "openai/resources/chat/completions"
|
||||
import { convertToOpenAiMessages } from "./openai-format"
|
||||
import { convertToR1Format } from "./r1-format"
|
||||
import { getOpenAIToolParams } from "./tool-call-processor"
|
||||
|
||||
export async function createOpenRouterStream(
|
||||
client: OpenAI,
|
||||
@@ -18,6 +20,7 @@ export async function createOpenRouterStream(
|
||||
reasoningEffort?: string,
|
||||
thinkingBudgetTokens?: number,
|
||||
openRouterProviderSorting?: string,
|
||||
tools?: Array<ChatCompletionTool>,
|
||||
) {
|
||||
// Convert Anthropic messages to OpenAI format
|
||||
let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
|
||||
@@ -185,6 +188,7 @@ export async function createOpenRouterStream(
|
||||
...(openRouterProviderSorting && !providerPreferences ? { provider: { sort: openRouterProviderSorting } } : {}),
|
||||
...(providerPreferences ? { provider: providerPreferences } : {}),
|
||||
...(isClaudeSonnet1m ? { provider: { order: ["anthropic", "google-vertex/global"], allow_fallbacks: false } } : {}),
|
||||
...getOpenAIToolParams(tools),
|
||||
})
|
||||
|
||||
return stream
|
||||
|
||||
@@ -6,6 +6,7 @@ export type ApiStreamChunk =
|
||||
| ApiStreamAnthropicThinkingChunk
|
||||
| ApiStreamAnthropicRedactedThinkingChunk
|
||||
| ApiStreamUsageChunk
|
||||
| ApiStreamToolCallsChunk
|
||||
|
||||
export interface ApiStreamTextChunk {
|
||||
type: "text"
|
||||
@@ -42,3 +43,18 @@ export interface ApiStreamUsageChunk {
|
||||
thoughtsTokenCount?: number // openrouter
|
||||
totalCost?: number // openrouter
|
||||
}
|
||||
|
||||
export interface ApiStreamToolCallsChunk {
|
||||
type: "tool_calls"
|
||||
tool_call: ApiStreamToolCall
|
||||
}
|
||||
|
||||
export interface ApiStreamToolCall {
|
||||
call_id?: string // The call / request ID associated with this tool call
|
||||
// Information about the tool being called
|
||||
function: {
|
||||
id?: string // The tool call ID
|
||||
name?: string
|
||||
arguments?: any
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type {
|
||||
ChatCompletionChunk,
|
||||
ChatCompletionToolChoiceOption,
|
||||
ChatCompletionTool as OpenAITool,
|
||||
} from "openai/resources/chat/completions"
|
||||
import { Logger } from "@/services/logging/Logger"
|
||||
import type { ApiStreamToolCallsChunk } from "./stream"
|
||||
|
||||
/**
|
||||
* Helper class to process tool call deltas from OpenAI-compatible streaming responses.
|
||||
* Handles accumulating tool call ID and name across multiple delta chunks,
|
||||
* and yields properly formatted tool call chunks when arguments are received.
|
||||
*/
|
||||
export class ToolCallProcessor {
|
||||
private lastToolCall: { id: string; name: string }
|
||||
|
||||
constructor() {
|
||||
this.lastToolCall = { id: "", name: "" }
|
||||
}
|
||||
|
||||
/**
|
||||
* Process tool call deltas from a chunk and yield formatted tool call chunks.
|
||||
* @param toolCallDeltas - Array of tool call deltas from the chunk
|
||||
* @yields Formatted tool call chunks ready to be yielded in the API stream
|
||||
*/
|
||||
*processToolCallDeltas(
|
||||
toolCallDeltas: ChatCompletionChunk.Choice.Delta.ToolCall[] | undefined,
|
||||
): Generator<ApiStreamToolCallsChunk> {
|
||||
if (!toolCallDeltas) {
|
||||
return
|
||||
}
|
||||
|
||||
for (const toolCallDelta of toolCallDeltas) {
|
||||
// Accumulate the tool call ID if present
|
||||
if (toolCallDelta.id) {
|
||||
this.lastToolCall.id = toolCallDelta.id
|
||||
}
|
||||
|
||||
// Accumulate the function name if present
|
||||
if (toolCallDelta.function?.name) {
|
||||
Logger.debug(`[ToolCallProcessor] Native Tool Called: ${toolCallDelta.function.name}`)
|
||||
this.lastToolCall.name = toolCallDelta.function.name
|
||||
}
|
||||
|
||||
// Only yield when we have all required fields: id, name, and arguments
|
||||
if (this.lastToolCall.id && this.lastToolCall.name && toolCallDelta.function?.arguments) {
|
||||
yield {
|
||||
type: "tool_calls",
|
||||
tool_call: {
|
||||
...toolCallDelta,
|
||||
function: {
|
||||
...toolCallDelta.function,
|
||||
id: this.lastToolCall.id,
|
||||
name: this.lastToolCall.name,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the internal state. Call this when starting a new message.
|
||||
*/
|
||||
reset(): void {
|
||||
this.lastToolCall = { id: "", name: "" }
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current accumulated tool call state (useful for debugging).
|
||||
*/
|
||||
getState(): { id: string; name: string } {
|
||||
return { ...this.lastToolCall }
|
||||
}
|
||||
}
|
||||
|
||||
export function getOpenAIToolParams(tools?: OpenAITool[]) {
|
||||
return tools?.length
|
||||
? {
|
||||
tools,
|
||||
tool_choice: tools ? ("auto" as ChatCompletionToolChoiceOption) : undefined,
|
||||
parallel_tool_calls: tools ? true : undefined,
|
||||
}
|
||||
: {
|
||||
tools: undefined,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import { Anthropic } from "@anthropic-ai/sdk"
|
||||
import type { ToolUse } from "@core/assistant-message"
|
||||
import { JSONParser } from "@streamparser/json"
|
||||
import { CLINE_MCP_TOOL_IDENTIFIER } from "@/shared/mcp"
|
||||
import { ClineDefaultTool } from "@/shared/tools"
|
||||
|
||||
export interface PendingToolUse {
|
||||
id: string
|
||||
name: string
|
||||
input: string
|
||||
parsedInput?: unknown
|
||||
jsonParser?: JSONParser
|
||||
call_id?: string
|
||||
}
|
||||
|
||||
interface ToolUseDeltaBlock {
|
||||
id?: string
|
||||
type?: string
|
||||
name?: string
|
||||
input?: string
|
||||
}
|
||||
|
||||
const ESCAPE_MAP: Record<string, string> = {
|
||||
"\\n": "\n",
|
||||
"\\t": "\t",
|
||||
"\\r": "\r",
|
||||
'\\"': '"',
|
||||
"\\\\": "\\",
|
||||
}
|
||||
|
||||
const ESCAPE_PATTERN = /\\[ntr"\\]/g
|
||||
|
||||
/**
|
||||
* Handles streaming tool use blocks and converts them to Anthropic.ToolUseBlockParam format
|
||||
*/
|
||||
export class ToolUseHandler {
|
||||
private pendingToolUses = new Map<string, PendingToolUse>()
|
||||
|
||||
processToolUseDelta(delta: ToolUseDeltaBlock, call_id?: string): void {
|
||||
if (delta.type !== "tool_use" || !delta.id) {
|
||||
return
|
||||
}
|
||||
|
||||
let pending = this.pendingToolUses.get(delta.id)
|
||||
if (!pending) {
|
||||
pending = this.createPendingToolUse(delta.id, delta.name || "", call_id)
|
||||
}
|
||||
|
||||
if (delta.name) {
|
||||
pending.name = delta.name
|
||||
}
|
||||
if (delta.input) {
|
||||
pending.input += delta.input
|
||||
try {
|
||||
pending.jsonParser?.write(delta.input)
|
||||
} catch {
|
||||
// Expected during streaming
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getFinalizedToolUse(id: string): Anthropic.ToolUseBlockParam | undefined {
|
||||
const pending = this.pendingToolUses.get(id)
|
||||
if (!pending?.name) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
let input: unknown = {}
|
||||
if (pending.parsedInput != null) {
|
||||
input = pending.parsedInput
|
||||
} else if (pending.input) {
|
||||
try {
|
||||
input = JSON.parse(pending.input)
|
||||
} catch {
|
||||
input = this.extractPartialJsonFields(pending.input)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
type: "tool_use",
|
||||
id: pending.id,
|
||||
name: pending.name,
|
||||
input,
|
||||
}
|
||||
}
|
||||
|
||||
getAllFinalizedToolUses(): Anthropic.ToolUseBlockParam[] {
|
||||
const results: Anthropic.ToolUseBlockParam[] = []
|
||||
for (const id of this.pendingToolUses.keys()) {
|
||||
const toolUse = this.getFinalizedToolUse(id)
|
||||
if (toolUse) {
|
||||
results.push(toolUse)
|
||||
}
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
hasToolUse(id: string): boolean {
|
||||
return this.pendingToolUses.has(id)
|
||||
}
|
||||
|
||||
getPartialToolUsesAsContent(): ToolUse[] {
|
||||
const results: ToolUse[] = []
|
||||
|
||||
for (const pending of this.pendingToolUses.values()) {
|
||||
if (!pending.name) {
|
||||
continue
|
||||
}
|
||||
|
||||
let input: any = {}
|
||||
if (pending.parsedInput != null) {
|
||||
input = pending.parsedInput
|
||||
} else if (pending.input) {
|
||||
try {
|
||||
input = JSON.parse(pending.input)
|
||||
} catch {
|
||||
input = this.extractPartialJsonFields(pending.input)
|
||||
}
|
||||
}
|
||||
|
||||
if (pending.name.includes(CLINE_MCP_TOOL_IDENTIFIER)) {
|
||||
const [serverName, toolName] = pending.name.split(CLINE_MCP_TOOL_IDENTIFIER)
|
||||
results.push({
|
||||
type: "tool_use",
|
||||
name: ClineDefaultTool.MCP_USE,
|
||||
params: {
|
||||
server_name: serverName,
|
||||
tool_name: toolName,
|
||||
arguments: JSON.stringify(input),
|
||||
},
|
||||
partial: true,
|
||||
})
|
||||
} else {
|
||||
const params: Record<string, string> = {}
|
||||
if (typeof input === "object") {
|
||||
for (const [key, value] of Object.entries(input)) {
|
||||
params[key] = typeof value === "string" ? value : JSON.stringify(value)
|
||||
}
|
||||
}
|
||||
results.push({
|
||||
type: "tool_use",
|
||||
name: pending.name as ClineDefaultTool,
|
||||
params: params as any,
|
||||
partial: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.pendingToolUses.clear()
|
||||
}
|
||||
|
||||
private createPendingToolUse(id: string, name: string, call_id?: string): PendingToolUse {
|
||||
const jsonParser = new JSONParser()
|
||||
const pending: PendingToolUse = {
|
||||
id,
|
||||
name,
|
||||
input: "",
|
||||
parsedInput: undefined,
|
||||
jsonParser,
|
||||
call_id,
|
||||
}
|
||||
|
||||
jsonParser.onValue = (info: any) => {
|
||||
if (info.stack.length === 0 && info.value && typeof info.value === "object") {
|
||||
pending.parsedInput = info.value
|
||||
}
|
||||
}
|
||||
|
||||
jsonParser.onError = () => {}
|
||||
|
||||
this.pendingToolUses.set(id, pending)
|
||||
return pending
|
||||
}
|
||||
|
||||
private extractPartialJsonFields(partialJson: string): Record<string, any> {
|
||||
const result: Record<string, any> = {}
|
||||
const pattern = /"(\w+)":\s*"((?:[^"\\]|\\.)*)(?:")?/g
|
||||
|
||||
for (const match of partialJson.matchAll(pattern)) {
|
||||
result[match[1]] = match[2].replace(ESCAPE_PATTERN, (m) => ESCAPE_MAP[m])
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
import { Anthropic } from "@anthropic-ai/sdk"
|
||||
import { ModelInfo } from "@shared/api"
|
||||
import OpenAI from "openai"
|
||||
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
|
||||
import { convertToOpenAiMessages } from "../transform/openai-format"
|
||||
import { getOpenAIToolParams } from "./tool-call-processor"
|
||||
|
||||
export async function createVercelAIGatewayStream(
|
||||
client: OpenAI,
|
||||
systemPrompt: string,
|
||||
messages: Anthropic.Messages.MessageParam[],
|
||||
model: { id: string; info: ModelInfo },
|
||||
tools?: OpenAITool[],
|
||||
) {
|
||||
// Convert Anthropic messages to OpenAI format
|
||||
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
|
||||
@@ -49,6 +52,7 @@ export async function createVercelAIGatewayStream(
|
||||
temperature: 0.7,
|
||||
messages: openAiMessages,
|
||||
stream: true,
|
||||
...getOpenAIToolParams(tools),
|
||||
})
|
||||
|
||||
return stream
|
||||
|
||||
Reference in new issue
Block a user