Certainly! Let's go through your code step-by-step to identify and rectify the issues. I'll provide explanations for each correction to ensure clarity.
1. Imports and Syntax Errors
Issue:
- Missing Imports: You're using
List from the typing module but haven't imported it.
- Syntax Error: The comment and the import statement for
pydantic are on the same line without a space.
- Missing LangChain Imports: Classes like
ChatOpenAI and ChatPromptTemplate from LangChain are used but not imported.
- Incorrect Model Name: The model name
"gpt-4o-mini" seems incorrect. It should likely be "gpt-4" or another valid variant.
Corrections:
- Import
List from typing.
- Separate the comment from the import statement with a newline.
- Import necessary classes from LangChain.
- Correct the model name to a valid one.
2. Structured Output Handling
Issue:
with_structured_output Method: This method doesn't exist in LangChain's ChatOpenAI. Instead, you should use output_parser or handle parsing manually.
- Usage of
invoke: The invoke method isn't a standard method in LangChain's workflow. Instead, you should call the chain directly.
Corrections:
- Use
output_parser to parse the LLM responses into structured data.
- Call the chain directly instead of using
invoke.
3. State Management
Issue:
- Updating State Fields: In functions like
improve_goal and auto_grok_output_fields, you're updating state["goal"] instead of their respective improved or grokked fields.
Corrections:
- Update the correct fields in the state dictionary to reflect changes appropriately.
4. Complete Corrected Code
Below is the fully corrected version of your code with detailed comments explaining each change:
import openai
from typing_extensions import TypedDict # Use this for Python < 3.12
from typing import List
from pydantic import BaseModel, Field
from io import BytesIO
from PIL import Image
from IPython.display import display
# Import necessary classes from LangChain
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.schema import HumanMessage, SystemMessage
# Set your OpenAI API key
openai.api_key = "sk-..." # Replace with your actual OpenAI API key
# Define the structure for BP fields
class OutputField(TypedDict):
name: str
description: str
type: str
source: str
required: bool
class BPState(TypedDict):
goal: str
output_fields: List[OutputField]
examples: List[str]
improved_goal: str
grokked_output_fields: List[OutputField]
generated_examples: List[str]
chosen_prompt: str
# Define structured models for OpenAI's LLM function calls
class ImprovedGoal(BaseModel):
"""Structured output for improved goal."""
improved_goal: str = Field(description="The improved or rephrased version of the user's goal.")
class GrokkedOutputFields(BaseModel):
"""Structured output for grokked output fields."""
grokked_output_fields: List[OutputField] = Field(description="The enhanced output fields list.")
class GeneratedExamples(BaseModel):
"""Structured output for generated examples."""
examples: List[str] = Field(description="Generated examples based on the goal and output fields.")
class ChosenPrompt(BaseModel):
"""Structured output for chosen prompt."""
chosen_prompt: str = Field(description="The most complete prompt chosen for inference.")
# Initialize the OpenAI LLM via LangChain
llm = ChatOpenAI(model_name="gpt-4", temperature=0) # Corrected model name
# 1. Improve Goal
def improve_goal(state: BPState) -> BPState:
"""Improve or rephrase the goal using OpenAI API."""
goal_system = "You are a goal improvement agent. Improve the following goal."
goal_prompt = ChatPromptTemplate.from_messages(
[
SystemMessage(content=goal_system),
HumanMessage(content="Goal: {goal}")
]
)
# Format the prompt with the current goal
formatted_prompt = goal_prompt.format_messages(goal=state["goal"])
# Get the response from the LLM
response = llm(formatted_prompt)
# Assuming the LLM returns JSON-like structured response
# You might need to parse the response accordingly
# Here, we're using simple extraction for demonstration
improved_goal = response.content.strip()
# Update the state with the improved goal
state["improved_goal"] = improved_goal
state["goal"] = improved_goal # If you want to replace the original goal
return state
# 2. Auto Grok Output Fields
def auto_grok_output_fields(state: BPState) -> BPState:
"""Auto grok output fields using OpenAI API."""
grok_system = "You are a field augmentation agent. Suggest output fields based on the goal."
grok_prompt = ChatPromptTemplate.from_messages(
[
SystemMessage(content=grok_system),
HumanMessage(content="Goal: {goal}")
]
)
# Format the prompt with the improved goal
formatted_prompt = grok_prompt.format_messages(goal=state["goal"])
# Get the response from the LLM
response = llm(formatted_prompt)
# Here, you should parse the response into a list of OutputField
# For demonstration, let's assume the response is a JSON array
import json
try:
grokked_output_fields = json.loads(response.content)
except json.JSONDecodeError:
grokked_output_fields = state["output_fields"] # Fallback to original if parsing fails
# Update the state with grokked output fields
state["grokked_output_fields"] = grokked_output_fields
state["output_fields"] = grokked_output_fields # If you want to replace the original fields
return state
# 3. Generate Examples
def generate_examples(state: BPState) -> BPState:
"""Generate examples using OpenAI API."""
examples_system = "You are an example generation agent. Create example inputs and outputs for the following goal and fields."
examples_prompt = ChatPromptTemplate.from_messages(
[
SystemMessage(content=examples_system),
HumanMessage(content="Goal: {goal}, Output Fields: {output_fields}")
]
)
# Convert output_fields to a readable format, e.g., JSON string
import json
output_fields_str = json.dumps(state["output_fields"], indent=2)
# Format the prompt with the current goal and output fields
formatted_prompt = examples_prompt.format_messages(goal=state["goal"], output_fields=output_fields_str)
# Get the response from the LLM
response = llm(formatted_prompt)
# Assuming the LLM returns a list of examples separated by newlines
generated_examples = response.content.strip().split('\n')
# Update the state with generated examples
state["generated_examples"] = generated_examples
state["examples"] = generated_examples # If you want to replace the original examples
return state
# 4. Generate Candidate Prompts (with structured outputs)
def generate_candidate_prompts(state: BPState) -> List[str]:
"""Generate three candidate prompts using structured output."""
prompt_system = "You are a prompt generator. Create a complete prompt based on the following goal, output fields, and examples."
prompt_template = ChatPromptTemplate.from_messages(
[
SystemMessage(content=prompt_system),
HumanMessage(content="Goal: {goal}, Output Fields: {output_fields}, Examples: {examples}")
]
)
candidates = []
# Convert output_fields and examples to readable formats
import json
output_fields_str = json.dumps(state["output_fields"], indent=2)
examples_str = "\n".join(state["examples"])
for _ in range(3): # Generate 3 candidate prompts
formatted_prompt = prompt_template.format_messages(
goal=state["goal"],
output_fields=output_fields_str,
examples=examples_str
)
response = llm(formatted_prompt)
chosen_prompt = response.content.strip()
candidates.append(chosen_prompt)
return candidates
# 5. Evaluate Prompts
def evaluate_prompts(candidates: List[str]) -> str:
"""Select the best prompt using a heuristic."""
# For now, we're using length as a heuristic; replace with a better heuristic or G-Eval later
best_prompt = max(candidates, key=len)
return best_prompt
# Overall Workflow
def run_blueprint_workflow(goal: str, output_fields: List[OutputField], examples: List[str]) -> str:
"""Run the BP workflow and return the chosen prompt."""
# Initial state with user inputs
state: BPState = {
"goal": goal,
"output_fields": output_fields,
"examples": examples,
"improved_goal": "",
"grokked_output_fields": [],
"generated_examples": [],
"chosen_prompt": ""
}
# Step 1: Improve the Goal
state = improve_goal(state)
# Step 2: Auto Grok Output Fields
state = auto_grok_output_fields(state)
# Step 3: Generate Examples
state = generate_examples(state)
# Step 4: Generate Candidate Prompts
candidates = generate_candidate_prompts(state)
# Step 5: Evaluate and choose the best prompt
state["chosen_prompt"] = evaluate_prompts(candidates)
return state["chosen_prompt"]
# Example Input Data
goal_input = "Create an AI agent that helps with task scheduling based on user availability."
output_fields_input = [
{
"name": "task_name",
"description": "The name of the task to schedule.",
"type": "string",
"source": "user input",
"required": True
},
{
"name": "scheduled_time",
"description": "The time at which the task is scheduled.",
"type": "datetime",
"source": "calendar",
"required": True
}
]
examples_input = [
"Input: Schedule a meeting for tomorrow at 10 AM. Output: {'task_name': 'meeting', 'scheduled_time': '2023-10-23T10:00:00'}.",
"Input: Set a reminder for next Monday. Output: {'task_name': 'reminder', 'scheduled_time': '2023-10-30T09:00:00'}."
]
# Running the workflow with the input data
chosen_prompt = run_blueprint_workflow(goal_input, output_fields_input, examples_input)
# Output the chosen prompt
print("Chosen Prompt for Inference:")
print(chosen_prompt)
5. Detailed Explanations of Corrections
-
Imports:
List: Imported from typing to use for type annotations.
- LangChain Classes: Imported
ChatOpenAI and ChatPromptTemplate from LangChain to handle LLM interactions.
-
Model Name Correction:
- Changed
model="gpt-4o-mini" to model_name="gpt-4" assuming "gpt-4o-mini" was a typo. Ensure you use the correct model name as per your OpenAI subscription.
-
Structured Output Handling:
- Removed
with_structured_output as it's not a standard method in LangChain. Instead, after receiving the response from the LLM, manually parse it into the desired structured format using Pydantic models or JSON parsing.
-
Prompt Formatting:
- Used
format_messages to inject variables into the prompt templates.
- Ensured outputs from the LLM are correctly parsed and assigned to the state.
-
State Updates:
- Ensured that each step updates the appropriate fields in the
state dictionary rather than overwriting unrelated fields.
-
Error Handling:
- Added a
try-except block when parsing JSON responses to handle potential parsing errors gracefully.
-
Candidate Prompt Generation:
- Moved the
prompt_template creation outside the loop since it remains the same for each iteration.
- Ensured that output fields and examples are converted to string formats suitable for the prompt.
-
Example Inputs:
- Modified the example outputs to use single quotes inside the dictionary to avoid JSON parsing issues if necessary.
6. Additional Recommendations
-
Response Parsing: Depending on how the LLM formats its responses, you might need more sophisticated parsing logic. Consider using regex or natural language processing techniques to extract structured data reliably.
-
Heuristics for Evaluation: Currently, the code selects the longest prompt as the best one. Depending on your requirements, you might want to implement more meaningful heuristics, such as prompt clarity, completeness, or alignment with desired outcomes.
-
Testing: Before deploying, test each function individually with mock responses to ensure that parsing and state updates work as expected.
-
API Key Security: Ensure that your OpenAI API key is securely managed and not hard-coded in the script, especially if sharing the code publicly.
7. Conclusion
The corrected code should now run without syntax errors and handle the workflow as intended. Ensure that all dependencies, especially LangChain, are installed and up-to-date. If you encounter specific runtime errors, feel free to provide the error messages for further assistance.