Skip to content
Easy AI How-To

IntermediateGeneralPOC to production

Python, TypeScript, Go, or Rust? Pick the right language for each part of a production AI agent

Now that AI can write code in almost any language, the hard part of taking an agent from proof of concept to production is choosing the right language for each part and connecting tools that were written in other languages. This guide is part of the From POC to production track. It explains when Python, TypeScript, Go, Rust, or C/C++ fits, shows four ways to bridge between them with small code you can run, and ends with a worked hybrid log watcher, a decision table, and how to measure before you rewrite.

Time
About 30 minutes
Checked
Tools
uv (Python package and project manager), MCP official SDKs, vLLM OpenAI-compatible server, PyO3 and maturin, Python ctypes, py-spy profiler

If a button name on the screen does not match this guide, follow the action. These products rename buttons often.

Steps

  1. Ask the real question: which language for which part?

    AI coding tools can write Python, TypeScript, Go, or Rust for you, so typing the code is no longer the hard part. What still takes judgment is the shape of the system. A production agent usually has four parts:

    • The agent loop: the code that calls the model, reads its answer, and decides what to do next. (Build your first AI agent walks through one.)
    • Tools: the functions the agent can call, such as searching tickets, reading a database, or running a script.
    • Hot paths: code that runs on every request or every log line, where speed really matters. Hot path just means "the code that runs the most."
    • Model serving: the program that runs the model itself, either a cloud API or a local server.

    Each part can use a different language, and they talk through a few standard bridges (Steps 6 to 9). This guide tells you which language usually fits each part, and how to check before you switch.

  2. Default to Python for the agent loop

    Python is the default for agent code, for three reasons:

    • The libraries are there first. Model providers usually ship their Python SDK first, or alongside TypeScript. So do agent frameworks, evaluation tools, and RAG libraries.
    • The heavy math isn't Python. NumPy's core is C. PyTorch runs C++ and CUDA (code that runs on NVIDIA GPUs) underneath. vLLM is driven from Python, but its attention kernels (the small, heavily optimized GPU routines) come from FlashAttention, FlashInfer, and Triton. Python is the steering wheel, not the engine.
    • Speed rarely matters in the loop. One model call takes from half a second to tens of seconds. The Python code around it takes microseconds. Rewriting the loop in Rust speeds up the part that was already fast.

    Python is the wrong fit when the agent has to live inside a TypeScript web app, or when a single loop chews through millions of lines per second on the CPU. The next steps cover both.

  3. Make Python environments painless with uv

    Most Python pain comes from environments, not the language. A virtual environment (venv) is a folder with its own Python and packages, so projects don't break each other. uv creates and manages them for you, and it's very fast:

    curl -LsSf https://astral.sh/uv/install.sh | sh   # or: brew install uv
    uv init logwatch --python 3.12                     # new project, pinned Python
    cd logwatch
    uv add openai "mcp>=2"                             # adds to pyproject.toml and uv.lock
    uv run watch.py                                    # runs inside the project's venv
    

    uv run creates the .venv folder and syncs packages on the first run, so you never have to activate anything. Commit pyproject.toml and uv.lock, and your teammates and your server get the exact same versions with uv sync. To fix an older project quickly, uv venv followed by uv pip install -r requirements.txt also works.

  4. Use TypeScript for MCP servers, web apps, and serverless agents

    TypeScript is JavaScript with types, which means the editor checks that you pass the right fields before the code runs. Pick it when:

    • The agent lives in a web app or a Next.js route, so the UI and agent share one language and one deploy.
    • You deploy to serverless platforms (functions that start on demand), where Node.js starts fast and is supported everywhere.
    • You're writing an MCP server. MCP (Model Context Protocol) is the open standard for giving AI apps access to tools. When this was checked, TypeScript, Python, C#, Go, Rust, and Ruby were the top-tier ("Tier 1") official MCP SDKs, with Java, Swift, PHP, and Kotlin also available.

    A tiny MCP server in TypeScript, using v2 of the official SDK (npm init -y && npm pkg set type=module && npm install @modelcontextprotocol/server zod tsx):

    // server.ts
    import { readFile } from "node:fs/promises";
    import { McpServer } from "@modelcontextprotocol/server";
    import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
    import * as z from "zod/v4";
    
    const server = new McpServer({ name: "log-tools", version: "1.0.0" });
    
    server.registerTool(
      "count_errors",
      {
        description: "Count lines containing level=error in a log file",
        inputSchema: z.object({ path: z.string() }),
      },
      async ({ path }) => {
        const text = await readFile(path, "utf8");
        const errors = text.split("\n").filter((l) => l.includes("level=error")).length;
        return { content: [{ type: "text", text: String(errors) }] };
      }
    );
    
    await server.connect(new StdioServerTransport());
    

    zod describes the tool's input, and the SDK turns it into the schema the model sees. The older v1 package, @modelcontextprotocol/sdk, still gets fixes, but new projects should start on v2.

  5. Save Go, Rust, and C/C++ for the hot paths

    Compiled languages earn their place where the CPU really is the bottleneck:

    • Inference engines. llama.cpp is written in C/C++. vLLM's GPU kernels are CUDA, C++, and Triton. You use these engines; you rarely write them.
    • High-volume parsing. Reading thousands of log lines per second, counting patterns, and keeping rolling windows. Python can do it, but a small Go or Rust program uses a fraction of the CPU and stays steady under load.
    • CPU-bound loops, meaning code that's slow because of math or string work, not because it's waiting on a network or a model.

    Rough guide: Go for small, fast services and command-line tools (easy to learn, one static binary, good concurrency). Rust when you need maximum speed or memory safety, or want to speed up a Python function from inside Python (Step 9). C/C++ mostly when you're calling a library that already exists in it.

  6. Bridge 1: call command-line tools with subprocess

    The simplest way to use a tool written in another language is to run it as a program. Python's subprocess module starts the program, passes arguments, and reads its output. This calls ripgrep (rg, a fast search tool written in Rust):

    import subprocess
    
    result = subprocess.run(
        ["rg", "--count", "level=error", "app.log"],
        capture_output=True, text=True, timeout=30,
    )
    # rg exits 0 when it finds matches, 1 when it finds none, 2 on an error
    if result.returncode == 2:
        raise RuntimeError(result.stderr)
    count = int(result.stdout.strip() or 0)
    print("errors:", count)
    

    Always pass the command as a list, and don't use shell=True with anything a model or user typed. That's how a prompt turns into an injected shell command. Set a timeout, and read the tool's documented exit codes.

  7. Bridge 2: talk to models and services over HTTP

    HTTP makes language a non-issue: any language can call any server. Many local model servers copy OpenAI's API (they're OpenAI-compatible), so the same client code works against the cloud or your own GPU. Start vLLM, which listens on port 8000 by default:

    vllm serve [model-name]
    

    Then point the OpenAI Python library at it:

    from openai import OpenAI
    
    client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed-locally")
    reply = client.chat.completions.create(
        model="[model-name]",
        messages=[{"role": "user", "content": "Say hello in five words."}],
    )
    print(reply.choices[0].message.content)
    

    vLLM is Python and C++ underneath, but your agent doesn't care. Chat Completions is the endpoint OpenAI-compatible servers support most widely. vLLM also serves the newer Responses API at /v1/responses, which the OpenAI Responses API guide covers. Replace [model-name] with the model you serve; curl localhost:8000/v1/models lists it.

  8. Bridge 3: use MCP as the language-neutral tool bridge

    MCP lets an agent in one language use tools written in another, with no custom glue. This Python agent starts the TypeScript server from Step 4 as a subprocess and calls its tool. The connection over stdin and stdout is called stdio.

    import asyncio
    
    from mcp import Client, StdioServerParameters
    
    server = StdioServerParameters(command="npx", args=["tsx", "server.ts"], cwd="../mcp-ts")
    
    
    async def main() -> None:
        async with Client(server) as client:
            tools = await client.list_tools()
            print([t.name for t in tools.tools])          # ['count_errors']
            result = await client.call_tool("count_errors", {"path": "app.log"})
            print(result.content[0].text)
    
    
    asyncio.run(main())
    

    This uses v2 of the MCP Python SDK (uv add "mcp>=2", Python 3.11+). The same TypeScript server also plugs into Claude Code, Cursor, and other MCP apps without changes. That's the payoff: write a tool once, in whatever language suits it, and every agent can use it. To write your own server in Python instead, see Build an MCP server.

  9. Bridge 4: bindings, when one call per line is too slow

    Subprocesses and HTTP add a few milliseconds per call. When you need to call fast code millions of times, load it straight into Python with a binding, a thin layer that makes compiled code look like a normal Python function.

    Rust with PyO3 and maturin. PyO3 connects Rust to Python, and maturin builds and installs the package:

    uvx maturin new -b pyo3 fastcount && cd fastcount
    

    Replace src/lib.rs with:

    use pyo3::prelude::*;
    
    #[pymodule]
    mod fastcount {
        use pyo3::prelude::*;
    
        /// Count lines in `text` that contain `needle`.
        #[pyfunction]
        fn count_matches(text: &str, needle: &str) -> usize {
            text.lines().filter(|line| line.contains(needle)).count()
        }
    }
    

    Then build it into a venv and call it:

    uv venv && uv pip install maturin && uv run maturin develop --release
    uv run python -c "import fastcount; print(fastcount.count_matches(open('app.log').read(), 'level=error'))"
    

    An existing C library with ctypes. ctypes ships with Python and loads a compiled C library (gcc -O2 -shared -fPIC -o libcount.so count.c) with no build step on the Python side:

    import ctypes
    
    lib = ctypes.CDLL("./libcount.so")
    lib.count_substr.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
    lib.count_substr.restype = ctypes.c_long
    print(lib.count_substr(open("app.log", "rb").read(), b"level=error"))
    

    Always set argtypes and restype. Without them, ctypes guesses the types and can crash. cffi is a popular alternative for bigger C APIs, because you paste in the C declarations instead of rewriting them.

  10. Worked example: a Go counter feeding a Python agent

    This is the pattern from the hybrid log watching recipe, split by language. Go reads every log line and counts. Python only wakes the model when a window looks wrong. The log format here is made up (level=error msg="..."), so adjust the match to yours.

    The hot path, in Go (go mod init example.com/logcount, then go build -o logcount .):

    // main.go: read log lines on stdin, print one JSON summary per window.
    package main
    
    import (
    	"bufio"
    	"encoding/json"
    	"flag"
    	"os"
    	"strings"
    	"sync"
    	"time"
    )
    
    type Summary struct {
    	WindowEnd string   `json:"window_end"`
    	Lines     int      `json:"lines"`
    	Errors    int      `json:"errors"`
    	Warnings  int      `json:"warnings"`
    	Samples   []string `json:"samples"`
    }
    
    func main() {
    	window := flag.Duration("window", 10*time.Second, "summary interval")
    	flag.Parse()
    	var mu sync.Mutex
    	cur := Summary{}
    	out := json.NewEncoder(os.Stdout)
    
    	go func() { // print a summary every window, then reset
    		for t := range time.Tick(*window) {
    			mu.Lock()
    			cur.WindowEnd = t.UTC().Format(time.RFC3339)
    			out.Encode(cur)
    			cur = Summary{}
    			mu.Unlock()
    		}
    	}()
    
    	sc := bufio.NewScanner(os.Stdin)
    	sc.Buffer(make([]byte, 1024*1024), 1024*1024) // allow long lines
    	for sc.Scan() {
    		line := sc.Text()
    		mu.Lock()
    		cur.Lines++
    		switch {
    		case strings.Contains(line, "level=error"):
    			cur.Errors++
    			if len(cur.Samples) < 5 {
    				cur.Samples = append(cur.Samples, line)
    			}
    		case strings.Contains(line, "level=warn"):
    			cur.Warnings++
    		}
    		mu.Unlock()
    	}
    }
    

    The agent, in Python (watch.py, run with uv run watch.py app.log):

    import json
    import subprocess
    import sys
    
    from openai import OpenAI
    
    LOG_FILE = sys.argv[1] if len(sys.argv) > 1 else "app.log"
    ERROR_THRESHOLD = 5            # errors per window before we ask the model
    MODEL = "[model-name]"         # the name your server lists at /v1/models
    
    client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed-locally")
    
    # tail (C) -> logcount (Go) -> this script (Python)
    tail = subprocess.Popen(["tail", "-F", "-n", "0", LOG_FILE], stdout=subprocess.PIPE)
    counter = subprocess.Popen(
        ["./logcount", "-window", "10s"], stdin=tail.stdout, stdout=subprocess.PIPE, text=True
    )
    
    for line in counter.stdout:
        s = json.loads(line)
        print(f"{s['window_end']}  lines={s['lines']}  errors={s['errors']}")
        if s["errors"] < ERROR_THRESHOLD:
            continue  # the cheap path: no model call for a normal window
        samples = "\n".join(s["samples"] or [])
        reply = client.chat.completions.create(
            model=MODEL,
            messages=[
                {"role": "system", "content": "You are an on-call assistant. Be brief and concrete."},
                {"role": "user", "content": (
                    f"{s['errors']} errors out of {s['lines']} lines in the last window. "
                    f"Sample lines:\n{samples}\n\n"
                    "In two sentences: what is the likely cause, and what should I check first?"
                )},
            ],
        )
        print("  model:", reply.choices[0].message.content)
    

    Each language does what it's good at. tail (C) follows the file. Go counts every line using very little CPU. Python handles the prompt, the model call, and whatever you add next, like posting to chat or opening a ticket. Most windows never touch the GPU. To test it, append some level=error lines to app.log from another terminal and watch a summary and a model answer appear within 10 seconds.

  11. Use the decision table

    Part of the system Start with Switch when
    Agent loop, prompts, RAG, evals Python The agent must live inside a TypeScript web app
    MCP server or tools for others to use TypeScript or Python Your team's code already lives in Go, C#, or Rust (all have official SDKs)
    Web UI, API routes, serverless agents TypeScript Heavy data science work happens on the server side, so call a Python service
    Log parsing, counters, high-volume streams Python first, then Go or Rust A profile shows parsing using most of the CPU
    One slow function inside Python Python, then a Rust binding (PyO3) That function shows up at the top of the profile
    Existing C or C++ library ctypes or cffi Many calls with complex types; use a maintained wrapper instead
    Model serving vLLM, llama.cpp, or a cloud API (don't write your own) Rarely. Tune the server's settings first
    Glue between all of these subprocess, HTTP, MCP Calls are too slow per item; then use a binding
  12. Measure before you rewrite

    Before you rewrite anything for speed, find out where the time actually goes. A profiler is a tool that shows which functions use the most time.

    • Time the model call against everything else. In an agent, this one check usually settles it:
      import time
      
      t0 = time.perf_counter()
      prompt = build_prompt(summary)       # your Python code
      t1 = time.perf_counter()
      reply = client.chat.completions.create(model=MODEL, messages=prompt)
      t2 = time.perf_counter()
      print(f"python {t1 - t0:.4f}s   model {t2 - t1:.2f}s")
      
    • cProfile ships with Python: python -m cProfile -s cumtime watch.py lists functions by total time.
    • py-spy looks at a running program without changing it: py-spy top --pid 12345 shows a live view, and py-spy record -o profile.svg -- python watch.py saves a flame graph (a picture of where the time goes). Attaching to a running process usually needs sudo.
    • For Go, the built-in pprof profiler does the same job.

    Rewrite only the function at the top of the profile, keep the rest in Python, and measure again. For a worked example with real numbers, see I rewrote my Python log parser in Rust. Was it worth it? If the model call is 99% of the time, the fix is a smaller or faster model, caching, or fewer calls, not a new language.

Tips

  • Ask your AI coding tool for the bridge, not just the code: "write this parser in Go and have it print one JSON line per window that my Python script reads." A clear interface between parts matters more than the language inside each one.

  • Keep each cross-language boundary boring: JSON lines on stdout, HTTP with JSON, or MCP. Every boundary is a place where versions and error handling can drift.

  • Ship compiled tools as one binary per platform (Go makes this easy), and pin Python packages with uv.lock so the agent and its tools upgrade on purpose, not by accident.

  • Use made-up or scrubbed sample logs when you share prompts or examples. Real logs often contain hostnames, IP addresses, and customer details.

Common questions

If AI writes the code, why does the language matter?

Because you still decide where each piece runs, what it depends on, and how the pieces talk to each other. Those choices decide speed, cost, and how hard the system is to run and fix. The AI can write any of the code; it can't tell what your production environment needs unless you do.

Isn't Python too slow for production?

For agent loops, almost never: the time goes to model and GPU calls, and Python's heavy libraries already run C, C++, or CUDA underneath. Python becomes the bottleneck in CPU-heavy loops over lots of data, and that's the one piece you move to Go or Rust.

Should I write my MCP server in TypeScript or Python?

Either works, since both are top-tier official SDKs. Use the language of the code the tool wraps: TypeScript if it calls your web app's APIs, Python if it calls data or ML libraries. Agents connect to both the same way.

Do I need to learn Rust?

Not to start. Learn to read it well enough to review what an AI coding tool writes, and to run maturin develop. You'll only need it for the rare function that a profile shows is too slow in Python.

Free newsletter

Learn AI by doing, one how-to at a time

New how-tos across all of AI: everyday tools, RAG, agents, local models, and taking a proof of concept to production. Each one is something you can try yourself, because the best way to learn AI is by doing it. Free, and you can unsubscribe in one click.

Subscribe free

Opens our sign-up page on beehiiv. Privacy