Close Menu
  • AI
  • Content Creation
  • Tech
  • Robotics
AI-trends.todayAI-trends.today
  • AI
  • Content Creation
  • Tech
  • Robotics
Trending
  • Black Forest Labs Releases FLUX 3 Motion: A 7B Open-Weights World Motion Mannequin That Tops RoboLab-120
  • Fastino Releases GLiNER2.5-Resolve: A 340M Open-Weight Determination Mannequin That Runs on CPU
  • BottleCap AI Releases ThinkingCap-Qwen3.8-27B: 37.2% Fewer Considering Tokens at a 0.86pp Accuracy Price
  • What if I find an AI agent that is worth the risk?
  • Google’s Gemini Can Now Make Requires You on Pixel Telephones
  • An OpenAI Agent Hacked Australia’s Well being Service. Their Authorities Discovered Out Months Later
  • Vibe Coding for Inexperienced persons — Easy Information for Creators, Entrepreneurs, and Non-technical People
  • Contrastive-LM Releases CLM-8B: An Open System One Mannequin That Scores Agent Actions As much as 9× Quicker Than Jev
AI-trends.todayAI-trends.today
Home»Tech»Implementing Self-Refine Technique Using Large Language Models LLMs

Implementing Self-Refine Technique Using Large Language Models LLMs

Tech By Gavin Wallace29/07/20255 Mins Read
Facebook Twitter LinkedIn Email
A Coding Implementation to Build an Interactive Transcript and PDF
A Coding Implementation to Build an Interactive Transcript and PDF
Share
Facebook Twitter LinkedIn Email

This tutorial shows how to use Mirascope’s powerful framework, Mirascope (a large language model), for implementing the Self-Refine method. Mirascope is a powerful tool that allows you to build structured prompt workflows. Self-Refine refers to a prompting strategy in which the model assesses itself and generates feedback. It then improves on its output based upon that feedback. The loop of refinement can be repeated many times in order to improve the accuracy and quality of the answer.

Self-Refine is especially effective when it comes to tasks that involve reasoning, code creation and content generation. This approach leads to better results with incremental improvements. Click here to see the Full Codes here

Installing Dependencies

!pip Install "mirascope[openai]"

OpenAI Key

OpenAI API keys can be obtained by visiting https://platform.openai.com/settings/organization/api-keys Create a new API key. You may be required to enter billing information and pay $5 minimum to get API access if you are a brand new user. You can check out the Full Codes here

Import os
Getpass Import
os.environ["OPENAI_API_KEY"] = getpass('Enter OpenAI API Key: ')

Basic Self-Refined Implementation

We implement the Self-Refine method using Mirascope @openai.call, and @prompt_template. It begins by generating a response for a specific user request. The model evaluates this response and provides feedback. This feedback is then used by the model to produce an improved answer. This refinement can be repeated for an specified number of cycles, improving the output quality with each iteration. See the Full Codes here

Openai prompt_template imported from mirascope.core
from mirascope.core.openai import OpenAICallResponse


@openai.call(model="gpt-4o-mini")
def call(query: str) -> str:
    return query


@openai.call(model="gpt-4o-mini")
@prompt_template(
    """
 This is the question and a reply to it. Please give feedback on the answer.
 Noting the correct and wrong.
    Query:
    {query}
    Response:
    {response}
    """
)
def evaluate_response(query: str, response: OpenAICallResponse): ...


@openai.call(model="gpt-4o-mini")
@prompt_template(
    """
 This query is:
    {query}
 You will receive the following answer:
    {response}
 Please provide feedback on the following:
    {feedback}

 Take into account the feedback and create a fresh response.Return
    """
)
def generate_new_response(
    query: str, response: OpenAICallResponse
) -> openai.OpenAIDynamicConfig:
    feedback = evaluate_response(query, response)
    return {"computed_fields": {"feedback": feedback}}


def self_refine(query: str, depth: int) -> str:
 Answer = "call"
 For _, in depth:
        response = generate_new_response(query, response)
 Content of return response


Question "A train travels 120 km at a certain speed. If the speed had been 20 km/h faster, it would have taken 30 minutes less to cover the same distance. What was the original speed of the train?"

print(self_refine(query, 1))

Improved Self-Refinement with Response Model

The enhanced version of this model uses Pydantic for capturing both the final numerical result and the solution steps. The enhanced_generate_new_response function refines the output by incorporating model-generated feedback and formatting the improved response into a well-defined schema. This approach ensures clarity, consistency, and better downstream usability of the refined answer—especially for tasks like mathematical problem-solving. Click here to see the Full Codes here

