当前位置:首页>文章>使用指南>Gemini多场景-Java代码示例

Gemini多场景-Java代码示例

文本是《工具配置(共38篇)》专题的第 36 篇。阅读本文前,建议先阅读前面的文章:

资源准备

如使用 yibuapi.com 中转:将 base_url 改为 https://yibuapi.com,并使用你在 yibuapi 控制台创建的 API Key。

OpenAI 兼容性:用 OpenAI SDK 访问 Gemini(Markdown 版)

本文示例展示如何直接使用 OpenAI 官方 SDK(Python/JS/REST 兼容风格)调用 Gemini 模型,只需改动三行配置,即可在不改业务代码的前提下完成迁移与共存。


三行改动(Only 3 lines)

  1. API Key

    • apiKey="sk-***"(JS)或 api_key="sk-***"(Python)
    • "sk-***" 替换为你在 Google AI Studio 创建的实际密钥。
  2. Base URL

    • baseURL="https://yibuapi.com"
  3. Model

    • model="gemini-2.0-flash"(或其他兼容 Gemini 模型)

快速上手(JavaScript / TypeScript)

import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: "sk-***",
  baseURL: "https://yibuapi.com"
});

const response = await openai.chat.completions.create({
  model: "gemini-2.0-flash",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Explain to me how AI works" }
  ],
});

console.log(response.choices[0].message);

思考(Reasoning)与思考预算(Thinking Budget)

OpenAI SDK 兼容的 Gemini 2.5 系列支持推理控制:

  • reasoning_effort: "low" | "medium" | "high" | "none"
  • extra_body.google.thinking_config.thinking_budget: 指定精确思考 token 预算

二者不能同时使用。


流式输出(Streaming)

import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: "sk-***",
  baseURL: "https://yibuapi.com"
});

async function main() {
  const completion = await openai.chat.completions.create({
    model: "gemini-2.0-flash",
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: "Hello!" }
    ],
    stream: true,
  });

  for await (const chunk of completion) {
    process.stdout.write(chunk?.choices?.[0]?.delta?.content ?? "");
  }
}
main();

函数调用(Function Calling)

import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: "sk-***",
  baseURL: "https://yibuapi.com"
});

async function main() {
  const messages = [{ role: "user", content: "What's the weather like in Chicago today?" }];

  const tools = [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "Get the weather in a given location",
        parameters: {
          type: "object",
          properties: {
            location: { type: "string" },
            unit: { type: "string", enum: ["celsius", "fahrenheit"] }
          },
          required: ["location"]
        }
      }
    }
  ];

  const resp = await openai.chat.completions.create({
    model: "gemini-2.0-flash",
    messages,
    tools,
    tool_choice: "auto",
  });

  console.log(resp);
}
main();

图片理解(Vision)

import OpenAI from "openai";
import fs from "fs/promises";

const openai = new OpenAI({
  apiKey: "sk-***",
  baseURL: "https://yibuapi.com"
});

async function encodeImage(imagePath: string) {
  const buf = await fs.readFile(imagePath);
  return buf.toString("base64");
}

async function main() {
  const base64Image = await encodeImage("Path/to/agi/image.jpeg");

  const messages = [
    {
      role: "user",
      content: [
        { type: "text", text: "What is in this image?" },
        { type: "image_url", image_url: { url: `data:image/jpeg;base64,${base64Image}` } }
      ]
    }
  ];

  const resp = await openai.chat.completions.create({
    model: "gemini-2.0-flash",
    messages
  });

  console.log(resp.choices[0]);
}
main();

Embeddings(文本向量)

import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: "sk-***",
  baseURL: "https://yibuapi.com"
});

async function main() {
  const embedding = await openai.embeddings.create({
    model: "gemini-embedding-001",
    input: "Your text string goes here"
  });

  console.log(embedding);
}
main();

模型管理

const openai = new OpenAI({
  apiKey: "sk-***",
  baseURL: "https://yibuapi.com"
});

const list = await openai.models.list();
for await (const model of list) console.log(model);

使用指南

gpt-image-1-Python示例代码

2025-10-16 10:05:27

使用指南

# 🚀 四大AI巨头巅峰对决:GPT-5 vs Claude 4.5 vs Gemini 2.5 Pro vs DeepSeek V3.1

2025-10-20 9:56:27

搜索