Packing source files so the model sees what it needs

Pasting a project into a chat box works for a single file and fails quickly after that. Context windows fill up, lock files and build output crowd out real code, and the model answers confidently about functions it never saw. Developers keep reinventing the same tools to deal with this: small command-line packers that bundle a repository into one tagged document with sensible ignore rules, and smarter agents that read import statements to fetch the files a snippet depends on.
This guide shows how to do both yourself with short Python scripts. You will learn what to exclude, how to estimate tokens without a tokenizer, how to wrap files so the model can tell them apart, and how to choose files by following imports instead of grabbing everything. The target is the 32,000-token context of the keyless free-ai endpoint on this site, but the same approach helps with any model, including DeepSeek's larger-context ones.
This site is independent and not affiliated with DeepSeek. The techniques here are provider-neutral; only the base URL and limits change.
Frequently asked questions
What is a context window?
It is the maximum number of tokens a model can consider in one request, counting the system prompt, the conversation, any pasted files and the answer it writes. On this endpoint the context is 32,000 tokens and a single answer can be up to 16,000.
How many tokens is a typical source file?
A rough rule for English text and code is about four characters per token. A 400-line Python file of average width often lands between 3,000 and 5,000 tokens, so a 32K window holds a handful of files plus room for the answer.
Why wrap files in XML-style tags?
Tags such as <file path="..."> give the model an unambiguous boundary and a name for each file. It can then refer to paths precisely, and you can ask it to return edits per file.
How does packing differ from retrieval-augmented generation?
Packing selects whole files up front and sends them in one request. Retrieval splits documents into chunks, searches them per question and sends only the best matches. Packing keeps code intact; retrieval scales to far larger collections.
Which is better for code questions: whole files or chunks?
For code, whole files or whole functions usually work better, because chunks cut definitions apart. Retrieval that respects syntax, for example splitting by function, narrows the gap.
Should I include tests in the packed context?
Include tests when asking about behaviour or bugs, since they show intended use. Leave them out for pure refactoring questions to save space.
Does a larger context window remove the need for packing?
It reduces the pressure but not the benefit. Models answer better when irrelevant material is absent, and smaller requests are faster and cheaper on any provider.
- Budget the window before you fill it
- Exclude everything that is not source
- A small packer script
- Follow imports instead of grabbing everything
- Send the pack with clear instructions
- Shrinking files without losing meaning
- When the project is simply too large
- Privacy and what leaves your machine
- Where bigger models help
Step by step
- Set a token budget — Subtract the answer length and instructions from the context size and keep a ten percent margin.
- Exclude non-source files — Skip dependency folders, build output, lock files, binaries, minified code and secrets.
- Pick files by dependency — Start from the file in question and follow local imports one or two levels deep.
- Wrap and pack — Wrap each file in a tag with its path and stop when the budget is reached, noting what was skipped.
- Ask the question last — Send a short structural preface, the packed files, then a precise question that asks for file-scoped answers.
Budget the window before you fill it
Treat the context as a budget with three parts: instructions, code and answer. If you want a reply of up to 2,000 tokens and your system prompt and question take 500, roughly 29,000 tokens remain for code on a 32K model. Leave a margin of ten percent because estimates are imprecise.
Writing the budget down changes how you work. Instead of asking 'will it fit?', you ask 'which files deserve these 26,000 tokens?', which is the right question.
Estimating without a tokenizer
Divide character count by four for code and English. It overestimates for very repetitive code and underestimates for dense non-English text, but it is good enough to plan with.
Reserve space for the answer
If the code fills the whole window, the model has no room to reply. Always subtract max_tokens from the budget first.
Exclude everything that is not source
A surprising share of a repository is not useful to a model at all. Dependency folders, build output, lock files, minified bundles, images, fonts and generated code can be most of the bytes. Excluding them is the cheapest improvement you can make.
Start from the project's .gitignore, then add a list of patterns that are tracked but unhelpful.
Keep configuration that explains behaviour
Small config files such as pyproject.toml, tsconfig.json or a router definition often explain more per token than any source file.
- Dependency folders:
node_modules,vendor,.venv - Build output:
dist,build,.next,target - Lock files:
package-lock.json,poetry.lock,Cargo.lock - Binary assets: images, fonts, archives, databases
- Minified files:
*.min.js,*.map - Large fixtures and snapshots

