You keep an AI coding chat stable by treating the conversation like a small protocol, not a diary. Write down the contract (what goes in, what comes out, what must stay true), expose only the tools the assistant actually needs, and stream output in chunks so a single slow response cannot freeze the session. That is the whole idea. Everything below is the practical version: how to phrase the contract, how to scope tools, how to handle streaming output and argument parsing, and how to recover when a reply gets truncated, a tool call loops, or the model drifts off the task. You do not need special software. A terminal, an editor, a way to run your code, and access to a chat interface or API that supports tool calling and streaming are enough. Menu labels and API names differ slightly by provider and app version, so treat any named setting as a starting point.

What You'll Need

  • A chat interface or API that supports tool or function calling and streamed responses. If yours supports neither, you can still use the contract steps, but you will be pasting output manually.
  • Your project open in an editor, ideally under version control (git) so you can diff and revert what the assistant produces.
  • A short written spec of the task: the files involved, the language and runtime, and the acceptance test you will run at the end.
  • A way to run tests or your program locally so you can verify output instead of trusting it.
  • A scratch file or notes pane for the contract text, so you can re-paste it after a context reset.
  • Optional: a local diff or lint tool, a timeout setting on your client, and knowledge of your editor's file search so you can point the assistant at exact paths.

Step-by-Step

  1. Write the contract before the first message. A contract is four short blocks: inputs (which files and what data), outputs (which files to create or edit, and the exact shape), invariants (things that must never change, such as public function signatures, config keys or database columns), and the acceptance check (the command to run and the expected result). Keep it under 20 lines. This single block prevents most drift, because the assistant re-reads the same constraints every turn instead of guessing from earlier chat.
  2. Paste the contract at the top of a fresh session, then restate it verbatim after any summarisation. Long chats get compressed or trimmed. When that happens the model quietly forgets the invariants. A cheap fix is to keep the contract in a file in the repo, say CONTRACT.md, and have the assistant read that file whenever you ask it to continue. Reading a file costs less confusion than a long chat history.
  3. Scope the tools to one job each. If your setup lets you define functions, define small ones with obvious names: read a file, write a file, run the test command, search the tree. Avoid a single "do anything" shell tool if you can; it gives the model too many ways to wander. For each tool, write a one-line description and list the required and optional arguments, and mark which arguments must be absolute paths.
  4. Validate tool arguments before you execute them. In your client code, parse the model's JSON arguments, check the required keys exist, check the types, and confirm the path stays inside the project directory. Reject and return the error to the model as tool output rather than throwing an exception. A well-formed error message ("missing required field 'path'") lets the model correct itself on the next turn; a crash ends the chat.
  5. Turn on streaming and decode by event, not by raw text. With server-sent events or a chunked stream, accumulate the bytes, split on event boundaries, and only parse complete JSON objects. Do not parse a partial buffer mid-object; you will get intermittent syntax errors that look random. Keep a separate buffer for text deltas and a separate one for tool-call deltas, because the two can interleave.
  6. Set timeouts and a size cap on every stream. A stream that never closes, or that dribbles one token every few seconds, will hold your session open indefinitely. Use an idle timeout (reset each time data arrives) plus a hard maximum response length, then cut the stream and ask for a shorter continuation. This is the most common cause of "the chat froze" reports.
  7. Make every tool call idempotent where possible. Reading a file is naturally safe. Writing is not: if a stream is cut and retried, a naive writer can append the same block twice. Write to a temporary file and rename it into place, or check whether the change already exists before applying it. For test runs, make sure retrying does not leave stray processes or locked ports.
  8. Ask for one change per turn, and verify before the next. After the assistant edits code, run the acceptance command yourself and paste only the relevant failure lines back. A short, factual error report keeps the contract in focus. If the output is long, summarise it into the shape of the contract: what failed, expected versus actual, and the file and line.
  9. Cap the loop. Decide in advance how many tool-call rounds a task may take (for example, ten) and stop when you hit it. Loops usually mean the contract is ambiguous or the tool keeps returning the same error. When you stop, go back to step 1 and tighten the wording rather than nudging the model with "try again".
  10. Close out with a diff and a re-run. Review the diff, confirm the invariants are untouched, run the acceptance check one final time, and commit. If you will resume later, store the contract and the final diff summary in the repo so the next session starts from facts instead of reconstructed chat history.

