使用免費Gemini API可以做12件事

使用免費Gemini API可以做12件事

文章目录

  • 如何獲取免費的Gemini API?
  • 第一部分:基礎提示技巧
  • 第二部分:引導模型的行為和知識
  • 第三部分:解鎖高階推理
  • 第四部分:Gemini的實際應用
  • 小結
  • 常見問題解答

使用免費Gemini API可以做12件事

大型語言模型 (LLM) 現在比以往任何時候都更容易獲得。Google 的 Gemini API 為開發者和創作者提供了強大而多功能的工具。本指南探討了您可以使用免費 Gemini API 實現的眾多實際應用。我們將透過幾個實際示例進行講解。您將學習關鍵的 Gemini API 提示技術,從簡單查詢到複雜任務。我們將介紹零樣本提示、Gemini 和小樣本提示等方法。您還將學習如何使用 Gemini 執行基本程式碼生成等任務,從而提高工作流程的效率。

如何獲取免費的Gemini API?

在開始之前,您需要設定您的環境。這個過程很簡單,只需幾分鐘。您需要一個 Google AI Studio API 金鑰才能啟動。

首先,安裝必要的 Python 庫。此軟體包允許您輕鬆地與 Gemini API 通訊。

!pip install -U -q "google-genai>=1.0.0"

接下來,配置您的 API 金鑰。您可以從 Google AI Studio 獲取免費金鑰。請妥善保管金鑰,並使用以下程式碼初始化客戶端。此設定是後續所有示例的基礎。

from google import genai
# Make sure to secure your API key
# For example, by using userdata in Colab
# from google.colab import userdata
# GOOGLE_API_KEY=userdata.get('GOOGLE_API_KEY')
client = genai.Client(api_key="YOUR_API_KEY")
MODEL_ID = "gemini-1.5-flash"

第一部分:基礎提示技巧

讓我們從兩種基本的 Gemini API 提示技巧開始。這些方法構成了更高階互動的基礎。

技巧 1:零樣本提示,快速獲得答案

零樣本提示是與 LLM 互動最簡單的方法。您可以直接提出問題,無需提供任何示例。這種方法適用於模型現有知識充足的簡單任務。對於有效的零樣本提示,清晰性是關鍵。

讓我們用它來對客戶評論的情緒進行分類。

提示詞:

prompt = """
   Classify the sentiment of the following review as positive, negative, or neutral:
   Review: "I go to this restaurant every week, I love it so much."
"""
response = client.models.generate_content(
   model=MODEL_ID,
   contents=prompt,
)
print(response.text)

輸出:

零樣本提示輸出

這種簡單的方法可以快速完成任務。這是使用 Gemini 免費 API 最常見的功能之一。

技巧 2:自定義格式的小樣本提示

有時,您需要特定格式的輸出。小樣本提示透過提供一些輸入和預期輸出的示例來指導模型。這項技巧可以幫助模型準確理解您的需求。

在這裡,我們將城市及其所屬國家/地區提取為 JSON 格式。

提示詞:

prompt = """
   Extract cities from the text and include the country they are in.
   USER: I visited Mexico City and Poznan last year
   MODEL: {"Mexico City": "Mexico", "Poznan": "Poland"}
   USER: She wanted to visit Lviv, Monaco and Maputo
   MODEL: {"Lviv": "Ukraine", "Monaco": "Monaco", "Maputo": "Mozambique"}
   USER: I am currently in Austin, but I will be moving to Lisbon soon
   MODEL:
"""
# We also specify the response should be JSON
generation_config = types.GenerationConfig(response_mime_type="application/json")
response = model.generate_content(
   contents=prompt,
   generation_config=generation_config
)
display(Markdown(f"```json\n{response.text}\n```"))

輸出:

自定義格式的小樣本提示輸出

透過提供示例,您可以教會模型您想要的精確結構。這是在基礎的零樣本提示 Gemini 基礎上的有力進步。

第二部分:引導模型的行為和知識

您可以控制模型的角色併為其提供特定的知識。這些 Gemini API 提示技巧可以讓您的互動更具針對性。

技巧 3:角色提示以定義角色

您可以為模型分配角色來影響其語氣和風格。這使得響應更加真實,並針對特定情境進行量身定製。

讓我們從德國導遊的角度詢問博物館推薦。

提示詞:

system_instruction = """
   You are a German tour guide. Your task is to give recommendations
   to people visiting your country.
"""
prompt = 'Could you give me some recommendations on art museums in Berlin and Cologne?'
model_with_role = genai.GenerativeModel(
   'gemini-2.5-flash-',
   system_instruction=system_instruction
)
response = model_with_role.generate_content(prompt)
display(Markdown(response.text))

輸出:

角色提示以定義角色輸出

模型會採用角色,使響應更具吸引力和實用性。

技巧 4:新增上下文以回答小眾問題

LLM 並非無所不知。您可以在提示中提供具體資訊,以幫助模型回答有關新資料或私人資料的問題。這是檢索增強生成 (RAG) 背後的核心概念。

