> ## Documentation Index
> Fetch the complete documentation index at: https://quwan-b8010aef.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Gemini 基础对话示例

> 使用Gemini API进行基础文本生成的完整示例代码

# Gemini 基础对话示例

以下示例展示如何使用Gemini的 `/v1beta/models/{model}:generateContent` 接口进行基础文本生成。

## 快速开始

只需要替换 `<API-KEY>` 为你的实际API密钥即可运行。

```bash cURL theme={null}
curl -X POST "https://api.tokenops.ai/v1beta/models/gemini-2.5-flash:generateContent" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <API-KEY>" \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "你好，请介绍一下你自己"
          }
        ]
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 3000,
      "temperature": 0.7
    }
  }'
```

```python Python theme={null}
import requests
import json

# 配置API密钥和基础URL
API_KEY = "<API-KEY>"
BASE_URL = "https://api.tokenops.ai/v1beta"

def chat_with_gemini(message, model="gemini-2.5-flash"):
    url = f"{BASE_URL}/models/{model}:generateContent"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {API_KEY}"
    }
    
    data = {
        "contents": [
            {
                "parts": [
                    {
                        "text": message
                    }
                ]
            }
        ],
        "generationConfig": {
            "maxOutputTokens": 3000,
            "temperature": 0.7
        }
    }
    
    response = requests.post(url, headers=headers, json=data)
    
    if response.status_code == 200:
        result = response.json()
        return result['candidates'][0]['content']['parts'][0]['text']
    else:
        return f"错误: {response.status_code} - {response.text}"

# 使用示例
if __name__ == "__main__":
    message = "你好，请介绍一下你自己"
    reply = chat_with_gemini(message)
    print(f"Gemini回复: {reply}")
```

```javascript JavaScript/Node.js theme={null}
const axios = require('axios');

// 配置API密钥和基础URL
const API_KEY = '<API-KEY>';
const BASE_URL = 'https://api.tokenops.ai/v1beta';

async function chatWithGemini(message, model = 'gemini-2.5-flash') {
    const url = `${BASE_URL}/models/${model}:generateContent`;
    
    const headers = {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`
    };
    
    const data = {
        contents: [
            {
                parts: [
                    {
                        text: message
                    }
                ]
            }
        ],
        generationConfig: {
            maxOutputTokens: 3000,
            temperature: 0.7
        }
    };
    
    try {
        const response = await axios.post(url, data, { headers });
        return response.data.candidates[0].content.parts[0].text;
    } catch (error) {
        return `错误: ${error.response?.status} - ${error.response?.data || error.message}`;
    }
}

// 使用示例
(async () => {
    const message = '你好，请介绍一下你自己';
    const reply = await chatWithGemini(message);
    console.log(`Gemini回复: ${reply}`);
})();
```

```go Go theme={null}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

const (
    APIKey  = "<API-KEY>"
    BaseURL = "https://api.tokenops.ai/v1beta"
)

type Part struct {
    Text string `json:"text"`
}

type Content struct {
    Parts []Part `json:"parts"`
}

type GenerationConfig struct {
    MaxOutputTokens int     `json:"maxOutputTokens"`
    Temperature     float64 `json:"temperature"`
}

type GeminiRequest struct {
    Contents         []Content        `json:"contents"`
    GenerationConfig GenerationConfig `json:"generationConfig"`
}

type Candidate struct {
    Content Content `json:"content"`
}

type GeminiResponse struct {
    Candidates []Candidate `json:"candidates"`
}

func chatWithGemini(message string, model string) (string, error) {
    if model == "" {
        model = "gemini-2.5-flash"
    }
    
    url := fmt.Sprintf("%s/models/%s:generateContent", BaseURL, model)
    
    reqData := GeminiRequest{
        Contents: []Content{
            {
                Parts: []Part{
                    {
                        Text: message,
                    },
                },
            },
        },
        GenerationConfig: GenerationConfig{
            MaxOutputTokens: 3000,
            Temperature:     0.7,
        },
    }
    
    jsonData, err := json.Marshal(reqData)
    if err != nil {
        return "", err
    }
    
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    if err != nil {
        return "", err
    }
    
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", APIKey))
    
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()
    
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return "", err
    }
    
    if resp.StatusCode != 200 {
        return "", fmt.Errorf("API错误: %d - %s", resp.StatusCode, string(body))
    }
    
    var geminiResp GeminiResponse
    err = json.Unmarshal(body, &geminiResp)
    if err != nil {
        return "", err
    }
    
    return geminiResp.Candidates[0].Content.Parts[0].Text, nil
}

func main() {
    message := "你好，请介绍一下你自己"
    reply, err := chatWithGemini(message, "")
    if err != nil {
        fmt.Printf("错误: %v\n", err)
        return
    }
    
    fmt.Printf("Gemini回复: %s\n", reply)
}
```

```java Java theme={null}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
import java.util.Map;

public class GeminiBasicChat {
    private static final String API_KEY = "<API-KEY>";
    private static final String BASE_URL = "https://api.tokenops.ai/v1beta";
    