A small packer script
The script below walks a directory, skips ignored paths and binary files, estimates tokens, and writes a single document where each file is wrapped in a tag with its path. It stops adding files when the budget is reached and reports what it left out, so you can decide whether to swap something in.
Preferred files first
Pass the files you know matter as extra arguments. They are sorted to the front, then smaller files fill the remaining space.
Smallest first is a heuristic
Sorting by size fits more files, but a large central module can matter more than ten small helpers. Use the preference list to override it.
import os, sys, fnmatch
SKIP_DIRS = {".git", "node_modules", "dist", "build", ".venv", "__pycache__", ".next", "target"}
SKIP_FILES = ["*.lock", "package-lock.json", "*.min.js", "*.map", "*.png", "*.jpg", "*.svg", "*.ico", "*.woff*", ".env*"]
def tokens(text):
return len(text) // 4 + 1
def pack(root, budget=26000, prefer=()):
files = []
for d, dirs, names in os.walk(root):
dirs[:] = [x for x in dirs if x not in SKIP_DIRS]
for n in names:
if any(fnmatch.fnmatch(n, p) for p in SKIP_FILES):
continue
path = os.path.join(d, n)
try:
text = open(path, encoding="utf-8").read()
except (UnicodeDecodeError, OSError):
continue
rel = os.path.relpath(path, root)
files.append((0 if rel in prefer else 1, tokens(text), rel, text))
files.sort()
out, used, skipped = [], 0, []
for _, t, rel, text in files:
if used + t > budget:
skipped.append(rel)
continue
out.append(f'<file path="{rel}">\n{text}\n</file>')
used += t
return "\n".join(out), used, skipped
if __name__ == "__main__":
doc, used, skipped = pack(sys.argv[1], prefer=tuple(sys.argv[2:]))
print(doc)
print(f"<!-- ~{used} tokens, skipped {len(skipped)} files -->", file=sys.stderr)Follow imports instead of grabbing everything
A common failure of naive selection is fragmentation: the model sees a function that calls parse_config but not the file that defines it, and guesses. Tools that parse the syntax tree solve this by reading import statements and pulling in the files a snippet depends on.
For Python, the standard library ast module makes a basic version easy. Start from the file you are asking about, collect its local imports, and add those files to the preference list before packing.
Limit the depth
Following imports two levels deep usually captures what matters. Going further pulls in half the project and defeats the point.
Other languages
JavaScript and TypeScript need a parser or a careful regular expression for import and require. The principle is identical.
import ast, os
def local_deps(path, root, depth=2, seen=None):
seen = seen if seen is not None else set()
rel = os.path.relpath(path, root)
if rel in seen or depth < 0:
return seen
seen.add(rel)
tree = ast.parse(open(path, encoding="utf-8").read())
for node in ast.walk(tree):
names = []
if isinstance(node, ast.Import):
names = [a.name for a in node.names]
elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
names = [node.module]
for name in names:
candidate = os.path.join(root, *name.split(".")) + ".py"
if os.path.exists(candidate):
local_deps(candidate, root, depth - 1, seen)
return seen
# usage: deps = local_deps("app/routes.py", "."); doc, used, skipped = pack(".", prefer=tuple(deps))
Send the pack with clear instructions
Put the packed files in the user message after a short preface that explains the structure, then ask the question last. Models attend well to the end of the prompt, so the question should not be buried in the middle of thousands of lines.
The example sends a pack to this site's endpoint. No key is required.
Ask for file-scoped answers
Requesting 'name the file and function' or 'return edits as one block per file' makes answers easier to verify and apply.
from openai import OpenAI
client = OpenAI(base_url="https://api.apideepseekfreekey.com/v1", api_key="free")
doc, used, skipped = pack(".", budget=24000, prefer=("app/routes.py",))
prompt = (
"Below are files from a project, each inside <file path=...> tags.\n\n" + doc +
"\n\nQuestion: why could a request to /export return an empty file? "
"Name the file and function you suspect."
)
r = client.chat.completions.create(
model="free-ai",
messages=[{"role": "user", "content": prompt}],
max_tokens=1500,
)
print(r.choices[0].message.content)Shrinking files without losing meaning
Sometimes the right files are known but still too large. Before dropping any of them, try making them smaller in ways that keep what the model needs. Comments that explain why code exists are valuable; licence headers, commented-out blocks and long docstring examples usually are not. Blank lines and trailing whitespace cost tokens for nothing.
A stronger technique is to keep full bodies only for the functions you are asking about and reduce everything else to signatures. The model then sees the shape of every class and function, their names, parameters and return types, without paying for thousands of lines of implementation it does not need to read.
For data files, include a representative sample instead of the whole thing: the header row and a dozen lines of a CSV, or one entry of a large JSON array. Say in the prompt that the file was truncated, so the model does not draw conclusions from the sample size.
Signature-only views
With Python's ast module you can print each function's definition line and docstring while replacing its body with an ellipsis. Interfaces stay visible at a fraction of the cost.
Mark every cut
Whenever you remove or shorten something, leave a short marker such as a comment saying the body was omitted. Models handle gaps well when they are told about them and badly when they are not.

