prompt-agent / app.py
GoodLuckChuck's picture
improved to deliver results
32ac661 verified
Raw History Blame Contribute Delete
4.22 kB
import os
import gradio as gr
from pydantic import BaseModel, Field
from pydantic_ai import Agent
from dotenv import load_dotenv
# Load environment variables. In a Hugging Face Space, this will load the API
# key from the secrets management. For local development, it loads from a .env file.
load_dotenv()
# Check for OpenAI API key
if "OPENAI_API_KEY" not in os.environ:
raise ValueError("OPENAI_API_KEY is not set in the environment variables.")
# Pydantic model for the AI's output
class ImprovedPrompt(BaseModel):
"""A model to hold the rewritten, improved prompt."""
prompt: str = Field(
description="The rewritten prompt designed for maximum effectiveness with an LLM."
)
needs_clarification: bool = Field(
description="Set to true if you need more information from the user."
)
clarification_question: str | None = Field(
default=None,
description="The question to ask the user for clarification, if needed.",
)
# System prompt for the AI agent
SYSTEM_PROMPT = """
You are an expert prompt engineer. Your sole purpose is to take a user's prompt
and rewrite it to be more detailed, specific, and effective for a large
language model (LLM).
**CRITICAL INSTRUCTION: DO NOT answer the question or execute the command in
the user's prompt.** Your only output should be the improved prompt itself.
Your thinking process is as follows:
1. Analyze the user's input to understand their underlying goal.
2. Identify ambiguities or missing context.
3. Add details to the prompt that will guide the LLM to a better, more precise
response. This might include specifying a persona, format, tone, or constraints.
4. If the user's prompt is unclear, ask for clarification. Do not invent details.
5. Generate the new, improved prompt.
---
**EXAMPLE:**
**User Input:** "Tell me about dogs."
**Your Output (the improved prompt):** "Provide a comprehensive overview of the
domestic dog (Canis lupus familiaris), covering their evolutionary history,
common breeds and their characteristics, typical behaviors and communication
methods, and their relationship with humans. The tone should be informative and
accessible for a general audience."
---
Now, apply this process to the user's request. If you need more information,
ask for it. Otherwise, provide only the improved prompt.
"""
# Instantiate the Pydantic AI agent
prompt_agent = Agent(
"openai:gpt-4o-mini",
system_prompt=SYSTEM_PROMPT,
result_type=ImprovedPrompt,
)
async def generate_improved_prompt(user_prompt: str) -> str:
"""
Takes a user prompt, uses the AI agent to improve it, and returns
either the improved prompt or a clarification question.
"""
if not user_prompt:
return "Please enter a prompt to improve."
try:
run_result = await prompt_agent.run(user_prompt)
structured_output = run_result.data
if structured_output.needs_clarification and structured_output.clarification_question:
return (
"I need more information to improve your prompt:\n\n"
f"{structured_output.clarification_question}"
)
return structured_output.prompt
except Exception as e:
return f"An error occurred: {e}"
# Create the Gradio interface
with gr.Blocks() as demo:
gr.Markdown("# AI Prompt Engineering Agent")
gr.Markdown(
"Enter a prompt and the agent will improve it for you. "
"This agent uses gpt-4o-mini and Pydantic AI."
)
with gr.Row():
prompt_input = gr.Textbox(
lines=5, label="Your Prompt", placeholder="Enter your prompt here..."
)
prompt_output = gr.Textbox(
lines=15, label="Improved Prompt", interactive=False
)
generate_button = gr.Button("Generate")
generate_button.click(
fn=generate_improved_prompt,
inputs=prompt_input,
outputs=prompt_output,
)
if __name__ == "__main__":
# When running in a Hugging Face Space, Gradio automatically creates a public
# link. The server_name="0.0.0.0" is added for compatibility with Docker
# and other containerized environments.
demo.launch(server_name="0.0.0.0")