The fastest way to get good code out of Gemini is to be specific: name the language and version, paste the actual file (or the whole codebase — Gemini 3.1 holds a 1M-token context), set the right thinking level, and ask it to explain its reasoning and list edge cases. The 26 prompts below are grouped by task and written to do exactly that. Fill in the [bracketed placeholders] and paste. For the wider method, see the best Gemini prompts roundup and the Gemini prompt cheat sheet.

Advertisement

Write new code

For new code, give Gemini the language and version, the exact signature or spec, and your constraints. Set Medium thinking for routine work and High for anything algorithmic. Always ask for reasoning and edge cases so you can catch a wrong assumption before you paste it.

1. Scaffold a typed function from a spec

You are a senior [language + version, e.g. TypeScript 5.4] engineer. Write a single function that does the following:

Spec:
[describe exactly what the function takes, returns, and does]

Constraints:
- Fully typed, no `any`.
- Pure where possible; no hidden global state.
- Handle these edge cases explicitly: [empty input, nulls, very large input, ...].
- Follow this style: [e.g. functional, early returns, no external deps].

Return: the function, then a short bullet list of the edge cases you handled and any assumptions you made. Do not include unrelated boilerplate.

Best for: a clean, self-contained function you can drop straight into a module.

2. Build a REST endpoint with validation

Set thinking to Medium. Framework: [e.g. Node.js + Express 5, or FastAPI 0.115]. Language: [language + version].

Build a [POST /resource] endpoint that:
- Accepts this JSON body: [paste the shape / fields and types].
- Validates every field and returns 400 with a clear error object on bad input.
- [Persists to / calls] [describe the store or service].
- Returns [status + response shape].

Requirements: input validation with [library, e.g. zod / pydantic], structured error responses, and no unhandled promise rejections. After the code, list the validation rules you applied and any security checks (auth, rate limiting) I should add next.

Best for: a production-shaped endpoint instead of a happy-path stub.

3. Generate a CLI tool

Language: [e.g. Python 3.12]. Write a small command-line tool called [name] that:

[describe what it does, e.g. "reads a CSV, filters rows where column X > N, writes the result to a new file"]

Requirements:
- Parse arguments with [argparse / click / the standard lib], with --help output.
- Validate inputs and exit with a non-zero code and a readable message on error.
- No third-party deps unless necessary; if you add one, justify it.

Return the full script as one file, plus example invocations and the expected output for each.

Best for: quick internal scripts and one-off automation you'll actually keep.

4. Implement an algorithm with complexity notes

Set thinking to High. Language: [language + version].

Implement [algorithm / problem, e.g. "an LRU cache with O(1) get and put"]. Requirements:
- Meet these complexity targets: [time / space].
- Handle these edge cases: [capacity 0, duplicate keys, eviction order, ...].

Before the code, briefly state your approach and why it meets the targets. Then give the implementation, then the time and space complexity of each public method, and 3 test inputs that would break a naive version.

Best for: data-structure and algorithm work where the reasoning matters as much as the code.

5. Build a React component from a screenshot

[Paste a screenshot of the UI/mockup.]

Build this as a [React 19 + TypeScript] component using [Tailwind / CSS modules / plain CSS]. Match the layout, spacing, and states shown in the image. Requirements:
- Typed props for anything dynamic in the design.
- Accessible: proper roles, labels, and keyboard focus.
- Responsive down to [360px].

Return the component, then note anything in the image you had to guess (exact colors, hover states) so I can confirm.

Best for: turning a design mockup into a real component using Gemini's multimodal input.

Advertisement

Debug & fix

For debugging, give Gemini everything: the failing code, the exact error (paste the stack trace or a screenshot of it), and what you expected. Set High thinking so it reasons about causes instead of guessing at the first plausible fix.

6. Diagnose an error from a stack trace

Set thinking to High. Language/runtime: [e.g. Node 22]. Here is the failing code and the full error.

Code:
[paste the relevant file(s)]

Error / stack trace:
[paste the complete trace]

What I expected: [expected behavior].
What happened: [actual behavior].

Walk through the trace to the root cause, explain WHY it happens (not just where), give the corrected code, and note any other places in this code that would hit the same bug.

