# @mistralai/mistralai-gcp 中文文档

规范地址：https://npmcn.com/package/%40mistralai/mistralai-gcp/

版本：2\.1\.0
npm 元数据更新时间：2026-11-01T20:24:01.684Z
中文译文更新时间：2026-11-01T21:47:32.230Z
软件包许可：Apache-2\.0

本文由上游 README 机器翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40mistralai/mistralai-gcp
原文对照：https://npmcn.com/package/%40mistralai/mistralai-gcp/?lang=original
项目主页：https://github.com/mistralai/client-ts#readme
源码仓库：https://github.com/mistralai/client-ts

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：879 kB，532 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2024-07-30T09:44:49.553Z
- 最新版本发布：2026-11-01T20:24:01.407Z
- 已发布版本数：21（近 12 个月 6 个）

## 中文简介

谷歌云上Mistral AI的TypeScript客户端库

## 安装

```sh
npm install @mistralai/mistralai-gcp
```

也可以使用：`pnpm add @mistralai/mistralai-gcp`、`yarn add @mistralai/mistralai-gcp`、`bun add @mistralai/mistralai-gcp`

## README

# 使用GCP Typescript客户端

> **v2重大变化：** SDK类已从 `MistralGoogleCloud` 来 `MistralGCP` (和 `MistralGoogleCloudError` 来 `MistralGCPError`)以与Python SDK保持一致。

## SDK安装

### NPM

```bash
npm add @mistralai/mistralai-gcp
```

### 规划

```bash
pnpm add @mistralai/mistralai-gcp
```

### 包子

```bash
bun add @mistralai/mistralai-gcp
```

### 纱

```bash
yarn add @mistralai/mistralai-gcp zod

# Note that Yarn does not install peer dependencies automatically. You will need
# to install zod as shown above.
```

## 要求

