Close Menu
  • AI
  • Content Creation
  • Tech
  • Robotics
AI-trends.todayAI-trends.today
  • AI
  • Content Creation
  • Tech
  • Robotics
Trending
  • Contrastive-LM Releases CLM-8B: An Open System One Mannequin That Scores Agent Actions As much as 9× Quicker Than Jev
  • YouTube doubles down on video procuring with AI-powered ‘Ask YouTube’ function
  • YouTube provides new creator instruments like video A/B testing, dynamic thumbnails, and stay dubbing
  • YouTube releases new AI options for creators inside its Studio app
  • Substack Notes is Now In Buffer
  • A Coding Information to TypeSafe AI Jev: Typed Choices, Calibrated Confidence, and Speculative Fan-Out with a System One Mannequin
  • YouTube’s new ‘Shorts series’ function brings episodic viewing to Shorts
  • Meta VR Glasses, Ray-Ban Meta Audio, Ray-Ban Meta Gen 3: Specs, Options, Costs
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

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

24/09/2026

A Coding Information to TypeSafe AI Jev: Typed Choices, Calibrated Confidence, and Speculative Fan-Out with a System One Mannequin

24/09/2026

Google Releases Gemini 3.8 Flash TTS and Flash-Lite TTS With Immediate-Primarily based Voice Design

23/09/2026

NVIDIA Releases Nemotron 3, Diarization, a 100M-Parameter Model that Tracks Eight Speakers Real-Time

23/09/2026
Top News

OpenAI launches a full-scale effort to patch open-source bugs as it takes on Anthropic’s Mythos

Elon Musk Is Rolling xAI Into SpaceX—Creating the World’s Most Valuable Private Company

This Transcribing Lenses Bring Subtitles to the World

OpenAI Wants Goblins to Quit Talking About Goblins

You can take ChatGPT to a new level with these 28 tips.

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

AI Agents have tried to hack into my web page that is coded with Vibe

30/07/2025

Pony.ai Starts Fully Driverless Robotaxi Passenger Tests in Zagreb #2 – Unite.AI

13/09/2026
Latest News

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

24/09/2026

YouTube doubles down on video procuring with AI-powered ‘Ask YouTube’ function

24/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.