When the project is simply too large
Some questions genuinely span more code than any reasonable window. Then split the work. Ask the model to summarise each module in a few lines, collect those summaries into a map of the project, and use the map plus a few full files for the actual question. Summaries cost a request each but can be reused many times.
Alternatively, switch to retrieval: index the code by function and fetch only the pieces relevant to each question. Our guide to a small retrieval demo without a backend shows the basic mechanics with documents; code works the same way with syntax-aware chunks.
Module maps
A one-paragraph description per module, with its main functions and dependencies, often fits an entire medium-sized project into a few thousand tokens.
Privacy and what leaves your machine
A packer makes it very easy to send a whole repository in one go, which is exactly why you should check what is in it. Environment files, credentials in config, customer data in fixtures and internal URLs all slip in easily. Add .env and secret files to the skip list and scan the pack before sending.
On this endpoint each request leaves a technical log, such as time, IP, User-Agent, endpoint, status, latency, sizes and tokens, but conversations are not kept as state. The model still reads what you send, so do not include anything you would not paste into any third-party service.
Scan for secrets
A simple search for patterns like KEY=, SECRET, BEGIN PRIVATE KEY or long random strings catches most accidents before they leave your laptop.

Where bigger models help
Packing well is a skill that pays off everywhere, but there are limits to what a 35B model with 32K context can do. For architecture reviews over large codebases or subtle cross-module bugs, a commercial model with a much larger window and stronger reasoning will usually give better answers. DeepSeek's own models and others offer that for a fee; check their documentation for current context sizes.
A practical workflow is to prototype the question here with a tight pack, confirm the prompt shape works, and move only the hard cases to a larger model. Those hard cases often benefit from a reasoning mode too, as discussed in chat versus reasoner modes.
Keep packs reusable
Save the packed document with a hash of its inputs. If the code has not changed, you can reuse it with a different question or a different model.
Open the home page and send a request to the keyless endpoint straight from your browser, no account or key needed.
Read also
- How to handle 429 and 503 errors from an LLM API without frustration
- How to build a Telegram assistant bot on a free OpenAI-compatible API
- Why does an AI model drop accents or garble non-English text?
- Direct DeepSeek API vs a unified gateway: which is better value?
- What should your app do if DeepSeek API prices go up?