Try this tool today
Accelerate your vibe coding workflow with our partner link.
Cody by Sourcegraph is an AI-powered code assistant that integrates directly into developer workflows—editing, browsing, and reviewing code. It is most valuable when you need to understand unfamiliar code, generate or refactor code, answer questions across your codebase, or automate common tasks without leaving your editor or terminal. It excels in large codebases with complex, heterogeneous systems, where the cost of context switching is high.
Writing and Refactoring Code
Cody generates code and refactors existing code using natural language prompts. The assistant operates across multiple editors via extensions, with a consistent API and behavior.
To generate code, open any file in your editor and invoke Cody with Ctrl+Shift+P (or Cmd+Shift+P), then type Cody: Generate function. The prompt appears, and you type a description like:
> Write a function to validate a user's email and return true if valid, using regex.
Cody responds instantly with a complete function body in your language, using your codebase’s style and conventions.
def validate_email(email: str) -> bool:
"""Validate an email address using a regular expression."""
pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
return bool(re.match(pattern, email))
Cody uses your project’s pyproject.toml, flake8, and mypy configuration to guide formatting and type hints.
For refactoring, use Cody: Refactor code and describe the change:
> Extract the database query logic from this function into a separate function called fetch_user_by_id.
Cody identifies the relevant code, extracts it, and returns a new function with proper signature and call sites.
Cody supports advanced refactoring patterns through inline prompts. You can place your cursor on a symbol and type // Cody: Refactor to use async to automatically convert a sync function to an async one, including await calls and async/await wrappers.
Common Pitfalls
- Overly broad prompts: A prompt like "Make this better" generates minimal, generic changes. Always specify the *what* and *why*.
- Missing context: Cody does not automatically include the file’s docstring or surrounding code unless explicitly told. Use
// Cody: Include docstring and importsto improve results. - Incorrect language detection: Cody infers language from file extension, but in mixed projects, it may misapply a prompt. Use
// Cody: Language: TypeScriptto override. - Refactoring fails silently: If Cody cannot find a target symbol or scope, it returns
nullor a partial result without an error.
Navigating and Understanding Code
Cody helps you quickly grasp unfamiliar code. You can ask questions like “What does this function do?” or “How is the user session stored?”
To navigate, position your cursor on any symbol and run Cody: Explain, or use Cody: Find all usages. Cody returns a detailed explanation with:
- A summary of the symbol’s purpose and inputs
- A list of related functions and types
- Example usage from your codebase
- Links to related files, tests, and documentation
For example, asking about UserSessionManager returns:
> UserSessionManager is a class that handles the lifecycle of user sessions in the application. It uses Redis for storage and JWT for authentication. It supports login, logout, refresh, and session invalidation. The class is used across the web, API, and worker services.
Cody includes code examples from real call sites:
session = UserSessionManager.get(session_id)
if session.is_valid():
await session.refresh()
Cody also supports context-aware searching. In your editor, type Cody: Search for "authentication flow" and Cody returns a curated list of relevant files, functions, and code snippets, with a summary of the flow.
Sharp Edges
- Context limits: Cody uses a fixed context window (typically 8,192 tokens). When you ask a question that requires deep understanding of a large module, Cody may omit key details from the beginning of the file. Use
// Cody: Include file header and importsto extend context. - Ambiguous symbols: When a symbol is defined in multiple files (e.g.,
Userinsrc/models/user.pyandsrc/api/user.py), Cody may choose the wrong definition. Use// Cody: Focus on file: src/models/user.pyto narrow scope. - Missing file context: Cody does not automatically include the file’s docstring when explaining a symbol. Always include
// Cody: Include docstringfor better results.
Answering Questions Across the Codebase
Cody acts as a persistent, context-aware knowledge engine. You can ask questions like:
> What are the steps to create a new user account?
Cody searches your entire codebase, identifies relevant files, and synthesizes a response with code, comments, and diagrams.
For example:
> The user creation process involves: > > 1. Validating the input via validate_user_data function. > 2. Creating a User record in the database using create_user. > 3. Sending a welcome email via send_welcome_email. > 4. Initializing the session with UserSessionManager.create. > > The flow is orchestrated in src/api/user/create.py.
Cody includes code blocks and links to files:
# src/api/user/create.py
async def create_user(request: Request):
data = await request.json()
if not validate_user_data(data):
raise HTTPException(400, "Invalid user data")
user = await create_user(data)
await send_welcome_email(user.email)
session = UserSessionManager.create(user)
return {"user_id": user.id, "session_id": session.id}
You can also ask follow-up questions in a chat-like interface:
> What does validate_user_data do?
Cody responds with a detailed explanation, including its parameters, return values, and example calls.
Failure Modes
- Incomplete answers: Cody may return a list of files but not synthesize a clear narrative. Use
// Cody: Summarize and explainto improve coherence. - Out-of-order results: When searching, Cody returns files in order of relevance, but the best match is not always first. Use
// Cody: Sort by relevance and include summaryto prioritize. - Slow responses: Cody uses a backend service with a queue of requests. If the codebase is large, responses may take 3–10 seconds. Use
// Cody: Prefetch contextto reduce latency.
Automating Tasks with Cody Commands
Cody supports custom commands, which are predefined actions that take parameters and return structured results.
To define a command, create a file in .cody/commands/ in your repository root:
// .cody/commands/create-issue.json
{
"name": "create-issue",
"description": "Create a GitHub issue from a code snippet",
"parameters": [
{
"name": "title",
"type": "string",
"description": "Title of the issue"
},
{
"name": "body",
"type": "string",
"description": "Body of the issue"
},
{
"name": "labels",
"type": "array",
"items": { "type": "string" },
"description": "List of labels"
}
],
"handler": "python3 scripts/cody/create_issue.py"
}
The handler script receives the parameters as JSON via stdin:
# scripts/cody/create_issue.py
import sys
import json
import requests
def main():
data = json.load(sys.stdin)
title = data["title"]
body = data["body"]
labels = data["labels"]
response = requests.post(
"https://api.github.com/repos/your-org/repo/issues",
json={
"title": title,
"body": body,
"labels": labels
},
headers={
"Authorization": f"Bearer {os.getenv('GITHUB_TOKEN')}",
"Accept": "application/vnd.github.v3+json"
}
)
if response.status_code == 201:
issue_url = response.json()["html_url"]
print(json.dumps({"success": True, "url": issue_url}))
else:
print(json.dumps({"success": False, "error": response.text}))
if __name__ == "__main__":
main()
You can invoke the command from your editor:
> Cody: create-issue title="Add dark mode" body="Add a toggle for dark mode in the UI." labels=["enhancement", "ui"]
Cody runs the command and returns the new issue URL.
Configuration and Failures
- Missing handler script: If the
handlerscript is not found, Cody returns a404error with{"error": "Handler script not found"}. - Invalid parameters: If a parameter is missing or malformed, Cody logs
{"error": "Invalid input", "details": { "missing": ["title"], "invalid": ["labels"] }}. - Asynchronous commands: Cody supports long-running commands. The handler script can return a
{"status": "running", "task_id": "123"}and update progress later via a webhook.
Integrating Cody into CI and Dev Workflows
Cody can be invoked directly from the command line using cody CLI.
# Run Cody from terminal
$ cody explain src/api/user.py --context=8192 --format=markdown
This command returns a markdown-formatted explanation of the file, including symbol definitions, usage, and code examples.
Cody also integrates with git:
$ git commit -m "Cody: Add user auth middleware"
Cody automatically suggests a commit message based on the changes:
> Add user authentication middleware using JWT and Redis. Includes login, refresh, and middleware functions. Fixes session leakage and improves performance.
You can use cody commit to generate a message and then commit with the suggested text:
$ cody commit --template=conventional
This generates a commit message using conventional commit format:
feat(auth): add JWT middleware
- Implement JWT-based authentication middleware
- Add refresh token support
- Improve session handling and error reporting
Failure Points
- Missing
.codydirectory: If the.codydirectory is not present, Cody uses default configurations and falls back to global settings. - Unreachable handler: If the command handler script fails to run (e.g., missing Python dependencies), Cody logs the error and returns it to the user.
- CI-specific context: In CI, Cody automatically sets
context: ciand usesCI=truein environment variables, enabling different behavior for pull requests, builds, and deploys.
Troubleshooting Cody
Common errors and their meanings:
Cody: Failed to fetch context: The assistant could not retrieve a file or symbol. Check the file path and ensure it exists in the codebase.Cody: Context exceeded: The input text exceeded the context window. Use// Cody: Truncate contextor reduce prompt size.Cody: Handler failed with status 500: The command handler script returned an HTTP 500 error. Check the logs orstdoutof the script.
Cody logs all interactions to a JSON file in .cody/logs/. Each log entry includes:
timestamppromptresponsecontextstatuserror
Example log entry:
{
"timestamp": "2024-05-15T12:34:56Z",
"prompt": "Explain how session validation works",
"response": "Session validation is performed by checking the JWT signature and expiration...",
"context": [
"src/auth/session.py",
"src/auth/jwt.py"
],
"status": "success",
"error": null
}
Cody also supports custom prompt templates in .cody/prompt-templates/:
// .cody/prompt-templates/fix-bug.json
{
"name": "fix-bug",
"template": "Fix the following bug in the code:\n\n{{code}}\n\nSteps to reproduce:\n\n- {{steps}}\n\nExpected behavior:\n\n- {{expected}}\n\nYour response should include:\n- A description of the root cause\n- The fix\n- A code snippet\n- A test case"
}
These templates are used when a user selects a custom prompt from their editor.
Cody is not a one-size-fits-all tool. It grows more powerful as your codebase grows. The most common mistake is relying on the default prompt without customizing it for your team’s style, leading to inconsistent results. Always review Cody’s output and adjust prompts and configurations iteratively.
This page was rewritten on 14 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.