[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-7294f442-b95a-4511-8021-3b87181fb19e":3,"$fL1_40ybqr8V2L-_mrb1dJgP0vIwHaq4EjBZ7EM2WYW4":42},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":33},"7294f442-b95a-4511-8021-3b87181fb19e","gemini-api-integration","用于将Google Gemini API集成到项目中。涵盖模型选择、多模态输入、流式传输、函数调用和生产最佳实践。","cat_coding_backend","mod_coding","sickn33,coding","---\nname: gemini-api-integration\ndescription: \"Use when integrating Google Gemini API into projects. Covers model selection, multimodal inputs, streaming, function calling, and production best practices.\"\nrisk: safe\nsource: community\ndate_added: \"2026-03-04\"\n---\n\n# Gemini API Integration\n\n## Overview\n\nThis skill guides AI agents through integrating Google Gemini API into applications — from basic text generation to advanced multimodal, function calling, and streaming use cases. It covers the full Gemini SDK lifecycle with production-grade patterns.\n\n## When to Use This Skill\n\n- Use when setting up Gemini API for the first time in a Node.js, Python, or browser project\n- Use when implementing multimodal inputs (text + image\u002Faudio\u002Fvideo)\n- Use when adding streaming responses to improve perceived latency\n- Use when implementing function calling \u002F tool use with Gemini\n- Use when optimizing model selection (Flash vs Pro vs Ultra) for cost and performance\n- Use when debugging Gemini API errors, rate limits, or quota issues\n\n## Step-by-Step Guide\n\n### 1. Installation & Setup\n\n**Node.js \u002F TypeScript:**\n```bash\nnpm install @google\u002Fgenerative-ai\n```\n\n**Python:**\n```bash\npip install google-generativeai\n```\n\nSet your API key securely:\n```bash\nexport GEMINI_API_KEY=\"your-api-key-here\"\n```\n\n### 2. Basic Text Generation\n\n**Node.js:**\n```javascript\nimport { GoogleGenerativeAI } from \"@google\u002Fgenerative-ai\";\n\nconst genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);\nconst model = genAI.getGenerativeModel({ model: \"gemini-1.5-flash\" });\n\nconst result = await model.generateContent(\"Explain async\u002Fawait in JavaScript\");\nconsole.log(result.response.text());\n```\n\n**Python:**\n```python\nimport google.generativeai as genai\nimport os\n\ngenai.configure(api_key=os.environ[\"GEMINI_API_KEY\"])\nmodel = genai.GenerativeModel(\"gemini-1.5-flash\")\n\nresponse = model.generate_content(\"Explain async\u002Fawait in JavaScript\")\nprint(response.text)\n```\n\n### 3. Streaming Responses\n\n```javascript\nconst result = await model.generateContentStream(\"Write a detailed blog post about AI\");\n\nfor await (const chunk of result.stream) {\n  process.stdout.write(chunk.text());\n}\n```\n\n### 4. Multimodal Input (Text + Image)\n\n```javascript\nimport fs from \"fs\";\n\nconst imageData = fs.readFileSync(\"screenshot.png\");\nconst imagePart = {\n  inlineData: {\n    data: imageData.toString(\"base64\"),\n    mimeType: \"image\u002Fpng\",\n  },\n};\n\nconst result = await model.generateContent([\"Describe this image:\", imagePart]);\nconsole.log(result.response.text());\n```\n\n### 5. Function Calling \u002F Tool Use\n\n```javascript\nconst tools = [{\n  functionDeclarations: [{\n    name: \"get_weather\",\n    description: \"Get current weather for a city\",\n    parameters: {\n      type: \"OBJECT\",\n      properties: {\n        city: { type: \"STRING\", description: \"City name\" },\n      },\n      required: [\"city\"],\n    },\n  }],\n}];\n\nconst model = genAI.getGenerativeModel({ model: \"gemini-1.5-pro\", tools });\nconst result = await model.generateContent(\"What's the weather in Mumbai?\");\n\nconst call = result.response.functionCalls()?.[0];\nif (call) {\n  \u002F\u002F Execute the actual function\n  const weatherData = await getWeather(call.args.city);\n  \u002F\u002F Send result back to model\n}\n```\n\n### 6. Multi-turn Chat\n\n```javascript\nconst chat = model.startChat({\n  history: [\n    { role: \"user\", parts: [{ text: \"You are a helpful coding assistant.\" }] },\n    { role: \"model\", parts: [{ text: \"Sure! I'm ready to help with code.\" }] },\n  ],\n});\n\nconst response = await chat.sendMessage(\"How do I reverse a string in Python?\");\nconsole.log(response.response.text());\n```\n\n### 7. Model Selection Guide\n\n| Model | Best For | Speed | Cost |\n|-------|----------|-------|------|\n| `gemini-1.5-flash` | High-throughput, cost-sensitive tasks | Fast | Low |\n| `gemini-1.5-pro` | Complex reasoning, long context | Medium | Medium |\n| `gemini-2.0-flash` | Latest fast model, multimodal | Very Fast | Low |\n| `gemini-2.0-pro` | Most capable, advanced tasks | Slow | High |\n\n## Best Practices\n\n- ✅ **Do:** Use `gemini-1.5-flash` for most tasks — it's fast and cost-effective\n- ✅ **Do:** Always stream responses for user-facing chat UIs to reduce perceived latency\n- ✅ **Do:** Store API keys in environment variables, never hard-code them\n- ✅ **Do:** Implement exponential backoff for rate limit (429) errors\n- ✅ **Do:** Use `systemInstruction` to set persistent model behavior\n- ❌ **Don't:** Use `gemini-pro` for simple tasks — Flash is cheaper and faster\n- ❌ **Don't:** Send large base64 images inline for files > 20MB — use File API instead\n- ❌ **Don't:** Ignore safety ratings in responses for production apps\n\n## Error Handling\n\n```javascript\ntry {\n  const result = await model.generateContent(prompt);\n  return result.response.text();\n} catch (error) {\n  if (error.status === 429) {\n    \u002F\u002F Rate limited — wait and retry with exponential backoff\n    await new Promise(r => setTimeout(r, 2 ** retryCount * 1000));\n  } else if (error.status === 400) {\n    \u002F\u002F Invalid request — check prompt or parameters\n    console.error(\"Invalid request:\", error.message);\n  } else {\n    throw error;\n  }\n}\n```\n\n## Troubleshooting\n\n**Problem:** `API_KEY_INVALID` error\n**Solution:** Ensure `GEMINI_API_KEY` environment variable is set and the key is active in Google AI Studio.\n\n**Problem:** Response blocked by safety filters\n**Solution:** Check `result.response.promptFeedback.blockReason` and adjust your prompt or safety settings.\n\n**Problem:** Slow response times\n**Solution:** Switch to `gemini-1.5-flash` and enable streaming. Consider caching repeated prompts.\n\n**Problem:** `RESOURCE_EXHAUSTED` (quota exceeded)\n**Solution:** Check your quota in Google Cloud Console. Implement request queuing and exponential backoff.\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,140,1613,"2026-05-16 13:19:50",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":25,"skillCount":32,"createdAt":26},"后端开发","backend","mdi-server","API、数据库、服务端架构",296,[34],{"id":35,"skillId":4,"version":36,"fileName":37,"fileSize":38,"filePath":39,"fileHash":40,"manifest":41,"createdAt":19},"db202833-e95b-4c16-8f6e-6710a00f653a","1.0.0","gemini-api-integration.zip",2747,"uploads\u002Fskills\u002F7294f442-b95a-4511-8021-3b87181fb19e\u002Fgemini-api-integration.zip","14867ff871fb72bc96819a7791e7bfc711c56f1035867cc4bb0604e5cffcd487","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":6073}]",{"code":43,"message":44,"data":45},200,"success",{"items":46,"stats":47,"page":50},[],{"averageRating":48,"totalRatings":48,"ratingCounts":49},0,[48,48,48,48,48],{"limit":51,"offset":48,"hasMore":52,"nextOffset":51,"ratedOnly":16},15,false]