Best for: real runtime errors where the top line of the trace isn't the real cause.

7. Debug from an error screenshot

[Paste a screenshot of the error — red overlay, terminal output, or CI log.]

This is from a [framework + version] app. Read the error in the image, then:
1. Tell me in one sentence what's wrong.
2. Explain the cause.
3. Give the exact fix (file + change).

If the screenshot doesn't contain enough to be sure, tell me exactly which file or line you need next instead of guessing.

Best for: when the error is easier to screenshot than to retype — Gemini reads it directly.

8. Find the bug in a function

Set thinking to High. This [language] function is supposed to [describe intended behavior] but returns [wrong result] for input [example].

[paste the function]

Find the bug. Show the exact line, explain the faulty logic, and give the corrected version. Then list the specific inputs (including edge cases) where the original would fail, so I can turn them into regression tests.

Best for: subtle logic bugs where the code runs but gives wrong output.

9. Fix a failing test

Here is a failing test and the code under test. Test runner: [e.g. Jest / pytest].

Test:
[paste the test]

Code under test:
[paste the implementation]

Failure output:
[paste the assertion / error]

Decide whether the bug is in the code or the test, and say which. Then give the corrected version of whichever is wrong, and explain your reasoning. Do not change the test's intent to make it pass.

Best for: red CI, where you need to know if the test or the code is actually wrong.

10. Trace an intermittent race condition

Set thinking to High. This [language, e.g. Go 1.23 / async TypeScript] code works most of the time but occasionally [describe the flaky symptom]. I suspect a race condition or ordering issue.

[paste the relevant concurrent code]

Reason step by step about interleavings and shared state. Identify the specific sequence that causes the failure, explain it, and propose a fix (lock, channel, atomic, restructured await) with the trade-offs of each option.

Best for: flaky, hard-to-reproduce concurrency bugs where you need explicit reasoning.

Refactor & optimize

For refactors, paste the whole file or module so Gemini can see the surrounding usage, and tell it what to preserve. Ask it to keep behavior identical unless you say otherwise, and to explain each change.

11. Refactor for readability

Refactor this [language] code for readability and maintainability without changing its behavior.

[paste the file]

Goals: clearer names, smaller functions, fewer nested branches, and no dead code. Keep the public API and all outputs identical. Follow [style guide / conventions]. Return the refactored code, then a short list of what you changed and why — call out anything where behavior might subtly differ so I can verify.

Best for: cleaning up code you inherited without altering what it does.

12. Optimize a slow function

Set thinking to High. This [language] function is a performance bottleneck. It processes [describe the data + scale, e.g. "up to 500k records"] and currently takes [time].

[paste the function]

Analyze its time and space complexity, identify what dominates, and rewrite it to be faster while keeping the same output. Explain the complexity before and after, and note any trade-offs (memory, readability). If the biggest win is outside this function (indexing, batching, caching), say so.

Best for: real bottlenecks where you want a complexity analysis, not just a rewrite.

Advertisement

13. Extract and de-duplicate logic

These files contain duplicated or near-duplicated logic. Language: [language].

[paste the 2-4 files or functions]

Extract the shared logic into a single well-named [function / module], update the call sites to use it, and preserve every existing behavior including the small differences between the copies (call those out explicitly). Return the new shared unit plus the updated call sites, and explain how you handled the differences.

Best for: collapsing copy-pasted code without silently dropping the edge cases each copy handled.

14. Modernize legacy syntax

Turn on grounding with Google Search. Modernize this [language] code from [old version/style, e.g. "callback-based, ES5"] to [target, e.g. "async/await, ES2023"].

[paste the code]

Use current idioms and non-deprecated APIs — verify against the current docs where a method may have changed. Keep behavior identical. Return the updated code and a list of each modernization, noting any API whose behavior differs from the old one.

Best for: upgrading old code, with grounding to confirm nothing you use is deprecated.

Tests & docs

Gemini is strong at tests and docs because you can ask it to reason about edge cases first. Paste the code, name the test framework, and ask it to explain what each test covers.

15. Generate a unit test suite

Set thinking to High. Write a unit test suite for this [language] code using [framework, e.g. pytest / Vitest].

