Skip to content

Function Chains: The Best Prompt Engineering Hack!

Table of Contents

After you finish reading this post, you will be able to create super-powerful workflows and scripts combining Power Prompts and Function Chains!

prompt engineering tricks function chains

What are Functions Chains?

I love simplicity, so let’s take a simple example to understand the concept in less than 2 minutes.

Let’s say you are developing an AI Tool. for example, a “Blog Title Generator” Tool.

You need mainly is 3 things:

  • The Right Prompt.
  • Integrate The Prompt in your App Code or Script.
  • UI for the tool.

How To Create the Right Prompt?

The Prompt is the heart of your tool, so I believe you have to invest time in this step to get the best results.

I have a full guide about creating the perfect prompts. You can check it here.

But let me share with you a quick step-by-step process here to create the right prompt for your tool.

Step 1: Define a clear goal.

You have to know exactly what you are looking for, and what you expect the prompt to generate.

For example, if you are creating a blog outline generator, then you expect the output to be a structured outline.

If you are creating a Title Generator, you expect a list of X Titles in the output and so on.

Step 2: Understand the main Elements of a Prompt

When crafting a prompt, consider these important components: Role, Instruction, Context, Input, Output, and optional Examples.

  • Role: Consider this a role-playing game where you instruct the AI to “act as” a particular character or entity. It could be anything from a detective solving a mystery to a language translator.
  • Instruction: Here, you’re telling the AI what to do. “Write a poem,” “Answer this question,” “Translate this text,” are all examples of instructions. It’s your ‘command’ to the AI.
  • Context: You provide the background or setting for the prompt. This could include the target audience, the style of response, the time frame, etc.
  • Input: This refers to the specific topic or content you want the AI to focus on. This is very important, especially when you create prompt templates.
  • Output: How do you want your response? This could be in the form of paragraphs, bullet points, a JSON, an XML, a table, a list, a graph, or any other structure. You can shape the AI’s response as you need.
  • Example (optional): Providing an example can be useful in some scenarios, as it can help guide the AI’s output. It’s like showing the AI a snapshot of what you want.

Example prompt for a blog tile generator:

Act as a professional blog writer. 

Your task is to create 10 Titles for a blog about [topic]

The Titles should be optimized for SEO and Intriguing and catchy, increases my CTR.

[topic] = “input topic”

If you test this prompt with ChatGPT, for example, here is the output you will get:

Not bad, but the main problem is that the output contains the titles with text above and beyond. Ok, and what?

The problem here is if you want to use this prompt in your tool and integrate within your script it will be hard to parse the titles and use them the way you want, especially when you are developing the UI.

For example, you can test my Blog Title Generator and see I am showing the titles in special cards like this:

So, in short, we need a way to have a structured JSON response out from the prompt, which makes it easy for us to parse and read the output and use it in our scripts and codes.

This is where Prompt Chains Come.

It is a prompt engineering tactic that helps you build prompts that are easily chained with your code and scripts.

How To Output JSON From Your Prompt?

Here the magic begins!

I know, that if you have some experience in prompting, you can tell the prompt to output JSON, for example, we can edit our prompt this way:

Act as a professional blog writer. 

Your task is to create 10 Titles for a blog about [topic]

The Titles should be optimized for SEO and Intriguing and catchy, increases my CTR.

[topic] = “input topic”

And we get something like:

nice, we got the JSON, but still, we have some text.

We can then update the Prompt again:

Act as a professional blog writer. 

Your task is to create 10 Titles for a blog about [topic]

The Titles should be optimized for SEO and Intriguing and catchy, increases my CTR.

[topic] = “input topic”
output: Only JSON ARRAY OF TITLES. Without any text


Perfect, we got only a JSON Array! That’s exactly what we are looking for.

Don’t Celebrate!

In my experience in building more than 100 scripts and AI tools. The Language Model May sometimes hallucinate, generating corrupted JSON, like missing commas or brackets.

Maybe someone may tell me OpenAI just released a feature called function calling that solves this issue.

Don’t Celebrate Again!

I also tested this feature and did a lot of tests, I mean it, a lot!

And still, the models hallucinate and generate Malformed JSON. Here is a simple discussion on OpenAI’s Forum about this issue.

