> ## Documentation Index
> Fetch the complete documentation index at: https://docs.openp.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# google-genai SDK

> 用 Google 官方 SDK 通过 OpenPAI 调用 Gemini

Google 官方推荐的 SDK 是 `google-genai`(新版,替代旧 `google-generativeai`)。
通过设置 `http_options.base_url` 即可把请求指向 OpenPAI。

## Python

```bash theme={null}
pip install google-genai
```

```python theme={null}
from google import genai

client = genai.Client(
    api_key="sk-XXXXXXXXXXXXXXXX",
    http_options={"base_url": "https://openp.ai"},
)

resp = client.models.generate_content(
    model="gemini-3.1-pro-preview",
    contents="用一句话介绍 OpenPAI",
)
print(resp.text)
```

## JavaScript / TypeScript

```bash theme={null}
npm install @google/genai
```

```ts theme={null}
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({
  apiKey: process.env.OPENPAI_API_KEY!,
  httpOptions: { baseUrl: "https://openp.ai" },
});

const resp = await client.models.generateContent({
  model: "gemini-3.1-pro-preview",
  contents: "hello",
});
console.log(resp.text);
```

## 流式

```python theme={null}
stream = client.models.generate_content_stream(
    model="gemini-3.1-pro-preview",
    contents="讲个 100 字的故事",
)
for chunk in stream:
    print(chunk.text, end="", flush=True)
```

## 多模态

```python theme={null}
from google.genai import types

resp = client.models.generate_content(
    model="gemini-3.1-pro-preview",
    contents=[
        types.Part.from_uri(file_uri="https://example.com/x.png", mime_type="image/png"),
        "描述这张图。",
    ],
)
```

## 函数调用

```python theme={null}
weather_tool = types.Tool(function_declarations=[
    types.FunctionDeclaration(
        name="get_weather",
        description="Get weather of a city",
        parameters={
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    )
])

resp = client.models.generate_content(
    model="gemini-3.1-pro-preview",
    contents="北京天气",
    config=types.GenerateContentConfig(tools=[weather_tool]),
)
```

## 思考模式

```python theme={null}
resp = client.models.generate_content(
    model="gemini-3.1-pro-preview",
    contents="证明哥德巴赫猜想",
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(thinking_budget=8000),
    ),
)
```

或直接使用带后缀的模型 ID(更简单):

```python theme={null}
resp = client.models.generate_content(
    model="gemini-2.5-pro-thinking",
    contents="...",
)
```

## 嵌入

```python theme={null}
resp = client.models.embed_content(
    model="text-embedding-004",
    contents=["hello world"],
)
print(resp.embeddings[0].values[:5])
```

## 注意事项

* 使用 Gemini 原生协议时,Base URL **不带 `/v1`**(SDK 会自动补 `/v1beta/models/...` 路径)。
* 若你的代码原本走 OpenAI 兼容路径(`/v1/chat/completions`),可保持不变只切换模型 ID 到 `gemini-*`。
* OpenAI 兼容协议会自动把 Gemini 的 `parts` / `inline_data` 映射为 `content` 数组,反向亦然。