[paste the code]

Cover the happy path plus edge cases: empty/null inputs, boundaries, invalid types, and error paths. Aim for meaningful coverage, not just line count. Return the tests, then a bullet list of what each group of tests verifies and which edge cases you added that weren't obvious from the code.

Best for: a thorough test suite that surfaces edge cases you hadn't listed.

16. Write integration tests

Write integration tests for this [feature, e.g. "the checkout API flow"]. Stack: [framework + test tools, e.g. "FastAPI + pytest + httpx"].

Relevant code:
[paste the routes/services involved]

Test the real interactions between [components], including a failure case for each external dependency (timeout, 500, bad data). Use [fixtures / mocks] appropriately and explain what you mocked and why. Return the tests plus setup/teardown notes.

Best for: testing how pieces work together, not just isolated units.

17. Generate docstrings and comments

Add documentation to this [language] code without changing any logic.

[paste the code]

Add [docstring style, e.g. Google-style / JSDoc / TSDoc] docstrings to every public function and class, documenting parameters, return values, raised errors, and non-obvious behavior. Add short inline comments only where the intent isn't clear from the code. Do not comment the obvious. Return the annotated code.

Best for: documenting a module before handing it off, with no logic changes.

18. Write a README from a codebase

Here is a codebase (multiple files). Read it and write a README.md.

[paste the files, or a concatenated dump of the repo]

Include: a one-line description, what it does, install steps, configuration/env vars, how to run it, how to run tests, and the project structure. Infer everything from the actual code — do not invent commands or dependencies. If something is ambiguous (like a missing env var default), list it under a "To confirm" section instead of guessing.

Best for: generating accurate docs from the code itself using the large context window.

Explain & learn

Use Gemini as a patient reviewer that explains its reasoning. Paste the code or concept and ask for the "why," not just the "what" — set High thinking when the topic is genuinely hard. See also Gemini prompts for students for more learning-focused patterns.

19. Explain unfamiliar code line by line

Explain this [language] code to me as if I'm a competent developer who's new to this codebase.

[paste the code]

Go section by section: what each part does, why it's written this way, and any non-obvious behavior, side effects, or gotchas. Point out anything that looks risky or that I should be careful editing. End with a 3-sentence summary of the code's overall purpose.

Best for: getting up to speed on code someone else wrote.

20. Explain a concept with a working example

Explain [concept, e.g. "how database connection pooling works"] in [language / ecosystem]. Assume I know the basics of the language but not this topic.

Structure: (1) the core idea in plain terms, (2) why it matters / what problem it solves, (3) a minimal working code example I can run, (4) the common mistakes people make. Keep it concrete — no hand-waving.

Best for: learning a new concept with code you can actually run.

21. Compare two approaches

Set thinking to High. I need to [goal]. I'm choosing between [approach A] and [approach B] in [language / stack].

Compare them on: correctness, performance at [expected scale], readability, testability, and long-term maintenance. Give a short code sketch of each, then a clear recommendation for MY case with the reasoning. If a third option is better, say so.

Best for: design decisions where you want the trade-offs laid out before you commit.

22. Turn an error message into a lesson

I keep hitting this error and I want to understand it, not just fix it once.

Error:
[paste the error]

Context:
[paste the code / situation]

Explain what the error actually means, the category of mistake that causes it, how to fix this instance, and how to avoid the whole class of it in future. Give one small example of the same mistake in a different form so I recognize it next time.

Best for: learning from a recurring error instead of patching it blindly.

Advertisement

Whole-codebase & review using 1M context

This is where Gemini 3.1's 1M-token context pays off: you can paste an entire codebase (often tens of thousands of lines) and ask cross-file questions in one shot. Set High thinking and describe the structure so it knows how the files fit together. A Gem with a "senior reviewer" system instruction makes these repeatable.

23. Review a pull request diff

Set thinking to High. You are a senior [language] reviewer. Review this pull request diff.

[paste the diff]

For each issue, give: file + line, severity (blocker / should-fix / nitpick), what's wrong, and the suggested change. Check correctness, edge cases, error handling, security, performance, and test coverage. If the diff lacks context you need, tell me which surrounding file to paste. End with a clear verdict: approve, approve-with-changes, or request-changes.