Common Mistakes

  • Describing the goal once at the start and never restating it. After summarisation or a new session, the original constraints are gone.
  • Giving the assistant a broad shell tool and hoping it stays in scope. Narrow tools fail more predictably and are easier to audit.
  • Parsing the stream as one big string at the end, then blaming the model for malformed output when the real bug was concatenating two events.
  • Letting the model edit files without version control. Without a diff you cannot see what changed, and revert means retyping.
  • Pasting entire stack traces back into chat. The relevant lines are usually the first error and the file and line number; the rest crowds out the contract.
  • Skipping argument validation, so a missing field becomes a crash instead of a message the model can act on.
  • Retrying a failed write without idempotency, which duplicates the edit and creates confusing diffs.

Tips

  • Keep the contract in a file, not only in the chat. Files survive resets and can be reviewed by you like any other source file.
  • Name tools with verbs and nouns that match your codebase (read_file, run_tests) so the model's choice is obvious.
  • Log every tool call with its arguments and result to a local file. When something goes wrong, the log tells you whether the model misread the tool or the tool misbehaved.
  • Return short, structured tool results, and include the exit code for commands.
  • Ask for the plan first on anything larger than a one-file change, approve it, then ask for the implementation. Plans are cheap to correct.
  • If your client supports a system prompt, put the invariants there and the task in the user message. That separation makes edits to the task less likely to erode the rules.
  • Prefer explicit paths over "the config file". Ambiguous references are a leading cause of wrong-file edits.

Troubleshooting

The reply cuts off mid-sentence. Check your idle timeout and maximum length first, then the provider's status page, then whether output was capped by the model's own limit. Ask for the remainder only, not a full rewrite, and restate the contract so the continuation matches the earlier part.

The stream parses sometimes and fails other times. You are almost certainly parsing partial events. Buffer until you see the event separator, parse only complete objects, and discard a trailing incomplete fragment at the end of the stream.

The assistant keeps calling the same tool. The tool is returning an error the model cannot use. Improve the error text, confirm the argument names match your schema exactly, and check for case or path mismatches. If it still loops, stop, tighten the contract, and start a fresh session with it.

Edits land in the wrong file or duplicate. Add path validation, make writes atomic, and ensure retries check for existing content. Then diff and revert before continuing.

Answers drift away from the task after a long chat. Restart or summarise deliberately, re-paste the contract, and point the assistant at the contract file. Long history is not the same as good context.

Tool calls never execute. Confirm your client actually handles tool-call events and sends results back in the expected format. A missing result message makes the model wait or repeat itself.

If none of that helps, reduce to a minimal case: one tool, one file, one acceptance command. If the minimal case works, add pieces back one at a time until it breaks.

Frequently Asked Questions

Do I need a special framework for this?

No. A plain HTTP client that can read a stream and send JSON can do all of it. Frameworks only save boilerplate.

What exactly is a contract here?

A short written block stating inputs, outputs, invariants and the acceptance check. It is a prompt artifact, not a legal document.

Why not just let the model run any command?

Broad tools make failures harder to trace and changes harder to audit. Small, named tools with validation behave more predictably.

How long should a session be?

As long as the contract stays accurate and the history is not being trimmed in ways that drop constraints. When output quality drops, restart with the contract file rather than pushing through.

Can I resume a session later?

Yes, if you stored the contract and a summary of the current diff in the repo. Without those, resume is really a new task.

Does streaming change what the model can do?

No. It changes how you receive the output. Tool calls still need complete arguments before you execute them.