liveBook · Manning

Code generation

As explained in Generative AI in Action

Code generation is the computational production of source code by a model from learned programming-language patterns and inputs.

Code generation uses a prompt and the surrounding software context to produce code snippets or functions. It is most useful as a developer aid, not a way to create a complete application: it can speed up scaffolding, help with unfamiliar SDKs, and suggest approaches to a specific task. section 5.1 section 5.6

In an IDE, GitHub Copilot can take a natural-language comment, consider the current file, and suggest code. That context matters: the language, libraries, existing code, and design patterns shape what a useful suggestion looks like. Generated code can also support adjacent work such as tests, documentation, code explanation, and refactoring. section 5.1.2 section 5.6

Listing 5.1 GitHub Copilot generation in an existing solution
# write a python function that takes a prompt and uses stability AI 
# to generate a image and save it to a file
def generate_image(prompt):
    if api_key is None:
        raise Exception("Missing Stability API key.")

    # Set the directory where we'll store the image
    image_dir = os.path.join(os.curdir, 'images')

    # Make sure the directory exists
    if not os.path.isdir(image_dir):
        os.mkdir(image_dir)

    # Function to clean up filenames
    def valid_filename(s):
        s = re.sub(r'[^\w_.)( -]', '', s).strip()
        return re.sub(r'[\s]+', '_', s)

    response = requests.post(
        f"{api_host}/v1/generation/{engine_id}/text-to-image",
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": f"Bearer {api_key}"
        },
        json={
            "text_prompts": [{ "text": f"{prompt}", "weight": 1.0}],
            "cfg_scale": 7, "height": 1024, "width": 1024,
            "samples": 1, "steps": 50,
        },
    )

    if response.status_code != 200:
        raise Exception("Non-200 response: " + str(response.text))

    data = response.json()

    for i, image in enumerate(data["artifacts"]):

filename = f"sd_{valid_filename(prompt)}_{i}_{
                      datetime.datetime.now().strftime(
                      '%Y%m%d_%H%M%S')}.png"
        image_path = os.path.join(image_dir, filename)"
        image_path = os.path.join(image_dir, filename)
        with open(image_path, "wb") as f:
            f.write(base64.b64decode(image["base64"]))

A comment requests a Python function that calls Stability AI and saves an image; the generated function illustrates how a prompt can produce a starting point within an existing solution. section 5.1.2

Treat every suggestion as a draft. Quality depends on the tool and the task; complex logic can be harder to generate reliably than a well-defined function. Review and test generated code for correctness, security vulnerabilities, performance, readability, maintainability, and compliance before production. A generated OpenAI API example even places an API key in source code—an illustrative shortcut, not a practice to copy. section 5.1.1 section 1.3.4 section 5.3.4

Choose a tool for the language, domain, and task rather than assuming all tools are interchangeable. In an enterprise, also consider development conventions and available organizational controls; Copilot’s enterprise offering includes telemetry controls and organization-wide policies. Developers remain responsible for the code they accept. section 5.3.4 section 5.1.2 section 5.1.1

How Generative AI in Action covers it

How deep it goes
Explains prompt-and-file-context suggestions and gives generated-code examples, but does not derive model internals or promise complete applications.
Examples
Shows a Python OpenAI API greeting-and-translation script and a Copilot-generated function that calls Stability AI to save an image.
What it assumes
Introduces an OpenAI API example for a developer new to OpenAI while using Python functions and IDE-based development scenarios.
What you can do after
Apply it via GitHub Copilot to draft bounded code, then review, test, and verify suggestions before production.
How it connects
Connects code generation to SDKs, code reviews, unit tests, documentation, and code refactoring.

Also explained in

Compare how 17 books explain code generation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Generative AI in Action. The section links point to the parts of the book it draws on.