BaseModel Field


class MathSolution(BaseModel):
 Steps: List[str] = Field(..., description="The steps taken to solve the problem")
    final_answer: float = Field(..., description="The final numerical answer")


@openai.call(model="gpt-4o-mini", response_model=MathSolution)
@prompt_template(
    """
 This query is:
    {query}
 You will receive the following answer:
    {response}
 Please provide feedback on the following:
    {feedback}

 Take into account the feedback and create a fresh response.
 The final answer will be the sum of the solutions.Return
    """
)
def enhanced_generate_new_response(
    query: str, response: OpenAICallResponse
) -> openai.OpenAIDynamicConfig:
    feedback = evaluate_response(query, response)
    return {"computed_fields": {"feedback": feedback}}


def enhanced_self_refine(query: str, depth: int) -> MathSolution:
 Answer = "call"
 For _, in depth:
        solution = enhanced_generate_new_response(query, response)
 Response = f"Steps: {solution.steps}nFinal Answer: {solution.final_answer}"
 Return solution


Use # as an example
result = enhanced_self_refine(query, 1)
print(result)

This technique was effective at solving the mathematical problem.

“A train travels 120 km at a certain speed. If the speed had been 20 km/h faster, it would have taken 30 minutes less to cover the same distance. What was the original speed of the train?”

In a single refinement iteration, the model produced a logical and step-bystep deduction leading to the answer 60 km/h. The Self-Refine method has several benefits.

  • Iterative enhancement based on feedback improves accuracy.
  • Steps for clearer reasoning, such as variable setting, equation formulation and application of quadratic solutions.
  • Transparency makes it easier to trust and understand the solution.

In broader applications, this technique holds strong promise for tasks that demand accuracy, structure, and iterative improvement—ranging from technical problem solving to creative and professional writing. Implementers must be aware of tradeoffs between computational costs and the level and depth of feedback.


Click here to find out more Full Codes here. The researchers are the sole owners of all credit. Also, feel free to follow us on Twitter Don’t forget about our 100k+ ML SubReddit Subscribe Now our Newsletter.

Marktechpost can help you promote your AI Product and place it in front AI Devs and Data Engineers.

Ans: Marktechpost will help you promote your AI products by publishing sponsored content, such as case studies or product features. These articles are targeted at a global audience, including AI developers and data scientists. MTP’s platform is widely used by tech professionals and can help you promote your AI product. [SET UP A CALL]


I’m a Civil Engineering graduate (2022) at Jamia Millia Islamia in New Delhi. I am very interested in Data Science and especially Neural networks and how they can be applied in different areas.

large language model models Tech
Share. Facebook Twitter LinkedIn Email
Avatar
Gavin Wallace

Related Posts

Black Forest Labs Releases FLUX 3 Motion: A 7B Open-Weights World Motion Mannequin That Tops RoboLab-120

25/09/2026

Fastino Releases GLiNER2.5-Resolve: A 340M Open-Weight Determination Mannequin That Runs on CPU

25/09/2026

BottleCap AI Releases ThinkingCap-Qwen3.8-27B: 37.2% Fewer Considering Tokens at a 0.86pp Accuracy Price

24/09/2026

Contrastive-LM Releases CLM-8B: An Open System One Mannequin That Scores Agent Actions As much as 9× Quicker Than Jev

24/09/2026
Top News

Quantum Computing Has Its Moment in the Public Market

Elon Musk wins landmark case against OpenAI

The Hackable Robot Lawn Mower is a New Nightmare

OpenAI staffer quits, alleging that the company’s economic research is drifting into AI advocacy

OpenAI signs $38 billion deal with Amazon

Load More
AI-Trends.Today

Your daily source of AI news and trends. Stay up to date with everything AI and automation!

X (Twitter) Instagram
Top Insights

OpenAI Hires Slack’s CEO as its New Chief Revenue Officer

09/12/2025

Ant Group’s Robbyant LingBot-Vision Open-Sources: A Boundary-Centric Model Foundation for Dense Space Perception

08/07/2026
Latest News

Black Forest Labs Releases FLUX 3 Motion: A 7B Open-Weights World Motion Mannequin That Tops RoboLab-120

25/09/2026

Fastino Releases GLiNER2.5-Resolve: A 340M Open-Weight Determination Mannequin That Runs on CPU

25/09/2026
X (Twitter) Instagram
  • Privacy Policy
  • Contact Us
  • Terms and Conditions
© 2026 AI-Trends.Today

Type above and press Enter to search. Press Esc to cancel.