mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 00:03:13 +03:00
refactor(core): remove unused code from the vendored Copilot provider (#61165)
This commit is contained in:
committed by
GitHub
Unverified
parent
06cd1a3eda
commit
bbd08b61de
@@ -20,6 +20,8 @@ preserve the intentional Copilot adaptations: the `copilot` options and metadata
|
||||
namespace, `thinking_budget`, reasoning text and opaque reasoning, stateless
|
||||
Responses requests with encrypted reasoning, rotating response item IDs, and
|
||||
explicit function-tool strictness taking precedence over the global fallback.
|
||||
Paths OpenCode never calls are trimmed: models only stream (`doGenerate`
|
||||
throws), and hosted tools keep only their schemas, not the tool factories.
|
||||
|
||||
`copilot-provider.ts` is the local adapter assembly entrypoint used by
|
||||
`plugin/provider/github-copilot.ts`. `models.ts` is OpenCode-owned catalog
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
InvalidResponseDataError,
|
||||
type LanguageModelV3,
|
||||
type LanguageModelV3CallOptions,
|
||||
type LanguageModelV3Content,
|
||||
type LanguageModelV3StreamPart,
|
||||
type SharedV3ProviderMetadata,
|
||||
type SharedV3Warning,
|
||||
@@ -12,7 +11,6 @@ import {
|
||||
combineHeaders,
|
||||
createEventSourceResponseHandler,
|
||||
createJsonErrorResponseHandler,
|
||||
createJsonResponseHandler,
|
||||
type FetchFunction,
|
||||
generateId,
|
||||
isParsableJson,
|
||||
@@ -189,117 +187,8 @@ export class OpenAICompatibleChatLanguageModel implements LanguageModelV3 {
|
||||
}
|
||||
}
|
||||
|
||||
async doGenerate(options: LanguageModelV3CallOptions) {
|
||||
const { args, warnings } = await this.getArgs({ ...options })
|
||||
|
||||
const body = JSON.stringify(args)
|
||||
|
||||
const {
|
||||
responseHeaders,
|
||||
value: responseBody,
|
||||
rawValue: rawResponse,
|
||||
} = await postJsonToApi({
|
||||
url: this.config.url({
|
||||
path: "/chat/completions",
|
||||
modelId: this.modelId,
|
||||
}),
|
||||
headers: combineHeaders(this.config.headers(), options.headers),
|
||||
body: args,
|
||||
failedResponseHandler: this.failedResponseHandler,
|
||||
successfulResponseHandler: createJsonResponseHandler(OpenAICompatibleChatResponseSchema),
|
||||
abortSignal: options.abortSignal,
|
||||
fetch: this.config.fetch,
|
||||
})
|
||||
|
||||
const choice = responseBody.choices[0]
|
||||
const content: Array<LanguageModelV3Content> = []
|
||||
|
||||
// text content:
|
||||
const text = choice.message.content
|
||||
if (text != null && text.length > 0) {
|
||||
content.push({
|
||||
type: "text",
|
||||
text,
|
||||
providerMetadata: choice.message.reasoning_opaque
|
||||
? { copilot: { reasoningOpaque: choice.message.reasoning_opaque } }
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
|
||||
// reasoning content (Copilot uses reasoning_text):
|
||||
const reasoning = choice.message.reasoning_text
|
||||
if (reasoning != null && reasoning.length > 0) {
|
||||
content.push({
|
||||
type: "reasoning",
|
||||
text: reasoning,
|
||||
// Include reasoning_opaque for Copilot multi-turn reasoning
|
||||
providerMetadata: choice.message.reasoning_opaque
|
||||
? { copilot: { reasoningOpaque: choice.message.reasoning_opaque } }
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
|
||||
// tool calls:
|
||||
if (choice.message.tool_calls != null) {
|
||||
for (const toolCall of choice.message.tool_calls) {
|
||||
content.push({
|
||||
type: "tool-call",
|
||||
toolCallId: toolCall.id ?? generateId(),
|
||||
toolName: toolCall.function.name,
|
||||
input: toolCall.function.arguments!,
|
||||
providerMetadata: choice.message.reasoning_opaque
|
||||
? { copilot: { reasoningOpaque: choice.message.reasoning_opaque } }
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// provider metadata:
|
||||
const providerMetadata: SharedV3ProviderMetadata = {
|
||||
[this.providerOptionsName]: {},
|
||||
...(await this.config.metadataExtractor?.extractMetadata?.({
|
||||
parsedBody: rawResponse,
|
||||
})),
|
||||
}
|
||||
const completionTokenDetails = responseBody.usage?.completion_tokens_details
|
||||
if (completionTokenDetails?.accepted_prediction_tokens != null) {
|
||||
providerMetadata[this.providerOptionsName].acceptedPredictionTokens =
|
||||
completionTokenDetails?.accepted_prediction_tokens
|
||||
}
|
||||
if (completionTokenDetails?.rejected_prediction_tokens != null) {
|
||||
providerMetadata[this.providerOptionsName].rejectedPredictionTokens =
|
||||
completionTokenDetails?.rejected_prediction_tokens
|
||||
}
|
||||
|
||||
return {
|
||||
content,
|
||||
finishReason: {
|
||||
unified: mapOpenAICompatibleFinishReason(choice.finish_reason),
|
||||
raw: choice.finish_reason ?? undefined,
|
||||
},
|
||||
usage: {
|
||||
inputTokens: {
|
||||
total: responseBody.usage?.prompt_tokens ?? undefined,
|
||||
noCache: undefined,
|
||||
cacheRead: responseBody.usage?.prompt_tokens_details?.cached_tokens ?? undefined,
|
||||
cacheWrite: undefined,
|
||||
},
|
||||
outputTokens: {
|
||||
total: responseBody.usage?.completion_tokens ?? undefined,
|
||||
text: undefined,
|
||||
reasoning: responseBody.usage?.completion_tokens_details?.reasoning_tokens ?? undefined,
|
||||
},
|
||||
raw: responseBody.usage ?? undefined,
|
||||
},
|
||||
providerMetadata,
|
||||
request: { body },
|
||||
response: {
|
||||
...getResponseMetadata(responseBody),
|
||||
headers: responseHeaders,
|
||||
body: rawResponse,
|
||||
},
|
||||
warnings,
|
||||
}
|
||||
async doGenerate(_options: LanguageModelV3CallOptions): Promise<never> {
|
||||
throw new Error("GitHub Copilot models only support streaming")
|
||||
}
|
||||
|
||||
async doStream(options: LanguageModelV3CallOptions) {
|
||||
@@ -737,38 +626,6 @@ const openaiCompatibleTokenUsageSchema = z
|
||||
})
|
||||
.nullish()
|
||||
|
||||
// limited version of the schema, focussed on what is needed for the implementation
|
||||
// this approach limits breakages when the API changes and increases efficiency
|
||||
const OpenAICompatibleChatResponseSchema = z.object({
|
||||
id: z.string().nullish(),
|
||||
created: z.number().nullish(),
|
||||
model: z.string().nullish(),
|
||||
choices: z.array(
|
||||
z.object({
|
||||
message: z.object({
|
||||
role: z.literal("assistant").nullish(),
|
||||
content: z.string().nullish(),
|
||||
// Copilot-specific reasoning fields
|
||||
reasoning_text: z.string().nullish(),
|
||||
reasoning_opaque: z.string().nullish(),
|
||||
tool_calls: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string().nullish(),
|
||||
function: z.object({
|
||||
name: z.string(),
|
||||
arguments: z.string(),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
.nullish(),
|
||||
}),
|
||||
finish_reason: z.string().nullish(),
|
||||
}),
|
||||
),
|
||||
usage: openaiCompatibleTokenUsageSchema,
|
||||
})
|
||||
|
||||
// limited version of the schema, focussed on what is needed for the implementation
|
||||
// this approach limits breakages when the API changes and increases efficiency
|
||||
const createOpenAICompatibleChatChunkSchema = <ERROR_SCHEMA extends z.core.$ZodType>(errorSchema: ERROR_SCHEMA) =>
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import {
|
||||
APICallError,
|
||||
type JSONValue,
|
||||
type LanguageModelV3,
|
||||
type LanguageModelV3CallOptions,
|
||||
type LanguageModelV3Content,
|
||||
type LanguageModelV3StreamPart,
|
||||
type SharedV3ProviderMetadata,
|
||||
type SharedV3Warning,
|
||||
@@ -11,7 +9,6 @@ import {
|
||||
import {
|
||||
combineHeaders,
|
||||
createEventSourceResponseHandler,
|
||||
createJsonResponseHandler,
|
||||
generateId,
|
||||
parseProviderOptions,
|
||||
type ParseResult,
|
||||
@@ -308,371 +305,8 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
|
||||
}
|
||||
}
|
||||
|
||||
async doGenerate(options: LanguageModelV3CallOptions) {
|
||||
const { args: body, warnings, getHostedToolName } = await this.getArgs(options)
|
||||
const url = this.config.url({
|
||||
path: "/responses",
|
||||
modelId: this.modelId,
|
||||
})
|
||||
|
||||
const {
|
||||
responseHeaders,
|
||||
value: response,
|
||||
rawValue: rawResponse,
|
||||
} = await postJsonToApi({
|
||||
url,
|
||||
headers: combineHeaders(this.config.headers(), options.headers),
|
||||
body,
|
||||
failedResponseHandler: openaiFailedResponseHandler,
|
||||
successfulResponseHandler: createJsonResponseHandler(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
created_at: z.number(),
|
||||
error: z
|
||||
.object({
|
||||
code: z.string(),
|
||||
message: z.string(),
|
||||
})
|
||||
.nullish(),
|
||||
model: z.string(),
|
||||
output: z.array(
|
||||
z.discriminatedUnion("type", [
|
||||
z.object({
|
||||
type: z.literal("message"),
|
||||
role: z.literal("assistant"),
|
||||
id: z.string(),
|
||||
content: z.array(
|
||||
z.object({
|
||||
type: z.literal("output_text"),
|
||||
text: z.string(),
|
||||
logprobs: LOGPROBS_SCHEMA.nullish(),
|
||||
annotations: z.array(
|
||||
z.discriminatedUnion("type", [
|
||||
z.object({
|
||||
type: z.literal("url_citation"),
|
||||
start_index: z.number(),
|
||||
end_index: z.number(),
|
||||
url: z.string(),
|
||||
title: z.string(),
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal("file_citation"),
|
||||
file_id: z.string(),
|
||||
filename: z.string().nullish(),
|
||||
index: z.number().nullish(),
|
||||
start_index: z.number().nullish(),
|
||||
end_index: z.number().nullish(),
|
||||
quote: z.string().nullish(),
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal("container_file_citation"),
|
||||
}),
|
||||
]),
|
||||
),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
webSearchCallItem,
|
||||
fileSearchCallItem,
|
||||
codeInterpreterCallItem,
|
||||
imageGenerationCallItem,
|
||||
z.object({
|
||||
type: z.literal("function_call"),
|
||||
call_id: z.string(),
|
||||
name: z.string(),
|
||||
arguments: z.string(),
|
||||
id: z.string(),
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal("computer_call"),
|
||||
id: z.string(),
|
||||
status: z.string().optional(),
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal("reasoning"),
|
||||
id: z.string(),
|
||||
encrypted_content: z.string().nullish(),
|
||||
summary: z.array(
|
||||
z.object({
|
||||
type: z.literal("summary_text"),
|
||||
text: z.string(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]),
|
||||
),
|
||||
service_tier: z.string().nullish(),
|
||||
incomplete_details: z.object({ reason: z.string() }).nullish(),
|
||||
usage: usageSchema,
|
||||
}),
|
||||
),
|
||||
abortSignal: options.abortSignal,
|
||||
fetch: this.config.fetch,
|
||||
})
|
||||
|
||||
if (response.error) {
|
||||
throw new APICallError({
|
||||
message: response.error.message,
|
||||
url,
|
||||
requestBodyValues: body,
|
||||
statusCode: 400,
|
||||
responseHeaders,
|
||||
responseBody: rawResponse as string,
|
||||
isRetryable: false,
|
||||
})
|
||||
}
|
||||
|
||||
const content: Array<LanguageModelV3Content> = []
|
||||
const logprobs: Array<z.infer<typeof LOGPROBS_SCHEMA>> = []
|
||||
|
||||
// flag that checks if there have been client-side tool calls (not executed by openai)
|
||||
let hasFunctionCall = false
|
||||
|
||||
// map response content to content array
|
||||
for (const part of response.output) {
|
||||
switch (part.type) {
|
||||
case "reasoning": {
|
||||
// when there are no summary parts, we need to add an empty reasoning part:
|
||||
if (part.summary.length === 0) {
|
||||
part.summary.push({ type: "summary_text", text: "" })
|
||||
}
|
||||
|
||||
for (const summary of part.summary) {
|
||||
content.push({
|
||||
type: "reasoning" as const,
|
||||
text: summary.text,
|
||||
providerMetadata: {
|
||||
copilot: {
|
||||
itemId: part.id,
|
||||
reasoningEncryptedContent: part.encrypted_content ?? null,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
case "image_generation_call": {
|
||||
content.push({
|
||||
type: "tool-call",
|
||||
toolCallId: part.id,
|
||||
toolName: getHostedToolName("image_generation"),
|
||||
input: "{}",
|
||||
providerExecuted: true,
|
||||
})
|
||||
|
||||
content.push({
|
||||
type: "tool-result",
|
||||
toolCallId: part.id,
|
||||
toolName: getHostedToolName("image_generation"),
|
||||
result: {
|
||||
result: part.result,
|
||||
} satisfies z.infer<typeof imageGenerationOutputSchema>,
|
||||
})
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
case "message": {
|
||||
for (const contentPart of part.content) {
|
||||
if (options.providerOptions?.copilot?.logprobs && contentPart.logprobs) {
|
||||
logprobs.push(contentPart.logprobs)
|
||||
}
|
||||
|
||||
content.push({
|
||||
type: "text",
|
||||
text: contentPart.text,
|
||||
providerMetadata: {
|
||||
copilot: {
|
||||
itemId: part.id,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
for (const annotation of contentPart.annotations) {
|
||||
if (annotation.type === "url_citation") {
|
||||
content.push({
|
||||
type: "source",
|
||||
sourceType: "url",
|
||||
id: this.config.generateId?.() ?? generateId(),
|
||||
url: annotation.url,
|
||||
title: annotation.title,
|
||||
})
|
||||
} else if (annotation.type === "file_citation") {
|
||||
content.push({
|
||||
type: "source",
|
||||
sourceType: "document",
|
||||
id: this.config.generateId?.() ?? generateId(),
|
||||
mediaType: "text/plain",
|
||||
title: annotation.quote ?? annotation.filename ?? "Document",
|
||||
filename: annotation.filename ?? annotation.file_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
case "function_call": {
|
||||
hasFunctionCall = true
|
||||
|
||||
content.push({
|
||||
type: "tool-call",
|
||||
toolCallId: part.call_id,
|
||||
toolName: part.name,
|
||||
input: part.arguments,
|
||||
providerMetadata: {
|
||||
copilot: {
|
||||
itemId: part.id,
|
||||
},
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case "web_search_call": {
|
||||
content.push({
|
||||
type: "tool-call",
|
||||
toolCallId: part.id,
|
||||
toolName: getHostedToolName("web_search"),
|
||||
input: JSON.stringify({ action: part.action }),
|
||||
providerExecuted: true,
|
||||
})
|
||||
|
||||
content.push({
|
||||
type: "tool-result",
|
||||
toolCallId: part.id,
|
||||
toolName: getHostedToolName("web_search"),
|
||||
result: { status: part.status },
|
||||
})
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
case "computer_call": {
|
||||
content.push({
|
||||
type: "tool-call",
|
||||
toolCallId: part.id,
|
||||
toolName: "computer_use",
|
||||
input: "",
|
||||
providerExecuted: true,
|
||||
})
|
||||
|
||||
content.push({
|
||||
type: "tool-result",
|
||||
toolCallId: part.id,
|
||||
toolName: "computer_use",
|
||||
result: {
|
||||
type: "computer_use_tool_result",
|
||||
status: part.status || "completed",
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case "file_search_call": {
|
||||
content.push({
|
||||
type: "tool-call",
|
||||
toolCallId: part.id,
|
||||
toolName: getHostedToolName("file_search"),
|
||||
input: "{}",
|
||||
providerExecuted: true,
|
||||
})
|
||||
|
||||
content.push({
|
||||
type: "tool-result",
|
||||
toolCallId: part.id,
|
||||
toolName: getHostedToolName("file_search"),
|
||||
result: {
|
||||
queries: part.queries,
|
||||
results:
|
||||
part.results?.map((result) => ({
|
||||
attributes: result.attributes as Record<string, JSONValue>,
|
||||
fileId: result.file_id,
|
||||
filename: result.filename,
|
||||
score: result.score,
|
||||
text: result.text,
|
||||
})) ?? null,
|
||||
} satisfies z.infer<typeof fileSearchOutputSchema>,
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case "code_interpreter_call": {
|
||||
content.push({
|
||||
type: "tool-call",
|
||||
toolCallId: part.id,
|
||||
toolName: getHostedToolName("code_interpreter"),
|
||||
input: JSON.stringify({
|
||||
code: part.code,
|
||||
containerId: part.container_id,
|
||||
} satisfies z.infer<typeof codeInterpreterInputSchema>),
|
||||
providerExecuted: true,
|
||||
})
|
||||
|
||||
content.push({
|
||||
type: "tool-result",
|
||||
toolCallId: part.id,
|
||||
toolName: getHostedToolName("code_interpreter"),
|
||||
result: {
|
||||
outputs: part.outputs,
|
||||
} satisfies z.infer<typeof codeInterpreterOutputSchema>,
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const providerMetadata: SharedV3ProviderMetadata = {
|
||||
copilot: { responseId: response.id },
|
||||
}
|
||||
|
||||
if (logprobs.length > 0) {
|
||||
providerMetadata.copilot.logprobs = logprobs
|
||||
}
|
||||
|
||||
if (typeof response.service_tier === "string") {
|
||||
providerMetadata.copilot.serviceTier = response.service_tier
|
||||
}
|
||||
|
||||
return {
|
||||
content,
|
||||
finishReason: {
|
||||
unified: mapOpenAIResponseFinishReason({
|
||||
finishReason: response.incomplete_details?.reason,
|
||||
hasFunctionCall,
|
||||
}),
|
||||
raw: response.incomplete_details?.reason,
|
||||
},
|
||||
usage: {
|
||||
inputTokens: {
|
||||
total: response.usage.input_tokens,
|
||||
noCache:
|
||||
response.usage.input_tokens_details?.cached_tokens != null
|
||||
? response.usage.input_tokens - response.usage.input_tokens_details.cached_tokens
|
||||
: undefined,
|
||||
cacheRead: response.usage.input_tokens_details?.cached_tokens ?? undefined,
|
||||
cacheWrite: undefined,
|
||||
},
|
||||
outputTokens: {
|
||||
total: response.usage.output_tokens,
|
||||
text: undefined,
|
||||
reasoning: response.usage.output_tokens_details?.reasoning_tokens ?? undefined,
|
||||
},
|
||||
raw: response.usage,
|
||||
},
|
||||
request: { body },
|
||||
response: {
|
||||
id: response.id,
|
||||
timestamp: new Date(response.created_at * 1000),
|
||||
modelId: response.model,
|
||||
headers: responseHeaders,
|
||||
body: rawResponse,
|
||||
},
|
||||
providerMetadata,
|
||||
warnings,
|
||||
}
|
||||
async doGenerate(_options: LanguageModelV3CallOptions): Promise<never> {
|
||||
throw new Error("GitHub Copilot models only support streaming")
|
||||
}
|
||||
|
||||
async doStream(options: LanguageModelV3CallOptions) {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { createProviderToolFactoryWithOutputSchema } from "@ai-sdk/provider-utils"
|
||||
import { z } from "zod/v4"
|
||||
|
||||
export const codeInterpreterInputSchema = z.object({
|
||||
@@ -27,61 +26,3 @@ export const codeInterpreterArgsSchema = z.object({
|
||||
])
|
||||
.optional(),
|
||||
})
|
||||
|
||||
type CodeInterpreterArgs = {
|
||||
/**
|
||||
* The code interpreter container.
|
||||
* Can be a container ID
|
||||
* or an object that specifies uploaded file IDs to make available to your code.
|
||||
*/
|
||||
container?: string | { fileIds?: string[] }
|
||||
}
|
||||
|
||||
export const codeInterpreterToolFactory = createProviderToolFactoryWithOutputSchema<
|
||||
{
|
||||
/**
|
||||
* The code to run, or null if not available.
|
||||
*/
|
||||
code?: string | null
|
||||
|
||||
/**
|
||||
* The ID of the container used to run the code.
|
||||
*/
|
||||
containerId: string
|
||||
},
|
||||
{
|
||||
/**
|
||||
* The outputs generated by the code interpreter, such as logs or images.
|
||||
* Can be null if no outputs are available.
|
||||
*/
|
||||
outputs?: Array<
|
||||
| {
|
||||
type: "logs"
|
||||
|
||||
/**
|
||||
* The logs output from the code interpreter.
|
||||
*/
|
||||
logs: string
|
||||
}
|
||||
| {
|
||||
type: "image"
|
||||
|
||||
/**
|
||||
* The URL of the image output from the code interpreter.
|
||||
*/
|
||||
url: string
|
||||
}
|
||||
> | null
|
||||
},
|
||||
CodeInterpreterArgs
|
||||
>({
|
||||
id: "openai.code_interpreter",
|
||||
inputSchema: codeInterpreterInputSchema,
|
||||
outputSchema: codeInterpreterOutputSchema,
|
||||
})
|
||||
|
||||
export const codeInterpreter = (
|
||||
args: CodeInterpreterArgs = {}, // default
|
||||
) => {
|
||||
return codeInterpreterToolFactory(args)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
import { createProviderToolFactoryWithOutputSchema } from "@ai-sdk/provider-utils"
|
||||
import type {
|
||||
OpenAIResponsesFileSearchToolComparisonFilter,
|
||||
OpenAIResponsesFileSearchToolCompoundFilter,
|
||||
} from "../openai-responses-api-types.js"
|
||||
import { z } from "zod/v4"
|
||||
|
||||
const comparisonFilterSchema = z.object({
|
||||
@@ -42,86 +37,3 @@ export const fileSearchOutputSchema = z.object({
|
||||
)
|
||||
.nullable(),
|
||||
})
|
||||
|
||||
export const fileSearch = createProviderToolFactoryWithOutputSchema<
|
||||
{},
|
||||
{
|
||||
/**
|
||||
* The search query to execute.
|
||||
*/
|
||||
queries: string[]
|
||||
|
||||
/**
|
||||
* The results of the file search tool call.
|
||||
*/
|
||||
results:
|
||||
| null
|
||||
| {
|
||||
/**
|
||||
* Set of 16 key-value pairs that can be attached to an object.
|
||||
* This can be useful for storing additional information about the object
|
||||
* in a structured format, and querying for objects via API or the dashboard.
|
||||
* Keys are strings with a maximum length of 64 characters.
|
||||
* Values are strings with a maximum length of 512 characters, booleans, or numbers.
|
||||
*/
|
||||
attributes: Record<string, unknown>
|
||||
|
||||
/**
|
||||
* The unique ID of the file.
|
||||
*/
|
||||
fileId: string
|
||||
|
||||
/**
|
||||
* The name of the file.
|
||||
*/
|
||||
filename: string
|
||||
|
||||
/**
|
||||
* The relevance score of the file - a value between 0 and 1.
|
||||
*/
|
||||
score: number
|
||||
|
||||
/**
|
||||
* The text that was retrieved from the file.
|
||||
*/
|
||||
text: string
|
||||
}[]
|
||||
},
|
||||
{
|
||||
/**
|
||||
* List of vector store IDs to search through.
|
||||
*/
|
||||
vectorStoreIds: string[]
|
||||
|
||||
/**
|
||||
* Maximum number of search results to return. Defaults to 10.
|
||||
*/
|
||||
maxNumResults?: number
|
||||
|
||||
/**
|
||||
* Ranking options for the search.
|
||||
*/
|
||||
ranking?: {
|
||||
/**
|
||||
* The ranker to use for the file search.
|
||||
*/
|
||||
ranker?: string
|
||||
|
||||
/**
|
||||
* The score threshold for the file search, a number between 0 and 1.
|
||||
* Numbers closer to 1 will attempt to return only the most relevant results,
|
||||
* but may return fewer results.
|
||||
*/
|
||||
scoreThreshold?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* A filter to apply.
|
||||
*/
|
||||
filters?: OpenAIResponsesFileSearchToolComparisonFilter | OpenAIResponsesFileSearchToolCompoundFilter
|
||||
}
|
||||
>({
|
||||
id: "openai.file_search",
|
||||
inputSchema: z.object({}),
|
||||
outputSchema: fileSearchOutputSchema,
|
||||
})
|
||||
|
||||
@@ -11,12 +11,6 @@ const HOSTED_TOOL_CASES = [
|
||||
name: "current_web",
|
||||
args: {},
|
||||
wireType: "web_search",
|
||||
output: {
|
||||
type: "web_search_call",
|
||||
id: "web_1",
|
||||
status: "completed",
|
||||
action: { type: "search", query: "news" },
|
||||
},
|
||||
stream: [
|
||||
{
|
||||
type: "response.output_item.added",
|
||||
@@ -47,12 +41,6 @@ const HOSTED_TOOL_CASES = [
|
||||
name: "preview_web",
|
||||
args: {},
|
||||
wireType: "web_search_preview",
|
||||
output: {
|
||||
type: "web_search_call",
|
||||
id: "preview_1",
|
||||
status: "completed",
|
||||
action: { type: "search", query: "news" },
|
||||
},
|
||||
stream: [
|
||||
{
|
||||
type: "response.output_item.added",
|
||||
@@ -83,7 +71,6 @@ const HOSTED_TOOL_CASES = [
|
||||
name: "documents",
|
||||
args: { vectorStoreIds: ["store_1"] },
|
||||
wireType: "file_search",
|
||||
output: { type: "file_search_call", id: "file_1", queries: ["news"], results: null },
|
||||
stream: [
|
||||
{
|
||||
type: "response.output_item.added",
|
||||
@@ -104,13 +91,6 @@ const HOSTED_TOOL_CASES = [
|
||||
name: "python",
|
||||
args: {},
|
||||
wireType: "code_interpreter",
|
||||
output: {
|
||||
type: "code_interpreter_call",
|
||||
id: "code_1",
|
||||
code: "print(1)",
|
||||
container_id: "container_1",
|
||||
outputs: null,
|
||||
},
|
||||
stream: [
|
||||
{
|
||||
type: "response.output_item.added",
|
||||
@@ -164,7 +144,6 @@ const HOSTED_TOOL_CASES = [
|
||||
name: "illustrate",
|
||||
args: {},
|
||||
wireType: "image_generation",
|
||||
output: { type: "image_generation_call", id: "image_1", result: "final-image" },
|
||||
stream: [
|
||||
{
|
||||
type: "response.output_item.added",
|
||||
@@ -192,15 +171,9 @@ function hostedTool(testCase: (typeof HOSTED_TOOL_CASES)[number]): LanguageModel
|
||||
return { type: "provider", id: testCase.id, name: testCase.name, args: testCase.args }
|
||||
}
|
||||
|
||||
function createMockFetch(body: unknown) {
|
||||
return mock(
|
||||
async () => new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } }),
|
||||
)
|
||||
}
|
||||
|
||||
function createStreamFetch(events: ReadonlyArray<Record<string, unknown>>) {
|
||||
return mock(
|
||||
async () =>
|
||||
async (_input: Parameters<typeof fetch>[0], _init?: RequestInit) =>
|
||||
new Response(events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "text/event-stream" },
|
||||
@@ -217,6 +190,10 @@ function createModel(fetchFn: ReturnType<typeof mock>) {
|
||||
})
|
||||
}
|
||||
|
||||
function requestBodies(fetchFn: ReturnType<typeof createStreamFetch>) {
|
||||
return fetchFn.mock.calls.map((call) => JSON.parse(call[1]?.body as string))
|
||||
}
|
||||
|
||||
async function readStream(stream: ReadableStream<LanguageModelV3StreamPart>) {
|
||||
const reader = stream.getReader()
|
||||
const events: LanguageModelV3StreamPart[] = []
|
||||
@@ -232,52 +209,25 @@ async function readStream(stream: ReadableStream<LanguageModelV3StreamPart>) {
|
||||
// namespace request options already use. It used to echo this metadata under "openai" (a leftover
|
||||
// from forking the OpenAI Responses model), which left it unreachable by anything reading the
|
||||
// "copilot" namespace and let stale itemIds slip past stripping meant for that namespace.
|
||||
describe("doGenerate", () => {
|
||||
describe("doStream", () => {
|
||||
test.each([...HOSTED_TOOL_CASES])("forces $id by its declared logical name", async (testCase) => {
|
||||
const requests: unknown[] = []
|
||||
const model = createModel(
|
||||
mock(async (_input: Parameters<typeof fetch>[0], init?: RequestInit) => {
|
||||
requests.push(await new Response(init?.body).json())
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
id: "resp_1",
|
||||
created_at: 0,
|
||||
model: "test-model",
|
||||
output: [],
|
||||
usage: { input_tokens: 1, output_tokens: 1 },
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } },
|
||||
)
|
||||
}),
|
||||
)
|
||||
const fetchFn = createStreamFetch([])
|
||||
const model = createModel(fetchFn)
|
||||
|
||||
await model.doGenerate({
|
||||
await model.doStream({
|
||||
prompt: TEST_PROMPT,
|
||||
tools: [hostedTool(testCase)],
|
||||
toolChoice: { type: "tool", toolName: testCase.name },
|
||||
})
|
||||
|
||||
expect(requests[0]).toMatchObject({ tool_choice: { type: testCase.wireType } })
|
||||
expect(requestBodies(fetchFn)[0]).toMatchObject({ tool_choice: { type: testCase.wireType } })
|
||||
})
|
||||
|
||||
test("does not mistake a colliding function name for a hosted tool", async () => {
|
||||
const requests: unknown[] = []
|
||||
const model = createModel(
|
||||
mock(async (_input: Parameters<typeof fetch>[0], init?: RequestInit) => {
|
||||
requests.push(await new Response(init?.body).json())
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
id: "resp_1",
|
||||
created_at: 0,
|
||||
model: "test-model",
|
||||
output: [],
|
||||
usage: { input_tokens: 1, output_tokens: 1 },
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } },
|
||||
)
|
||||
}),
|
||||
)
|
||||
await model.doGenerate({
|
||||
const fetchFn = createStreamFetch([])
|
||||
const model = createModel(fetchFn)
|
||||
|
||||
await model.doStream({
|
||||
prompt: TEST_PROMPT,
|
||||
tools: [
|
||||
{ type: "provider", id: "openai.web_search", name: "lookup", args: {} },
|
||||
@@ -286,156 +236,21 @@ describe("doGenerate", () => {
|
||||
toolChoice: { type: "tool", toolName: "web_search" },
|
||||
})
|
||||
|
||||
expect(requests[0]).toMatchObject({ tool_choice: { type: "function", name: "web_search" } })
|
||||
})
|
||||
|
||||
test.each([...HOSTED_TOOL_CASES])("uses $name for generated $id calls and results", async (testCase) => {
|
||||
const model = createModel(
|
||||
createMockFetch({
|
||||
id: "resp_1",
|
||||
created_at: 0,
|
||||
model: "test-model",
|
||||
output: [testCase.output],
|
||||
usage: { input_tokens: 1, output_tokens: 1 },
|
||||
}),
|
||||
)
|
||||
|
||||
const result = await model.doGenerate({ prompt: TEST_PROMPT, tools: [hostedTool(testCase)] })
|
||||
|
||||
expect(result.content.filter((part) => part.type === "tool-call" || part.type === "tool-result")).toMatchObject([
|
||||
{ type: "tool-call", toolName: testCase.name },
|
||||
{ type: "tool-result", toolName: testCase.name },
|
||||
])
|
||||
})
|
||||
|
||||
test("uses canonical names only when no hosted declaration matches", async () => {
|
||||
const model = createModel(
|
||||
createMockFetch({
|
||||
id: "resp_1",
|
||||
created_at: 0,
|
||||
model: "test-model",
|
||||
output: [
|
||||
HOSTED_TOOL_CASES[0].output,
|
||||
HOSTED_TOOL_CASES[2].output,
|
||||
HOSTED_TOOL_CASES[3].output,
|
||||
HOSTED_TOOL_CASES[4].output,
|
||||
{ type: "computer_call", id: "computer_1", status: "completed" },
|
||||
],
|
||||
usage: { input_tokens: 1, output_tokens: 1 },
|
||||
}),
|
||||
)
|
||||
|
||||
const result = await model.doGenerate({ prompt: TEST_PROMPT })
|
||||
|
||||
expect(result.content.filter((part) => part.type === "tool-call").map((part) => part.toolName)).toEqual([
|
||||
"web_search",
|
||||
"file_search",
|
||||
"code_interpreter",
|
||||
"image_generation",
|
||||
"computer_use",
|
||||
])
|
||||
})
|
||||
|
||||
test("rejects an automatic web response when both variants have different logical names", async () => {
|
||||
const model = createModel(
|
||||
createMockFetch({
|
||||
id: "resp_1",
|
||||
created_at: 0,
|
||||
model: "test-model",
|
||||
output: [HOSTED_TOOL_CASES[0].output],
|
||||
usage: { input_tokens: 1, output_tokens: 1 },
|
||||
}),
|
||||
)
|
||||
|
||||
await expect(
|
||||
model.doGenerate({
|
||||
prompt: TEST_PROMPT,
|
||||
tools: [hostedTool(HOSTED_TOOL_CASES[0]), hostedTool(HOSTED_TOOL_CASES[1])],
|
||||
}),
|
||||
).rejects.toThrow("ambiguous web_search response for hosted tools: current_web, preview_web")
|
||||
})
|
||||
|
||||
test("attaches item metadata under the copilot namespace, not openai", async () => {
|
||||
const mockFetch = createMockFetch({
|
||||
id: "resp_1",
|
||||
created_at: 0,
|
||||
model: "gpt-5.5",
|
||||
output: [
|
||||
{
|
||||
type: "reasoning",
|
||||
id: "rs_1",
|
||||
encrypted_content: "enc_1",
|
||||
summary: [{ type: "summary_text", text: "thinking..." }],
|
||||
},
|
||||
{
|
||||
type: "message",
|
||||
role: "assistant",
|
||||
id: "msg_1",
|
||||
content: [{ type: "output_text", text: "Hello there", annotations: [] }],
|
||||
},
|
||||
{
|
||||
type: "function_call",
|
||||
call_id: "call_1",
|
||||
name: "bash",
|
||||
arguments: "{}",
|
||||
id: "fc_1",
|
||||
},
|
||||
],
|
||||
usage: { input_tokens: 10, output_tokens: 5 },
|
||||
})
|
||||
const model = createModel(mockFetch)
|
||||
|
||||
const { content, providerMetadata } = await model.doGenerate({
|
||||
prompt: TEST_PROMPT,
|
||||
includeRawChunks: false,
|
||||
} as any)
|
||||
|
||||
const reasoning = content.find((part: any) => part.type === "reasoning") as any
|
||||
expect(reasoning.providerMetadata?.copilot?.itemId).toBe("rs_1")
|
||||
expect(reasoning.providerMetadata?.copilot?.reasoningEncryptedContent).toBe("enc_1")
|
||||
expect(reasoning.providerMetadata?.openai).toBeUndefined()
|
||||
|
||||
const text = content.find((part: any) => part.type === "text") as any
|
||||
expect(text.providerMetadata?.copilot?.itemId).toBe("msg_1")
|
||||
expect(text.providerMetadata?.openai).toBeUndefined()
|
||||
|
||||
const toolCall = content.find((part: any) => part.type === "tool-call") as any
|
||||
expect(toolCall.providerMetadata?.copilot?.itemId).toBe("fc_1")
|
||||
expect(toolCall.providerMetadata?.openai).toBeUndefined()
|
||||
|
||||
expect(providerMetadata?.copilot?.responseId).toBe("resp_1")
|
||||
expect(providerMetadata?.openai).toBeUndefined()
|
||||
expect(requestBodies(fetchFn)[0]).toMatchObject({ tool_choice: { type: "function", name: "web_search" } })
|
||||
})
|
||||
|
||||
test("defaults to stateless encrypted reasoning and keeps previousResponseId opt-in", async () => {
|
||||
const requests: Array<Record<string, unknown>> = []
|
||||
const fetchFn = mock(async (_input: Parameters<typeof fetch>[0], init?: RequestInit) => {
|
||||
requests.push(JSON.parse(init?.body as string))
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
id: "resp_1",
|
||||
created_at: 0,
|
||||
model: "gpt-5.5",
|
||||
output: [],
|
||||
usage: { input_tokens: 1, output_tokens: 1 },
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } },
|
||||
)
|
||||
})
|
||||
const fetchFn = createStreamFetch([])
|
||||
const model = createModel(fetchFn)
|
||||
|
||||
await model.doGenerate({ prompt: TEST_PROMPT, includeRawChunks: false } as any)
|
||||
await model.doGenerate({
|
||||
await model.doStream({ prompt: TEST_PROMPT })
|
||||
await model.doStream({
|
||||
prompt: TEST_PROMPT,
|
||||
includeRawChunks: false,
|
||||
providerOptions: { copilot: { previousResponseId: "resp_previous", store: false } },
|
||||
} as any)
|
||||
await model.doGenerate({
|
||||
prompt: TEST_PROMPT,
|
||||
includeRawChunks: false,
|
||||
providerOptions: { copilot: { store: true } },
|
||||
} as any)
|
||||
})
|
||||
await model.doStream({ prompt: TEST_PROMPT, providerOptions: { copilot: { store: true } } })
|
||||
|
||||
const requests = requestBodies(fetchFn)
|
||||
expect(requests[0]?.previous_response_id).toBeUndefined()
|
||||
expect(requests[0]?.store).toBe(false)
|
||||
expect(requests[0]?.include).toEqual(["reasoning.encrypted_content"])
|
||||
@@ -445,9 +260,6 @@ describe("doGenerate", () => {
|
||||
expect(requests[2]?.store).toBe(true)
|
||||
expect(requests[2]?.include).toEqual(["reasoning.encrypted_content"])
|
||||
})
|
||||
})
|
||||
|
||||
describe("doStream", () => {
|
||||
test.each([...HOSTED_TOOL_CASES])("uses $name for every streamed $id identity event", async (testCase) => {
|
||||
const model = createModel(createStreamFetch(testCase.stream))
|
||||
const result = await model.doStream({
|
||||
|
||||
Reference in New Issue
Block a user