
大型语言模型 (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:什么是思路链提示?
答:这是一种模型将问题分解为更小的、连续的步骤的技术。这有助于提高需要推理的复杂任务的准确性。


评论留言