    public static String chatWithGemini(String message, String model) throws IOException, InterruptedException {
        if (model == null || model.isEmpty()) {
            model = "gemini-2.5-flash";
        }
        
        HttpClient client = HttpClient.newHttpClient();
        ObjectMapper mapper = new ObjectMapper();
        
        Map<String, Object> request = Map.of(
            "contents", List.of(
                Map.of("parts", List.of(
                    Map.of("text", message)
                ))
            ),
            "generationConfig", Map.of(
                "maxOutputTokens", 3000,
                "temperature", 0.7
            )
        );
        
        String jsonBody = mapper.writeValueAsString(request);
        
        HttpRequest httpRequest = HttpRequest.newBuilder()
            .uri(URI.create(BASE_URL + "/models/" + model + ":generateContent"))
            .header("Content-Type", "application/json")
            .header("Authorization", "Bearer " + API_KEY)
            .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
            .build();
        
        HttpResponse<String> response = client.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        
        if (response.statusCode() == 200) {
            JsonNode jsonResponse = mapper.readTree(response.body());
            return jsonResponse.get("candidates").get(0)
                .get("content").get("parts").get(0).get("text").asText();
        } else {
            throw new RuntimeException("API错误: " + response.statusCode() + " - " + response.body());
        }
    }
    
    public static void main(String[] args) {
        try {
            String message = "你好，请介绍一下你自己";
            String reply = chatWithGemini(message, "gemini-2.5-flash");
            System.out.println("Gemini回复: " + reply);
        } catch (Exception e) {
            System.err.println("错误: " + e.getMessage());
        }
    }
}
```

```php PHP theme={null}
<?php

class GeminiBasicChat {
    private $apiKey;
    private $baseUrl;
    
    public function __construct($apiKey, $baseUrl = 'https://api.tokenops.ai/v1beta') {
        $this->apiKey = $apiKey;
        $this->baseUrl = $baseUrl;
    }
    
    public function chatWithGemini($message, $model = 'gemini-2.5-flash') {
        $url = $this->baseUrl . '/models/' . $model . ':generateContent';
        
        $data = [
            'contents' => [
                [
                    'parts' => [
                        [
                            'text' => $message
                        ]
                    ]
                ]
            ],
            'generationConfig' => [
                'maxOutputTokens' => 3000,
                'temperature' => 0.7
            ]
        ];
        
        $options = [
            'http' => [
                'header' => [
                    'Content-Type: application/json',
                    'Authorization: Bearer ' . $this->apiKey
                ],
                'method' => 'POST',
                'content' => json_encode($data)
            ]
        ];
        
        $context = stream_context_create($options);
        $response = file_get_contents($url, false, $context);
        
        if ($response === FALSE) {
            return '请求失败';
        }
        
        $responseData = json_decode($response, true);
        
        if (isset($responseData['candidates'][0]['content']['parts'][0]['text'])) {
            return $responseData['candidates'][0]['content']['parts'][0]['text'];
        } else {
            return '解析响应失败: ' . $response;
        }
    }
}

// 使用示例
$apiKey = '<API-KEY>';
$chat = new GeminiBasicChat($apiKey);

$message = '你好，请介绍一下你自己';
$reply = $chat->chatWithGemini($message);

echo "Gemini回复: " . $reply . "\n";

?>
```

## 结果示例

```bash 200 theme={null}
{
  "sdkHttpResponse": {
    "headers": {
      "Alt-Svc": [
        "h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000"
      ],
      "Content-Type": [
        "application/json; charset=UTF-8"
      ],
      "Date": [
        "Mon, 29 Sep 2025 07:44:45 GMT"
      ],
      "Server": [
        "scaffolding on HTTPServer2"
      ],
      "Vary": [
        "Origin",
        "X-Origin",
        "Referer"
      ],
      "X-Content-Type-Options": [
        "nosniff"
      ],
      "X-Frame-Options": [
        "SAMEORIGIN"
      ],
      "X-Xss-Protection": [
        "0"
      ]
    }
  },
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "你好！很高兴能介绍我自己。\n\n我是一个大型语言模型，由 Google 训练。\n\n我的主要能力包括：\n\n*   **理解并生成人类语言**：我可以理解你"
          }
        ],
        "role": "model"
      },
      "finishReason": "MAX_TOKENS",
      "avgLogprobs": -4.488159561157227
    }
  ],
  "createTime": "2025-09-29T07:44:40.11712Z",
  "modelVersion": "gemini-2.5-flash",
  "responseId": "c1ffee8d5e2342cd901652cbc6e99e5a",
  "usageMetadata": {
    "candidatesTokenCount": 40,
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 40
      }
    ],
    "promptTokenCount": 6,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 6
      }
    ],
    "thoughtsTokenCount": 958,
    "totalTokenCount": 1004,
    "trafficType": "ON_DEMAND"
  }
}
```

## 重要参数说明

* **contents**: 输入内容数组，每个元素包含 `parts` 数组
* **parts**: 内容部分，包含 `text` 字段
* **generationConfig**: 生成配置
  * **maxOutputTokens**: 最大输出token数量
  * **temperature**: 控制输出随机性，0-2之间

## 错误处理

Gemini API的常见错误：

* **400 Bad Request**: 请求格式错误
* **401 Unauthorized**: API密钥无效
* **429 Too Many Requests**: 请求频率过高
* **503 Service Unavailable**: 服务暂时不可用


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.