import { w as withoutTrailingSlash, N as NoSuchModelError, k as withUserAgentSuffix, o as createJsonErrorResponseHandler, p as parseProviderOptions, f as postJsonToApi, e as combineHeaders, h as createJsonResponseHandler, g as generateId, i as createEventSourceResponseHandler, q as InvalidResponseDataError, s as isParsableJson, j as loadApiKey, b as lazySchema, z as zodSchema } from "./index-BnnkYv5o.js";
import { aB as object, aK as union, aO as any, aD as string, aE as number, aF as _enum, aC as array, aI as literal } from "./index-Cba9M8g3.js";
function convertToDeepSeekChatMessages({
  prompt,
  responseFormat
}) {
  var _a;
  const messages = [];
  const warnings = [];
  if ((responseFormat == null ? void 0 : responseFormat.type) === "json") {
    if (responseFormat.schema == null) {
      messages.push({
        role: "system",
        content: "Return JSON."
      });
    } else {
      messages.push({
        role: "system",
        content: "Return JSON that conforms to the following schema: " + JSON.stringify(responseFormat.schema)
      });
      warnings.push({
        type: "compatibility",
        feature: "responseFormat JSON schema",
        details: "JSON response schema is injected into the system message."
      });
    }
  }
  let lastUserMessageIndex = -1;
  for (let i = prompt.length - 1; i >= 0; i--) {
    if (prompt[i].role === "user") {
      lastUserMessageIndex = i;
      break;
    }
  }
  let index = -1;
  for (const { role, content } of prompt) {
    index++;
    switch (role) {
      case "system": {
        messages.push({ role: "system", content });
        break;
      }
      case "user": {
        let userContent = "";
        for (const part of content) {
          if (part.type === "text") {
            userContent += part.text;
          } else {
            warnings.push({
              type: "unsupported",
              feature: `user message part type: ${part.type}`
            });
          }
        }
        messages.push({
          role: "user",
          content: userContent
        });
        break;
      }
      case "assistant": {
        let text = "";
        let reasoning;
        const toolCalls = [];
        for (const part of content) {
          switch (part.type) {
            case "text": {
              text += part.text;
              break;
            }
            case "reasoning": {
              if (index <= lastUserMessageIndex) {
                break;
              }
              if (reasoning == null) {
                reasoning = part.text;
              } else {
                reasoning += part.text;
              }
              break;
            }
            case "tool-call": {
              toolCalls.push({
                id: part.toolCallId,
                type: "function",
                function: {
                  name: part.toolName,
                  arguments: JSON.stringify(part.input)
                }
              });
              break;
            }
          }
        }
        messages.push({
          role: "assistant",
          content: text,
          reasoning_content: reasoning,
          tool_calls: toolCalls.length > 0 ? toolCalls : void 0
        });
        break;
      }
      case "tool": {
        for (const toolResponse of content) {
          if (toolResponse.type === "tool-approval-response") {
            continue;
          }
          const output = toolResponse.output;
          let contentValue;
          switch (output.type) {
            case "text":
            case "error-text":
              contentValue = output.value;
              break;
            case "execution-denied":
              contentValue = (_a = output.reason) != null ? _a : "Tool execution denied.";
              break;
            case "content":
            case "json":
            case "error-json":
              contentValue = JSON.stringify(output.value);
              break;
          }
          messages.push({
            role: "tool",
            tool_call_id: toolResponse.toolCallId,
            content: contentValue
          });
        }
        break;
      }
      default: {
        warnings.push({
          type: "unsupported",
          feature: `message role: ${role}`
        });
        break;
      }
    }
  }
  return { messages, warnings };
}
function convertDeepSeekUsage(usage) {
  var _a, _b, _c, _d, _e;
  if (usage == null) {
    return {
      inputTokens: {
        total: void 0,
        noCache: void 0,
        cacheRead: void 0,
        cacheWrite: void 0
      },
      outputTokens: {
        total: void 0,
        text: void 0,
        reasoning: void 0
      },
      raw: void 0
    };
  }
  const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;
  const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;
  const cacheReadTokens = (_c = usage.prompt_cache_hit_tokens) != null ? _c : 0;
  const reasoningTokens = (_e = (_d = usage.completion_tokens_details) == null ? void 0 : _d.reasoning_tokens) != null ? _e : 0;
  return {
    inputTokens: {
      total: promptTokens,
      noCache: promptTokens - cacheReadTokens,
      cacheRead: cacheReadTokens,
      cacheWrite: void 0
    },
    outputTokens: {
      total: completionTokens,
      text: completionTokens - reasoningTokens,
      reasoning: reasoningTokens
    },
    raw: usage
  };
}
var tokenUsageSchema = object({
  prompt_tokens: number().nullish(),
  completion_tokens: number().nullish(),
  prompt_cache_hit_tokens: number().nullish(),
  prompt_cache_miss_tokens: number().nullish(),
  total_tokens: number().nullish(),
  completion_tokens_details: object({
    reasoning_tokens: number().nullish()
  }).nullish()
}).nullish();
var deepSeekErrorSchema = object({
  error: object({
    message: string(),
    type: string().nullish(),
    param: any().nullish(),
    code: union([string(), number()]).nullish()
  })
});
var deepseekChatResponseSchema = object({
  id: string().nullish(),
  created: number().nullish(),
  model: string().nullish(),
  choices: array(
    object({
      message: object({
        role: literal("assistant").nullish(),
        content: string().nullish(),
        reasoning_content: string().nullish(),
        tool_calls: array(
          object({
            id: string().nullish(),
            function: object({
              name: string(),
              arguments: string()
            })
          })
        ).nullish()
      }),
      finish_reason: string().nullish()
    })
  ),
  usage: tokenUsageSchema
});
var deepseekChatChunkSchema = lazySchema(
  () => zodSchema(
    union([
      object({
        id: string().nullish(),
        created: number().nullish(),
        model: string().nullish(),
        choices: array(
          object({
            delta: object({
              role: _enum(["assistant"]).nullish(),
              content: string().nullish(),
              reasoning_content: string().nullish(),
              tool_calls: array(
                object({
                  index: number(),
                  id: string().nullish(),
                  function: object({
                    name: string().nullish(),
                    arguments: string().nullish()
                  })
                })
              ).nullish()
            }).nullish(),
            finish_reason: string().nullish()
          })
        ),
        usage: tokenUsageSchema
      }),
      deepSeekErrorSchema
    ])
  )
);
var deepseekChatOptions = object({
  /**
   * Type of thinking to use. Defaults to `enabled`.
   */
  thinking: object({
    type: _enum(["enabled", "disabled"]).optional()
  }).optional()
});
function prepareTools({
  tools,
  toolChoice
}) {
  tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
  const toolWarnings = [];
  if (tools == null) {
    return { tools: void 0, toolChoice: void 0, toolWarnings };
  }
  const deepseekTools = [];
  for (const tool of tools) {
    if (tool.type === "provider") {
      toolWarnings.push({
        type: "unsupported",
        feature: `provider-defined tool ${tool.id}`
      });
    } else {
      deepseekTools.push({
        type: "function",
        function: {
          name: tool.name,
          description: tool.description,
          parameters: tool.inputSchema,
          ...tool.strict != null ? { strict: tool.strict } : {}
        }
      });
    }
  }
  if (toolChoice == null) {
    return { tools: deepseekTools, toolChoice: void 0, toolWarnings };
  }
  const type = toolChoice == null ? void 0 : toolChoice.type;
  switch (type) {
    case "auto":
    case "none":
    case "required":
      return { tools: deepseekTools, toolChoice: type, toolWarnings };
    case "tool":
      return {
        tools: deepseekTools,
        toolChoice: {
          type: "function",
          function: { name: toolChoice.toolName }
        },
        toolWarnings
      };
    default: {
      return {
        tools: deepseekTools,
        toolChoice: void 0,
        toolWarnings: [
          ...toolWarnings,
          {
            type: "unsupported",
            feature: `tool choice type: ${type}`
          }
        ]
      };
    }
  }
}
function getResponseMetadata({
  id,
  model,
  created
}) {
  return {
    id: id != null ? id : void 0,
    modelId: model != null ? model : void 0,
    timestamp: created != null ? new Date(created * 1e3) : void 0
  };
}
function mapDeepSeekFinishReason(finishReason) {
  switch (finishReason) {
    case "stop":
      return "stop";
    case "length":
      return "length";
    case "content_filter":
      return "content-filter";
    case "tool_calls":
      return "tool-calls";
    case "insufficient_system_resource":
      return "error";
    default:
      return "other";
  }
}
var DeepSeekChatLanguageModel = class {
  constructor(modelId, config) {
    this.specificationVersion = "v3";
    this.supportedUrls = {};
    this.modelId = modelId;
    this.config = config;
    this.failedResponseHandler = createJsonErrorResponseHandler({
      errorSchema: deepSeekErrorSchema,
      errorToMessage: (error) => error.error.message
    });
  }
  get provider() {
    return this.config.provider;
  }
  get providerOptionsName() {
    return this.config.provider.split(".")[0].trim();
  }
  async getArgs({
    prompt,
    maxOutputTokens,
    temperature,
    topP,
    topK,
    frequencyPenalty,
    presencePenalty,
    providerOptions,
    stopSequences,
    responseFormat,
    seed,
    toolChoice,
    tools
  }) {
    var _a, _b;
    const deepseekOptions = (_a = await parseProviderOptions({
      provider: this.providerOptionsName,
      providerOptions,
      schema: deepseekChatOptions
    })) != null ? _a : {};
    const { messages, warnings } = convertToDeepSeekChatMessages({
      prompt,
      responseFormat
    });
    if (topK != null) {
      warnings.push({ type: "unsupported", feature: "topK" });
    }
    if (seed != null) {
      warnings.push({ type: "unsupported", feature: "seed" });
    }
    const {
      tools: deepseekTools,
      toolChoice: deepseekToolChoices,
      toolWarnings
    } = prepareTools({
      tools,
      toolChoice
    });
    return {
      args: {
        model: this.modelId,
        max_tokens: maxOutputTokens,
        temperature,
        top_p: topP,
        frequency_penalty: frequencyPenalty,
        presence_penalty: presencePenalty,
        response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? { type: "json_object" } : void 0,
        stop: stopSequences,
        messages,
        tools: deepseekTools,
        tool_choice: deepseekToolChoices,
        thinking: ((_b = deepseekOptions.thinking) == null ? void 0 : _b.type) != null ? { type: deepseekOptions.thinking.type } : void 0
      },
      warnings: [...warnings, ...toolWarnings]
    };
  }
  async doGenerate(options) {
    var _a, _b, _c, _d;
    const { args, warnings } = await this.getArgs({ ...options });
    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(
        deepseekChatResponseSchema
      ),
      abortSignal: options.abortSignal,
      fetch: this.config.fetch
    });
    const choice = responseBody.choices[0];
    const content = [];
    const reasoning = choice.message.reasoning_content;
    if (reasoning != null && reasoning.length > 0) {
      content.push({
        type: "reasoning",
        text: reasoning
      });
    }
    if (choice.message.tool_calls != null) {
      for (const toolCall of choice.message.tool_calls) {
        content.push({
          type: "tool-call",
          toolCallId: (_a = toolCall.id) != null ? _a : generateId(),
          toolName: toolCall.function.name,
          input: toolCall.function.arguments
        });
      }
    }
    const text = choice.message.content;
    if (text != null && text.length > 0) {
      content.push({ type: "text", text });
    }
    return {
      content,
      finishReason: {
        unified: mapDeepSeekFinishReason(choice.finish_reason),
        raw: (_b = choice.finish_reason) != null ? _b : void 0
      },
      usage: convertDeepSeekUsage(responseBody.usage),
      providerMetadata: {
        [this.providerOptionsName]: {
          promptCacheHitTokens: (_c = responseBody.usage) == null ? void 0 : _c.prompt_cache_hit_tokens,
          promptCacheMissTokens: (_d = responseBody.usage) == null ? void 0 : _d.prompt_cache_miss_tokens
        }
      },
      request: { body: args },
      response: {
        ...getResponseMetadata(responseBody),
        headers: responseHeaders,
        body: rawResponse
      },
      warnings
    };
  }
  async doStream(options) {
    const { args, warnings } = await this.getArgs({ ...options });
    const body = {
      ...args,
      stream: true,
      stream_options: { include_usage: true }
    };
    const { responseHeaders, value: response } = await postJsonToApi({
      url: this.config.url({
        path: "/chat/completions",
        modelId: this.modelId
      }),
      headers: combineHeaders(this.config.headers(), options.headers),
      body,
      failedResponseHandler: this.failedResponseHandler,
      successfulResponseHandler: createEventSourceResponseHandler(
        deepseekChatChunkSchema
      ),
      abortSignal: options.abortSignal,
      fetch: this.config.fetch
    });
    const toolCalls = [];
    let finishReason = {
      unified: "other",
      raw: void 0
    };
    let usage = void 0;
    let isFirstChunk = true;
    const providerOptionsName = this.providerOptionsName;
    let isActiveReasoning = false;
    let isActiveText = false;
    return {
      stream: response.pipeThrough(
        new TransformStream({
          start(controller) {
            controller.enqueue({ type: "stream-start", warnings });
          },
          transform(chunk, controller) {
            var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
            if (options.includeRawChunks) {
              controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
            }
            if (!chunk.success) {
              finishReason = { unified: "error", raw: void 0 };
              controller.enqueue({ type: "error", error: chunk.error });
              return;
            }
            const value = chunk.value;
            if ("error" in value) {
              finishReason = { unified: "error", raw: void 0 };
              controller.enqueue({ type: "error", error: value.error.message });
              return;
            }
            if (isFirstChunk) {
              isFirstChunk = false;
              controller.enqueue({
                type: "response-metadata",
                ...getResponseMetadata(value)
              });
            }
            if (value.usage != null) {
              usage = value.usage;
            }
            const choice = value.choices[0];
            if ((choice == null ? void 0 : choice.finish_reason) != null) {
              finishReason = {
                unified: mapDeepSeekFinishReason(choice.finish_reason),
                raw: choice.finish_reason
              };
            }
            if ((choice == null ? void 0 : choice.delta) == null) {
              return;
            }
            const delta = choice.delta;
            const reasoningContent = delta.reasoning_content;
            if (reasoningContent) {
              if (!isActiveReasoning) {
                controller.enqueue({
                  type: "reasoning-start",
                  id: "reasoning-0"
                });
                isActiveReasoning = true;
              }
              controller.enqueue({
                type: "reasoning-delta",
                id: "reasoning-0",
                delta: reasoningContent
              });
            }
            if (delta.content) {
              if (!isActiveText) {
                controller.enqueue({ type: "text-start", id: "txt-0" });
                isActiveText = true;
              }
              if (isActiveReasoning) {
                controller.enqueue({
                  type: "reasoning-end",
                  id: "reasoning-0"
                });
                isActiveReasoning = false;
              }
              controller.enqueue({
                type: "text-delta",
                id: "txt-0",
                delta: delta.content
              });
            }
            if (delta.tool_calls != null) {
              if (isActiveReasoning) {
                controller.enqueue({
                  type: "reasoning-end",
                  id: "reasoning-0"
                });
                isActiveReasoning = false;
              }
              for (const toolCallDelta of delta.tool_calls) {
                const index = toolCallDelta.index;
                if (toolCalls[index] == null) {
                  if (toolCallDelta.id == null) {
                    throw new InvalidResponseDataError({
                      data: toolCallDelta,
                      message: `Expected 'id' to be a string.`
                    });
                  }
                  if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
                    throw new InvalidResponseDataError({
                      data: toolCallDelta,
                      message: `Expected 'function.name' to be a string.`
                    });
                  }
                  controller.enqueue({
                    type: "tool-input-start",
                    id: toolCallDelta.id,
                    toolName: toolCallDelta.function.name
                  });
                  toolCalls[index] = {
                    id: toolCallDelta.id,
                    type: "function",
                    function: {
                      name: toolCallDelta.function.name,
                      arguments: (_b = toolCallDelta.function.arguments) != null ? _b : ""
                    },
                    hasFinished: false
                  };
                  const toolCall2 = toolCalls[index];
                  if (((_c = toolCall2.function) == null ? void 0 : _c.name) != null && ((_d = toolCall2.function) == null ? void 0 : _d.arguments) != null) {
                    if (toolCall2.function.arguments.length > 0) {
                      controller.enqueue({
                        type: "tool-input-delta",
                        id: toolCall2.id,
                        delta: toolCall2.function.arguments
                      });
                    }
                    if (isParsableJson(toolCall2.function.arguments)) {
                      controller.enqueue({
                        type: "tool-input-end",
                        id: toolCall2.id
                      });
                      controller.enqueue({
                        type: "tool-call",
                        toolCallId: (_e = toolCall2.id) != null ? _e : generateId(),
                        toolName: toolCall2.function.name,
                        input: toolCall2.function.arguments
                      });
                      toolCall2.hasFinished = true;
                    }
                  }
                  continue;
                }
                const toolCall = toolCalls[index];
                if (toolCall.hasFinished) {
                  continue;
                }
                if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) {
                  toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null ? _h : "";
                }
                controller.enqueue({
                  type: "tool-input-delta",
                  id: toolCall.id,
                  delta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
                });
                if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
                  controller.enqueue({
                    type: "tool-input-end",
                    id: toolCall.id
                  });
                  controller.enqueue({
                    type: "tool-call",
                    toolCallId: (_l = toolCall.id) != null ? _l : generateId(),
                    toolName: toolCall.function.name,
                    input: toolCall.function.arguments
                  });
                  toolCall.hasFinished = true;
                }
              }
            }
          },
          flush(controller) {
            var _a, _b, _c;
            if (isActiveReasoning) {
              controller.enqueue({ type: "reasoning-end", id: "reasoning-0" });
            }
            if (isActiveText) {
              controller.enqueue({ type: "text-end", id: "txt-0" });
            }
            for (const toolCall of toolCalls.filter(
              (toolCall2) => !toolCall2.hasFinished
            )) {
              controller.enqueue({
                type: "tool-input-end",
                id: toolCall.id
              });
              controller.enqueue({
                type: "tool-call",
                toolCallId: (_a = toolCall.id) != null ? _a : generateId(),
                toolName: toolCall.function.name,
                input: toolCall.function.arguments
              });
            }
            controller.enqueue({
              type: "finish",
              finishReason,
              usage: convertDeepSeekUsage(usage),
              providerMetadata: {
                [providerOptionsName]: {
                  promptCacheHitTokens: (_b = usage == null ? void 0 : usage.prompt_cache_hit_tokens) != null ? _b : void 0,
                  promptCacheMissTokens: (_c = usage == null ? void 0 : usage.prompt_cache_miss_tokens) != null ? _c : void 0
                }
              }
            });
          }
        })
      ),
      request: { body },
      response: { headers: responseHeaders }
    };
  }
};
var VERSION = "2.0.17";
function createDeepSeek(options = {}) {
  var _a;
  const baseURL = withoutTrailingSlash(
    (_a = options.baseURL) != null ? _a : "https://api.deepseek.com"
  );
  const getHeaders = () => withUserAgentSuffix(
    {
      Authorization: `Bearer ${loadApiKey({
        apiKey: options.apiKey,
        environmentVariableName: "DEEPSEEK_API_KEY",
        description: "DeepSeek API key"
      })}`,
      ...options.headers
    },
    `ai-sdk/deepseek/${VERSION}`
  );
  const createLanguageModel = (modelId) => {
    return new DeepSeekChatLanguageModel(modelId, {
      provider: `deepseek.chat`,
      url: ({ path }) => `${baseURL}${path}`,
      headers: getHeaders,
      fetch: options.fetch
    });
  };
  const provider = (modelId) => createLanguageModel(modelId);
  provider.specificationVersion = "v3";
  provider.languageModel = createLanguageModel;
  provider.chat = createLanguageModel;
  provider.embeddingModel = (modelId) => {
    throw new NoSuchModelError({ modelId, modelType: "embeddingModel" });
  };
  provider.textEmbeddingModel = provider.embeddingModel;
  provider.imageModel = (modelId) => {
    throw new NoSuchModelError({ modelId, modelType: "imageModel" });
  };
  return provider;
}
var deepseek = createDeepSeek();
export {
  VERSION,
  createDeepSeek,
  deepseek
};
//# sourceMappingURL=index-B1gn--QN.js.map