在這裡,我們為模型提供了一個奧運會運動員表格來回答特定查詢。

提示詞:

prompt = """
 QUERY: Provide a list of athletes that competed in the Olympics exactly 9 times.
 CONTEXT:
 Table title: Olympic athletes and number of times they've competed
 Ian Millar, 10
 Hubert Raudaschl, 9
 Afanasijs Kuzmins, 9
 Nino Salukvadze, 9
 Piero d'Inzeo, 8
"""
response = model.generate_content(prompt)
display(Markdown(response.text))

輸出:

新增上下文以回答小眾問題

該模型僅使用提供的上下文來給出準確的答案。

技巧 5:提供基本案例以明確邊界

定義模型在無法滿足請求時的行為非常重要。提供基本案例或預設響應可以避免出現意外或偏離主題的答案。

讓我們建立一個職責有限的度假助手。

提示詞:

system_instruction = """
You are an assistant that helps tourists plan their vacation. Your responsibilities are:
1. Helping book the hotel.
2. Recommending restaurants.
3. Warning about potential dangers.
If another request is asked, return "I cannot help with this request."
"""
model_with_rules = genai.GenerativeModel(
   'gemini-1.5-flash-latest',
   system_instruction=system_instruction
)
# On-topic request
response_on_topic = model_with_rules.generate_content("What should I look out for on the beaches in San Diego?")
print("--- ON-TOPIC REQUEST ---")
display(Markdown(response_on_topic.text))
# Off-topic request
response_off_topic = model_with_rules.generate_content("What bowling places do you recommend in Moscow?")
print("\n--- OFF-TOPIC REQUEST ---")
display(Markdown(response_off_topic.text))

輸出:

提供基本案例以明確邊界

第三部分:解鎖高階推理

對於複雜問題,您需要引導模型的思維過程。這些推理技巧可以提高多步驟任務的準確性。

技巧 6:逐步解決方案的基本推理

您可以指示模型分解問題並解釋其步驟。這對於過程與答案同等重要的數學或邏輯問題非常有用。

在這裡,我們要求模型求解三角形的面積並展示其計算過程。

提示詞:

system_instruction = """
 You are a teacher solving mathematical problems. Your task:
 1. Summarize given conditions.
 2. Identify the problem.
 3. Provide a clear, step-by-step solution.
 4. Provide an explanation for each step.
"""
math_problem = "Given a triangle with base b=6 and height h=8, calculate its area."
reasoning_model = genai.GenerativeModel(
   'gemini-1.5-flash-latest',
   system_instruction=system_instruction
)
response = reasoning_model.generate_content(math_problem)
display(Markdown(response.text))

輸出:

逐步解決方案的基本推理

這種結構化的輸出清晰易懂。

技巧 7:複雜問題的思路鏈

思路鏈 (CoT) 提示鼓勵模型逐步思考。谷歌的研究表明,這顯著提升了複雜推理任務的效能。模型不僅僅是給出最終答案,還會解釋其推理路徑。

讓我們使用 CoT 來解決一個邏輯難題。

提示詞:

prompt = """
 Question: 11 factories can make 22 cars per hour. How much time would it take 22 factories to make 88 cars?
 Answer: A factory can make 22/11=2 cars per hour. 22 factories can make 22*2=44 cars per hour. Making 88 cars would take 88/44=2 hours. The answer is 2 hours.
 Question: 5 people can create 5 donuts every 5 minutes. How much time would it take 25 people to make 100 donuts?
 Answer:
"""
response = model.generate_content(prompt)
display(Markdown(response.text))

輸出:

複雜問題的思路鏈

該模型遵循以下模式,將問題分解為邏輯步驟。

技巧 8:自問式提示法解構問題

自問式提示法與 CoT 類似。該模型將一個主要問題分解為更小的後續問題。它會在得出最終答案之前回答每個子問題。

讓我們用這種方法來解決一個由多個部分組成的歷史問題。

提示詞:

prompt = """
 Question: Who was the president of the united states when Mozart died?
 Are follow up questions needed?: yes.
 Follow up: When did Mozart die?
 Intermediate answer: 1791.
 Follow up: Who was the president of the united states in 1791?
 Intermediate answer: George Washington.
 Final answer: When Mozart died George Washington was the president of the USA.
 Question: Where did the Emperor of Japan, who ruled the year Maria Skłodowska was born, die?
"""
response = model.generate_content(prompt)
display(Markdown(response.text))

輸出:

自問式提示法解構問題

這種結構化的思維過程有助於確保複雜查詢的準確性。

第四部分:Gemini的實際應用

現在,讓我們看看這些技術如何應用​​於常見的實際任務。探索這些示例,可以展示 Gemini 免費 API 的廣泛用途。

技巧 9:文字分類,用於稽覈和分析

您可以使用 Gemini 自動分類文字。這對於內容稽覈等需要識別垃圾評論或辱罵性評論的任務非常有用。Gemini 使用小樣本提示,幫助模型學習您的特定類別。

提示詞:

classification_template = """
 Topic: Where can I buy a cheap phone?
 Comment: You have just won an IPhone 15 Pro Max!!! Click the link!!!
 Class: Spam
 Topic: How long do you boil eggs?
 Comment: Are you stupid?
 Class: Offensive
 Topic: {topic}
 Comment: {comment}
 Class:
"""
spam_topic = "I am looking for a vet in our neighbourhood."
spam_comment = "You can win 1000$ by just following me!"
spam_prompt = classification_template.format(topic=spam_topic, comment=spam_comment)
response = model.generate_content(spam_prompt)
display(Markdown(response.text))

輸出:

文字分類,用於稽覈和分析

技巧 10:從文字中提取結構化資訊

Gemini 可以從非結構化文字中提取特定資訊。這可以幫助您將純文字(例如食譜)轉換為結構化格式(例如購物清單)。

提示詞:

recipe = """
 Grind 3 garlic cloves, a knob of fresh ginger, and 3 spring onions to a paste.
 Add 2 tbsp of clear honey, juice from one orange, and 1 tbsp of light soy sauce.
 Pour the mixture over 4 small chicken breast fillets.
"""
# Step 1: Extract the list of groceries
extraction_prompt = f"""
Your task is to extract to a list all the groceries with its quantities based on the provided recipe.
Make sure that groceries are in the order of appearance.
Recipe:{recipe}
"""
extraction_response = model.generate_content(extraction_prompt)
grocery_list = extraction_response.text
print("--- Extracted Groceries ---")
display(Markdown(grocery_list))
# Step 2: Format the extracted list into a shopping list
formatting_system_instruction = "Organize groceries into categories for easier shopping. List each item with a checkbox []."
formatting_prompt = f"""
 LIST: {grocery_list}
 OUTPUT:
"""
formatting_model = genai.GenerativeModel(
   'gemini-2.5-flash',
   system_instruction=formatting_system_instruction
)
formatting_response = formatting_model.generate_content(formatting_prompt)
print("\n--- Formatted Shopping List ---")
display(Markdown(formatting_response.text))

輸出:

從文字中提取結構化資訊

技巧 11:基本程式碼生成和除錯

Gemini 的基本程式碼生成功能非常強大。它可以編寫程式碼片段、解釋錯誤並提出修復建議。GitHub 的一項調查發現,使用 AI 程式設計工具的開發者開發速度提高了 55%。

讓我們使用 Gemini 為倒計時器生成一個 Python 指令碼。

提示詞:

code_generation_prompt = """
 Create a countdown timer in Python that ticks down every second and prints
 "Time is up!" after 20 seconds.
"""
response = model.generate_content(code_generation_prompt)
display(Markdown(f"```python\n{response.text}\n```"))

輸出:

基本程式碼生成和除錯

技巧 12:評估文字質量

你甚至可以使用 Gemini 來評估文字。這對於評分、提供反饋或確保內容質量非常有用。在這裡,我們將讓模型扮演老師的角色,對一篇寫得不好的文章進行評分。

提示詞:

teacher_system_instruction = """
   As a teacher, you are tasked with grading a student's essay.
   1. Evaluate the essay on a scale of 1-5 for clarity, grammar, and argumentation.
   2. Write a corrected version of the essay.
   3. Explain the changes made.
"""
essay = "Reading is like, a really good thing. It’s beneficial, you know? Like, a lot. When you read, you learn new words and that's good. Its like a secret code to being smart. I read a book last week and I know it was making me smarter. Therefore, books good, TV bad. So everyone should read more."
evaluation_model = genai.GenerativeModel(
   'gemini-1.5-flash-latest',
   system_instruction=teacher_system_instruction
)
response = evaluation_model.generate_content(essay)
display(Markdown(response.text))

輸出:

評估文字質量

小結

Gemini API 是一個靈活而強大的資源。我們探索了使用免費 Gemini API 可以實現的廣泛功能,從簡單的問題到高階推理和程式碼生成。透過掌握這些 Gemini API 的提示技巧,您可以構建更智慧、更高效的應用程式。關鍵在於實踐。將這些示例作為您自己專案的起點,探索您可以創造什麼。

常見問題解答

問題 1:使用免費的 Gemini API 可以實現哪些最佳功能?

答:您可以執行文字分類、資訊提取和摘要。它也非常適合執行基本程式碼生成和複雜推理等任務。

問題 2:零樣本提示 Gemini 和少樣本提示 Gemini 有什麼區別?

答:零樣本提示是指直接提出問題,無需示例。少樣本提示則為模型提供一些示例來指導其響應格式和風格。

問題 3:我可以使用 Gemini 進行基本的程式碼生成嗎?

答:是的,Gemini 可以生成程式碼片段、解釋程式設計概念並除錯錯誤。這有助於加快許多程式設計師的開發程序。

問題 4:角色提示如何改進模型響應?

答:分配角色可以賦予模型特定的角色和背景。這使得模型的響應具有更合適的語氣、風格和領域知識。

問題 5:什麼是思路鏈提示?

答:這是一種模型將問題分解為更小的、連續的步驟的技術。這有助於提高需要推理的複雜任務的準確性。

評論留言