Soon, I will publish a full article about Function Calling with OpenAI, and share my tests and results.

What is the Solution?

The Solution is simply divided into two parts

The first one is in prompt engineering: crafting, testing, and optimizing the best prompt that fits your scenario.

And the second is in your scripts and codes. Let me share with you my prompt and a sample code in Python to handle this issue!

Here is the current Prompt I am using To Generate Blog Post Titles:

I want you to act as a professional blog titles generator. 
Think of titles that are seo optimized and attention-grabbing at the same time,
and will encourage people to click and read the blog post.
They should also be creative and clever.
Try to come up with titles that are unexpected and surprising.
Do not use titles that are too generic,or titles that have been used too many times before. I want to generate 10 titles maximum.
My blog post is is about {topic}
IMPORTANT: The output should be a JSON array of 10 titles without field names. Just the titles! Make Sure the JSON is valid.
Example Output:
    "Title 1",
    "Title 2",
    "Title 3",
    "Title 4",
    "Title 5",
    "Title 6",
    "Title 7",
    "Title 8",
    "Title 9",
    "Title 10",

This prompt is part of My Premium Prompts Library.

You can see the Last part:

The output should be a JSON array of 10 titles without field names. Just the titles! Make Sure the JSON is valid.

Then, I gave an example output.

This helped a lot in maintaining a consistent Valid JSON Output.

But still, sometimes, while I am checking the logs, I see some Malformed JSON.

The Best Solution I found till now, is to handle this in my Python code.

So before I return the JSON, I try to parse and check if it is valid, if not, I call The Language Model API again with another request to get a Valid Output.

I have a maximum retries of 5, but till now, I haven’t used more than 1. so we can say it is working perfectly.

Here is a sample of my code:

    retry_count = 0
    max_retries = 5

    while retry_count < max_retries:
        generated_titles_string = None

            prompt = generate_youtube_titles_2.format(
                topic=user_topic, style=user_style

            generated_titles_string = await llm.basic_function_call(prompt)
            generated_titles_json = json.loads(

            return TitlesGeneratorResponse(
                success=True, message="Done", titles=generated_titles.titles

        except (json.JSONDecodeError, ValidationError):
                f"Failed during JSON decoding or validation. Retry count: {retry_count + 1}. Generated String: {generated_titles_string}"
            retry_count += 1

Note: This code is just an example of the Idea and will not work directly, as you will need other functions I used in my code.

But it is a simple example of how to retry generation if the JSON is malformed.

Another Approach: Pydantic! (Update)

Last week (16 NOV 2023), I researched and tested the easiest way to connect OpenAI API with my scripts to build custom AI tools easily.

And I found myself missing the power of Pydantic in Python.

Now with three lines of code, you can call OpenAI and return custom JSON to use in any tool you want!

This makes function chaining much easier! And with Python, building tools is now a piece of cake.

Especially if you have your own API as the backend for your tool, as I do for my AI tools.

Here is a sample example of a function that generates YouTube Titles and returns a JSON:

from openai import OpenAI
open_ai_client = OpenAI(

from typing import List
from pydantic import BaseModel
import instructor

class YouTubeTitles(BaseModel):
    titles: List[str]

def youtube_generator():
    titles : YouTubeTitles =
        model = "gpt-3.5-turbo",
        response_model = YouTubeTitles,
        messages= [{"role":"user","content" : "generate 5 youtube titles for a video ..."}]
    return titles

I hope this helps.

If you have any questions, you can join us on the forum.

Bonus: Build the UI with WordPress

The last step is to Build a user interface for the tool.

Did you know that you can do this with WordPress?

I created a step-by-step guide to Building AI tools with WordPress. Check it out here.

Earn Points for Every Share!

9 thoughts on “Function Chains: The Best Prompt Engineering Hack!”

    1. Thank you sir! You provided invaluable content for educating us, without getting tiring .. I need to loop into most significant parts again & take action. Your way of teaching is novel, as it is refreshing to see the the results easily, while understanding the concept! Extraordinary

  1. Thank you so much for your tools and valuable information. How can I get a copy of the newsletter generator tool?

Leave a Reply

Your email address will not be published. Required fields are marked *