Best for: a rigorous first-pass review before you send a PR to a human.

24. Audit a whole codebase for a pattern

Set thinking to High. Below is my entire [language] codebase. The structure is: [briefly list the main folders/files].

[paste the concatenated codebase — Gemini's 1M-token context can hold it]

Find every place that [does X, e.g. "queries the database without parameterization", "swallows an exception silently", "uses the deprecated auth helper"]. For each hit: file, line, the risky code, why it's a problem, and the fix. Group by severity. If you find related issues I didn't ask about, list them separately.

Best for: a security or consistency sweep across the whole repo in one pass.

25. Plan a cross-cutting change

Set thinking to High. Here is my codebase. I need to [make a change that touches many files, e.g. "migrate from library A to library B", "add multi-tenancy", "rename this domain concept everywhere"].

[paste the relevant files / whole repo]

Produce a step-by-step migration plan: every file that must change and what changes, the safe order to do it in, what could break, and how I'd verify each step. Flag anything that can't be changed mechanically and needs a human decision. Don't write all the code yet — give me the plan first.

Best for: scoping a big refactor before touching anything, using full-repo context.

26. Onboarding walkthrough of a repo

Here is a codebase I just joined. Structure: [list the top-level folders].

[paste the repo / key files]

Give me an onboarding walkthrough: what the app does, the main entry points, how a request/data flows through the system end to end, where the important business logic lives, and the 5 files I should read first to be productive. Point out any surprising conventions or things that would trip up a new contributor.

Best for: ramping onto an unfamiliar project fast, with the whole thing in context.

Want the broader set? Start with the best Gemini prompts, keep the cheat sheet open for syntax and thinking levels, and grab reusable skeletons from Gemini prompt templates.

Frequently Asked Questions

Which Gemini model and thinking level should I use for coding?

Use Gemini 3.1 Pro at High thinking for hard debugging, architecture, and whole-codebase reasoning, since it plans before it answers. Drop to Medium for routine feature work, and use 3.1 Flash or Low thinking for quick edits, renames, and boilerplate where speed matters more than deep reasoning.

Can Gemini actually read my whole repository?

Yes. Gemini 3.1 has a 1M-token context window, which is large enough to ingest most codebases in a single prompt — often tens of thousands of lines across many files. Paste the files you care about (or a concatenated dump), tell it the structure, and ask cross-file questions. For very large monorepos, include only the relevant packages.

Can I paste screenshots of errors or UI?

Yes — Gemini is multimodal, so you can paste a screenshot of a red error overlay, a stack trace in a terminal, a failing CI log, or a UI mockup. It reads the image and works from it. This is faster than retyping errors and lets it match a component to a visual design.

Should I turn on Google Search grounding for coding?

Turn on grounding with Google Search when a library, framework, or API may have changed since the model's training — for example a new major version or a recently deprecated method. Ask it to look up the current docs and cite them. For self-contained logic problems, grounding is unnecessary and can slow the response.

When should I use Canvas for code?

Use Canvas when you want an editable, iteratable code document rather than a one-shot answer — for example building a script or component over several rounds, running it, and refining it in place. Canvas keeps the code in a side panel you can edit directly, which beats scrolling a long chat for anything you plan to revise.

How do I adapt these prompts to my project?

Replace every [bracketed placeholder] with your real details: language and version, framework, the actual code or error, and your constraints. The more specific you are — pinned versions, style guide, performance targets, edge cases — the closer the first answer lands. Keep the instruction to explain reasoning and list edge cases; that is where the quality comes from.

Can Gemini write tests and explain the code at the same time?

Yes. Ask it to generate the test suite and then walk through what each test covers and why, including the edge cases it chose. Because you can set High thinking, it will reason about boundary conditions, error paths, and inputs you might not have listed, which is often where real bugs hide.

Is a reusable coding assistant possible in Gemini?

Yes — create a Gem with a system instruction like "You are a senior [language] reviewer; always check for security, edge cases, and tests, and explain your reasoning." The Gem carries those rules into every chat so you don't restate them. It pairs well with the review and audit prompts in the last section.

Advertisement