Featured image of post 使用 Gemini 1.5 Pro 的海量上下文长度构建应用程序Featured image of post 使用 Gemini 1.5 Pro 的海量上下文长度构建应用程序

使用 Gemini 1.5 Pro 的海量上下文长度构建应用程序

在 Node Web 包装器中利用 Gemini 1.5 Pro 广泛的数百万令牌输入参数的强大功能。

上下文窗口革命

Gemini 1.5 Pro 通过提供高达200 万个令牌的上下文窗口,重新定义了大型语言模型的可能性。这意味着您可以在单个请求中传递整个代码库、数小时的视频或数千页文档——从根本上改变我们与人工智能交互的方式。

了解Gemini 1.5 Pro的功能

特色能力
上下文窗口高达 2M 代币(1M 标准)
输入方式文字、图片、音频、视频、代码
输出文本、代码、结构化数据
最大输出令牌8,192
语言100 多种语言
定价(输入)每 100 万个代币 1.25-10.00 美元
定价(输出)每 100 万个代币 10.00-40.00 美元

多模式输入处理

Gemini 1.5 Pro 在单个请求中本机处理多种模式。您可以无缝组合文本、图像、音频和视频:

import { GoogleGenerativeAI } from "@google/generative-ai";

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-pro" });

// Multimodal request with text, image, and audio
const result = await model.generateContent([
  "Analyze this presentation recording and provide feedback:",
  { inlineData: { mimeType: "image/png", data: slideImageBase64 } },
  { inlineData: { mimeType: "audio/mpeg", data: narrationBase64 } },
]);

Node.js SDK 设置

适用于 JavaScript 的官方 Google AI SDK 简化了集成:

npm install @google/generative-ai
const { GoogleGenerativeAI } = require("@google/generative-ai");

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({
  model: "gemini-1.5-pro",
  systemInstruction: "You are an expert code reviewer.",
});

async function reviewCode(code) {
  const result = await model.generateContent(code);
  return result.response.text();
}

流式响应

对于实时应用程序,流式传输提供低延迟输出:

const streamingResult = await model.generateContentStream(prompt);

for await (const chunk of streamingResult.stream) {
  const chunkText = chunk.text();
  process.stdout.write(chunkText);
}

System Instructions

System instructions let you define the model’s behavior globally:

const model = genAI.getGenerativeModel({
  model: "gemini-1.5-pro",
  systemInstruction: `
    You are a senior TypeScript developer.
    Always provide type-safe code examples.
    Include JSDoc comments for all functions.
    Prefer functional programming patterns.
  `,
});

函数调用

函数调用支持结构化数据提取和外部工具使用:

const model = genAI.getGenerativeModel({
  model: "gemini-1.5-pro",
  tools: {
    functionDeclarations: [{
      name: "searchDocs",
      parameters: {
        type: "object",
        properties: {
          query: { type: "string" },
          maxResults: { type: "number" },
        },
      },
    }],
  },
});

使用案例

巨大的上下文窗口支持新颖的应用程序:

  1. 完整的代码库分析:通过整个存储库进行架构审查
  2. 视频内容理解:分析会议摘要的录制时间
  3. 长文档问答:查询数千页文档或法律合同
  4. 多文件代码生成:使用上下文生成整个功能实现
  5. 音频转录和分析:一次性将转录与语义理解结合起来

定价考虑因素

在上下文窗口较大的情况下,令牌使用量会快速增加。管理成本的策略:

  • 分块:策略性地分割大量输入
  • 缓存:缓存相同查询的响应
  • Prompt optimization: Minimize token usage in system instructions
  • 批处理:聚合相似的请求

结论

Gemini 1.5 Pro 的庞大上下文窗口从根本上扩展了法学硕士在应用程序中的可能性。通过多模式输入处理数百万个令牌上下文的能力使得新型人工智能驱动的工具能够在一次传递中对整个代码库、库或媒体集合进行推理。