有关支持的JavaScript运行时，请咨询 [RUNTIMES.md](https://github.com/mistralai/client-ts/blob/main/packages/mistralai-gcp/RUNTIMES.md).

## SDK使用示例

### 创建聊天完成

这个例子展示了如何创建聊天完成。

```typescript
import { MistralGCP } from "@mistralai/mistralai-gcp";

const sdk = new MistralGCP({
  region: "europe-west4",
  projectId: process.env["GOOGLE_PROJECT_ID"],
});

async function run() {
  const result = await sdk.chat.complete({
    model: "mistral-small-latest",
    messages: [
      {
        content:
          "Who is the best French painter? Answer in one short sentence.",
        role: "user",
      },
    ],
  });

  // Handle the result
  console.log(result);
}

run();
```

## 可用资源和操作

### [闲谈，聊天](https://github.com/mistralai/client-ts/blob/main/packages/mistralai-gcp/docs/sdks/chat/README.md)

-   [流](https://github.com/mistralai/client-ts/blob/main/packages/mistralai-gcp/docs/sdks/chat/README.md#stream) -流聊天完成
-   [创建](https://github.com/mistralai/client-ts/blob/main/packages/mistralai-gcp/docs/sdks/chat/README.md#create) -聊天完成

### [鱼翅](https://github.com/mistralai/client-ts/blob/main/packages/mistralai-gcp/docs/sdks/fim/README.md)

-   [创建](https://github.com/mistralai/client-ts/blob/main/packages/mistralai-gcp/docs/sdks/fim/README.md#create) -影片完成

## 服务器发送的事件流

[服务器发送的事件](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) 是用来从某些流内容 操作。这些操作将把流公开为一个async可迭代对象 可以使用 [`for await...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) 循环。循环将会 当服务器不再有任何事件要发送时终止，并关闭 潜在的联系。

```typescript
import { MistralGCP } from "@mistralai/mistralai-gcp";

const sdk = new MistralGCP({
  region: "europe-west4",
  projectId: process.env["GOOGLE_PROJECT_ID"],
});

async function run() {
  const result = await sdk.chat.stream({
    model: "mistral-small-latest",
    messages: [
      {
        content:
          "Who is the best French painter? Answer in one short sentence.",
        role: "user",
      },
    ],
  });

  for await (const event of result) {
    // Handle the event
  }
}

run();
```

## 重试

这个SDK中的一些端点支持重试。如果您在没有任何配置的情况下使用SDK，它将退回到API提供的默认重试策略。但是，可以在每个操作的基础上或在整个SDK上重写默认的重试策略。

要更改单个API调用的默认重试策略，只需为调用提供一个retryConfig对象：

```typescript
import { MistralGCP } from "@mistralai/mistralai-gcp";

const sdk = new MistralGCP({
  region: "europe-west4",
  projectId: process.env["GOOGLE_PROJECT_ID"],
});

async function run() {
  const result = await sdk.chat.stream(
    {
      model: "mistral-small-latest",
      messages: [
        {
          content:
            "Who is the best French painter? Answer in one short sentence.",
          role: "user",
        },
      ],
    },
    {
      retries: {
        strategy: "backoff",
        backoff: {
          initialInterval: 1,
          maxInterval: 50,
          exponent: 1.1,
          maxElapsedTime: 100,
        },
        retryConnectionErrors: false,
      },
    },
  );

  for await (const event of result) {
    // Handle the event
  }
}

run();
```

如果你想覆盖所有支持重试的操作的默认重试策略，你可以在SDK初始化时提供一个retryConfig：

```typescript
import { MistralGCP } from "@mistralai/mistralai-gcp";

const sdk = new MistralGCP({
  retryConfig: {
    strategy: "backoff",
    backoff: {
      initialInterval: 1,
      maxInterval: 50,
      exponent: 1.1,
      maxElapsedTime: 100,
    },
    retryConnectionErrors: false,
  },
  region: "europe-west4",
  projectId: process.env["GOOGLE_PROJECT_ID"],
});

async function run() {
  const result = await sdk.chat.stream({
    model: "mistral-small-latest",
    messages: [
      {
        content:
          "Who is the best French painter? Answer in one short sentence.",
        role: "user",
      },
    ],
  });

  for await (const event of result) {
    // Handle the event
  }
}

run();
```

## 错误处理

所有SDK方法都返回一个响应对象或抛出一个错误。如果在OpenAPI规范中指定了错误对象，SDK将抛出适当的错误类型。

| 错误的对象 | 状态码 | 内容类型 |
| --- | --- | --- |
| 错误。HTTPValidationError | 422 | application / json |
| 错误。SDKError | 4 xx-5xx | _/_ |

当方法参数或从服务器返回的数据与预期格式不匹配时，也可能发生验证错误。这个 `SDKValidationError` 将捕获在调用的属性中验证失败的原始值 `rawValue`． 此外,一个 `pretty()` 方法可用于记录格式化良好的字符串，因为验证错误可能列出许多问题，并且在调试时普通错误字符串可能难以读取。

```typescript
import { MistralGCP } from "@mistralai/mistralai-gcp";
import { SDKValidationError } from "@mistralai/mistralai-gcp/models/errors";

const sdk = new MistralGCP({
  region: "europe-west4",
  projectId: process.env["GOOGLE_PROJECT_ID"],
});

async function run() {
  let result;
  try {
    result = await sdk.chat.complete({
      model: "mistral-small-latest",
      messages: [
        {
          content:
            "Who is the best French painter? Answer in one short sentence.",
          role: "user",
        },
      ],
    });
  } catch (err) {
    switch (true) {
      case err instanceof SDKValidationError: {
        // Validation errors can be pretty-printed
        console.error(err.pretty());
        // Raw value may also be inspected
        console.error(err.rawValue);
        return;
      }
      case err instanceof errors.HTTPValidationError: {
        console.error(err); // handle exception
        return;
      }
      default: {
        throw err;
      }
    }
  }

  // Handle the result
  console.log(result);
}

run();
```

## 服务器选择

### 按名称选择服务器

方法传递服务器名称，可以全局覆盖默认服务器 `server` 初始化SDK客户端实例时的可选参数。然后，所选服务器将被用作使用它的操作的默认服务器。该表列出了与可用服务器相关的名称：

| 名字 | 服务器 | 变量 |
| --- | --- | --- |
| `prod` | `https://api.mistral.ai` | 无 |

```typescript
import { MistralGCP } from "@mistralai/mistralai-gcp";

const sdk = new MistralGCP({
  server: "prod",
  region: "europe-west4",
  projectId: process.env["GOOGLE_PROJECT_ID"],
});

async function run() {
  const result = await sdk.chat.stream({
    model: "mistral-small-latest",
    messages: [
      {
        content:
          "Who is the best French painter? Answer in one short sentence.",
        role: "user",
      },
    ],
  });

  for await (const event of result) {
    // Handle the event
  }
}

run();
```

### 覆盖每个客户端的服务器URL

方法传递一个URL，也可以全局覆盖默认服务器 `serverURL` 初始化SDK客户端实例时的可选参数。例如:

```typescript
import { MistralGCP } from "@mistralai/mistralai-gcp";

const sdk = new MistralGCP({
  serverURL: "https://api.mistral.ai",
  region: "europe-west4",
  projectId: process.env["GOOGLE_PROJECT_ID"],
});

async function run() {
  const result = await sdk.chat.stream({
    model: "mistral-small-latest",
    messages: [
      {
        content:
          "Who is the best French painter? Answer in one short sentence.",
        role: "user",
      },
    ],
  });

  for await (const event of result) {
    // Handle the event
  }
}

run();
```

## 自定义HTTP客户机

TypeScript SDK使用 `HTTPClient` 这就封装了本地代码 [获取API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)。这 客户端是一个薄薄的包装 `fetch` 并提供附加钩子的能力 围绕请求生命周期，可用于修改请求或处理 错误和响应。

这个 `HTTPClient` 构造函数接受可选的 `fetcher` 论证可以是 用于集成第三方HTTP客户端或编写模拟测试时 HTTP客户端和提要在fixture中。

控件的使用方法 `"beforeRequest"` 钩到加一个 自定义标头和请求超时以及如何使用 `"requestError"` 钩 要记录错误：

```typescript
import { MistralGCP } from "@mistralai/mistralai-gcp";
import { HTTPClient } from "@mistralai/mistralai-gcp/lib/http";

const httpClient = new HTTPClient({
  // fetcher takes a function that has the same signature as native `fetch`.
  fetcher: (request) => {
    return fetch(request);
  },
});

httpClient.addHook("beforeRequest", (request) => {
  const nextRequest = new Request(request, {
    signal: request.signal || AbortSignal.timeout(5000),
  });

  nextRequest.headers.set("x-custom-header", "custom value");

  return nextRequest;
});

httpClient.addHook("requestError", (error, request) => {
  console.group("Request Error");
  console.log("Reason:", `${error}`);
  console.log("Endpoint:", `${request.method} ${request.url}`);
  console.groupEnd();
});

const sdk = new MistralGCP({ httpClient });
```

## 身份验证

### 每客户端安全方案

本SDK全局支持以下安全方案：

| 名字 | 类型 | 计划 |
| --- | --- | --- |
| `apiKey` | http | HTTP无记名 |

的API进行身份验证 `apiKey` 参数在初始化SDK客户端实例时必须设置。例如:

```typescript
import { MistralGCP } from "@mistralai/mistralai-gcp";

const sdk = new MistralGCP({
  region: "europe-west4",
  projectId: process.env["GOOGLE_PROJECT_ID"],
});

async function run() {
  const result = await sdk.chat.stream({
    model: "mistral-small-latest",
    messages: [
      {
        content:
          "Who is the best French painter? Answer in one short sentence.",
        role: "user",
      },
    ],
  });

  for await (const event of result) {
    // Handle the event
  }
}

run();
```

# 开发

## 贡献

虽然我们重视对这个SDK的开源贡献，但这个库是通过编程生成的。添加到内部文件的任何手动更改将在下一代中被覆盖。 我们期待听到您的反馈。请随意打开PR或概念验证问题，我们将尽最大努力将其包含在未来的版本中。

## 常见问题

### @mistralai/mistralai-gcp 是什么？

谷歌云上Mistral AI的TypeScript客户端库

### 如何安装 @mistralai/mistralai-gcp？

在项目目录运行 npm install @mistralai/mistralai-gcp，或使用 pnpm add / yarn add / bun add。

### @mistralai/mistralai-gcp 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @mistralai/mistralai-gcp 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @mistralai/mistralai-gcp 可以商用吗？

@mistralai/mistralai-gcp 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @mistralai/mistralai-gcp 还在维护吗？

最新版本 2\.1\.0 发布于 2026/11/02（1 天前）；至今共发布 21 个版本，其中过去 12 个月发布了 6 个；首次发布于 2024/07/30。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

