Commit ·
f02d14f
1
Parent(s): f85bd5d
fully implemented the generate script functionality
Browse files- __init__.py +0 -0
- app.py +6 -1
- classes.py +24 -0
- components/__init__.py +0 -0
- components/json_grabber.py +20 -0
- components/output_validator.py +69 -0
- pipelines/.gradio/flagged/dataset1.csv +0 -3
- pipelines/__init__.py +0 -0
- pipelines/generate_script.py +45 -14
- pipelines/generate_script.yml +33 -30
- requirements.txt +1 -0
__init__.py
ADDED
|
File without changes
|
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
from haystack import Pipeline
|
| 3 |
from pydantic import BaseModel
|
|
|
|
| 4 |
|
| 5 |
app = FastAPI()
|
| 6 |
|
|
@@ -24,7 +25,11 @@ async def generate_script(req: ScriptRequest):
|
|
| 24 |
|
| 25 |
results = pipe.run(
|
| 26 |
{
|
| 27 |
-
"prompt_builder": {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
}
|
| 29 |
)
|
| 30 |
|
|
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
from haystack import Pipeline
|
| 3 |
from pydantic import BaseModel
|
| 4 |
+
from classes import CourseOutline
|
| 5 |
|
| 6 |
app = FastAPI()
|
| 7 |
|
|
|
|
| 25 |
|
| 26 |
results = pipe.run(
|
| 27 |
{
|
| 28 |
+
"prompt_builder": {
|
| 29 |
+
"topic": req.topic,
|
| 30 |
+
"time": req.time,
|
| 31 |
+
"schema": CourseOutline.model_json_schema(),
|
| 32 |
+
},
|
| 33 |
}
|
| 34 |
)
|
| 35 |
|
classes.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel
|
| 2 |
+
from typing import List
|
| 3 |
+
from enum import Enum
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class FeatureEnum(str, Enum):
|
| 7 |
+
video = "video"
|
| 8 |
+
image = "image"
|
| 9 |
+
interactive = "interactive"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Module(BaseModel):
|
| 13 |
+
name: str
|
| 14 |
+
duration: str
|
| 15 |
+
subtopics: List[str]
|
| 16 |
+
features: List[FeatureEnum]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class CourseOutline(BaseModel):
|
| 20 |
+
title: str
|
| 21 |
+
objectives: List[str]
|
| 22 |
+
duration: str
|
| 23 |
+
modules: List[Module]
|
| 24 |
+
summary: str
|
components/__init__.py
ADDED
|
File without changes
|
components/json_grabber.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from haystack import component
|
| 2 |
+
from typing import List
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
@component
|
| 6 |
+
class JSONGrabber:
|
| 7 |
+
"""
|
| 8 |
+
A component that takes out a JSON body from a given string.
|
| 9 |
+
The string should have a JSON body encased with "<start>" and "<stop>" strings.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
@component.output_types(body=str)
|
| 13 |
+
def run(self, replies: List[str]):
|
| 14 |
+
reply = replies[0]
|
| 15 |
+
body = reply[reply.find("<start>") + len("<start>") :].strip()
|
| 16 |
+
body = body[: body.find("<stop>")].strip()
|
| 17 |
+
|
| 18 |
+
print(f"Grabbed JSON:\n{body}")
|
| 19 |
+
|
| 20 |
+
return {"body": body}
|
components/output_validator.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from haystack.core.serialization import import_class_by_name
|
| 3 |
+
import pydantic
|
| 4 |
+
from pydantic import ValidationError
|
| 5 |
+
from typing import Optional, List
|
| 6 |
+
from colorama import Fore
|
| 7 |
+
from haystack import component
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
output_validator.py
|
| 12 |
+
|
| 13 |
+
Purpose: Ensures that a JSON output generated by an LLM model is formatted correctly.
|
| 14 |
+
|
| 15 |
+
Copied from https://haystack.deepset.ai/tutorials/28_structured_output_with_loop !
|
| 16 |
+
;
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# Define the component input parameters
|
| 21 |
+
@component
|
| 22 |
+
class OutputValidator:
|
| 23 |
+
def __init__(self, pydantic_model: type[pydantic.BaseModel]):
|
| 24 |
+
self.pydantic_model = pydantic_model
|
| 25 |
+
self.iteration_counter = 0
|
| 26 |
+
|
| 27 |
+
def to_dict(self):
|
| 28 |
+
return {
|
| 29 |
+
"pydantic_model": f"{self.pydantic_model.__module__}.{self.pydantic_model.__name__}",
|
| 30 |
+
"type": "components.output_validator.OutputValidator",
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def from_dict(cls, data):
|
| 35 |
+
print(Fore.YELLOW + "Inside from_dict...")
|
| 36 |
+
model_class = import_class_by_name(data["pydantic_model"])
|
| 37 |
+
return cls(
|
| 38 |
+
pydantic_model=model_class,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# Define the component output
|
| 42 |
+
@component.output_types(
|
| 43 |
+
valid_replies=List[str],
|
| 44 |
+
invalid_replies=Optional[List[str]],
|
| 45 |
+
error_message=Optional[str],
|
| 46 |
+
)
|
| 47 |
+
def run(self, body: str):
|
| 48 |
+
self.iteration_counter += 1
|
| 49 |
+
|
| 50 |
+
## Try to parse the LLM's reply ##
|
| 51 |
+
# If the LLM's reply is a valid object, return `"valid_replies"`
|
| 52 |
+
try:
|
| 53 |
+
output_dict = json.loads(body)
|
| 54 |
+
self.pydantic_model.model_validate(output_dict)
|
| 55 |
+
print(
|
| 56 |
+
Fore.GREEN
|
| 57 |
+
+ f"OutputValidator at Iteration {self.iteration_counter}: Valid JSON from LLM - No need for looping: {body}"
|
| 58 |
+
)
|
| 59 |
+
return {"valid_replies": body}
|
| 60 |
+
|
| 61 |
+
# If the LLM's reply is corrupted or not valid, return "invalid_replies" and the "error_message" for LLM to try again
|
| 62 |
+
except (ValueError, ValidationError) as e:
|
| 63 |
+
print(
|
| 64 |
+
Fore.RED
|
| 65 |
+
+ f"OutputValidator at Iteration {self.iteration_counter}: Invalid JSON from LLM - Let's try again.\n"
|
| 66 |
+
f"Output from LLM:\n {body} \n"
|
| 67 |
+
f"Error from OutputValidator: {e}"
|
| 68 |
+
)
|
| 69 |
+
return {"invalid_replies": body, "error_message": str(e)}
|
pipelines/.gradio/flagged/dataset1.csv
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
Text,timestamp
|
| 2 |
-
"tell me a story about a time you were in a situation where you had to make a decision and you didn’t know what to do. What was the outcome?
|
| 3 |
-
I was in a situation where I had to make a decision and I didn’t know what to do. I was in a situation where I had to make a decision and I didn’t know what to do. I was in a situation where I had to make a decision and I didn’t know what to do. I was in a situation where I had",2024-11-11 00:10:45.021000
|
|
|
|
|
|
|
|
|
|
|
|
pipelines/__init__.py
ADDED
|
File without changes
|
pipelines/generate_script.py
CHANGED
|
@@ -2,19 +2,25 @@ from haystack import Pipeline
|
|
| 2 |
from haystack.components.builders import PromptBuilder
|
| 3 |
from haystack.components.generators import HuggingFaceAPIGenerator
|
| 4 |
from haystack.utils import Secret
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
template = """
|
| 7 |
-
You are a training manager. You are tasked to create an online, asynchronous course for new employees.
|
| 8 |
-
Create
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
| 18 |
"""
|
| 19 |
|
| 20 |
builder = PromptBuilder(template=template)
|
|
@@ -23,18 +29,43 @@ generator = HuggingFaceAPIGenerator(
|
|
| 23 |
api_type="serverless_inference_api",
|
| 24 |
api_params={"model": "meta-llama/Meta-Llama-3-8B-Instruct"},
|
| 25 |
token=Secret.from_env_var("HF_API_TOKEN"),
|
|
|
|
| 26 |
)
|
| 27 |
|
| 28 |
-
pipeline = Pipeline()
|
|
|
|
| 29 |
pipeline.add_component("prompt_builder", PromptBuilder(template=template))
|
| 30 |
pipeline.add_component("llm", generator)
|
|
|
|
|
|
|
|
|
|
| 31 |
pipeline.connect("prompt_builder", "llm")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
with open("generate_script.yml", "w") as file:
|
| 34 |
pipeline.dump(file)
|
|
|
|
|
|
|
| 35 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
results = pipeline.run(
|
| 37 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
print(results)
|
| 40 |
"""
|
|
|
|
| 2 |
from haystack.components.builders import PromptBuilder
|
| 3 |
from haystack.components.generators import HuggingFaceAPIGenerator
|
| 4 |
from haystack.utils import Secret
|
| 5 |
+
from components.output_validator import OutputValidator
|
| 6 |
+
from components.json_grabber import JSONGrabber
|
| 7 |
+
from classes import CourseOutline
|
| 8 |
+
|
| 9 |
+
output_validator = OutputValidator(pydantic_model=CourseOutline)
|
| 10 |
|
| 11 |
template = """
|
| 12 |
+
You are a training manager. You are tasked to create an online, asynchronous course intended for new employees.
|
| 13 |
+
Create one JSON object based on the requested topic of {{topic}} within the requested estimated time of {{time}}.
|
| 14 |
+
Follow this JSON schema, but only return the actual instance without any additional schema definitions:
|
| 15 |
+
{{schema}}
|
| 16 |
+
Make sure your response is a dict and not a list.
|
| 17 |
+
Put this string: "<start>" right before the JSON object.
|
| 18 |
+
Put this string: "<stop>" right after the JSON object.
|
| 19 |
+
{% if invalid_replies and error_message %}
|
| 20 |
+
You already created the following output in a previous attempt: {{invalid_replies}}
|
| 21 |
+
However, this doesn't comply with the format requirements from above and triggered this Python exception: {{error_message}}
|
| 22 |
+
Correct the output and try again. Just return the corrected output without any extra explanations.
|
| 23 |
+
{% endif %}
|
| 24 |
"""
|
| 25 |
|
| 26 |
builder = PromptBuilder(template=template)
|
|
|
|
| 29 |
api_type="serverless_inference_api",
|
| 30 |
api_params={"model": "meta-llama/Meta-Llama-3-8B-Instruct"},
|
| 31 |
token=Secret.from_env_var("HF_API_TOKEN"),
|
| 32 |
+
generation_kwargs={"max_new_tokens": 1024, "stop": ["<stop>"]},
|
| 33 |
)
|
| 34 |
|
| 35 |
+
pipeline = Pipeline(max_runs_per_component=5)
|
| 36 |
+
|
| 37 |
pipeline.add_component("prompt_builder", PromptBuilder(template=template))
|
| 38 |
pipeline.add_component("llm", generator)
|
| 39 |
+
pipeline.add_component("json_grabber", instance=JSONGrabber())
|
| 40 |
+
pipeline.add_component("output_validator", output_validator)
|
| 41 |
+
|
| 42 |
pipeline.connect("prompt_builder", "llm")
|
| 43 |
+
pipeline.connect("llm.replies", "json_grabber.replies")
|
| 44 |
+
pipeline.connect("json_grabber.body", "output_validator.body")
|
| 45 |
+
pipeline.connect("output_validator.invalid_replies", "prompt_builder.invalid_replies")
|
| 46 |
+
pipeline.connect("output_validator.error_message", "prompt_builder.error_message")
|
| 47 |
|
| 48 |
+
with open("./pipelines/generate_script.yml", "w") as file:
|
| 49 |
pipeline.dump(file)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
"""
|
| 53 |
+
|
| 54 |
+
json_schema = CourseOutline.model_json_schema()
|
| 55 |
+
import json
|
| 56 |
+
|
| 57 |
results = pipeline.run(
|
| 58 |
+
{
|
| 59 |
+
"prompt_builder": {
|
| 60 |
+
"topic": "Artificial Intelligence",
|
| 61 |
+
"time": "one hour",
|
| 62 |
+
"schema": json_schema,
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
)
|
| 66 |
+
from haystack.core.pipeline.template import Path
|
| 67 |
+
|
| 68 |
+
pipeline.draw(path=Path("pipeline.png"))
|
| 69 |
+
print(type(results))
|
| 70 |
print(results)
|
| 71 |
"""
|
pipelines/generate_script.yml
CHANGED
|
@@ -1,51 +1,54 @@
|
|
| 1 |
components:
|
|
|
|
|
|
|
|
|
|
| 2 |
llm:
|
| 3 |
init_parameters:
|
| 4 |
api_params:
|
| 5 |
model: meta-llama/Meta-Llama-3-8B-Instruct
|
| 6 |
api_type: serverless_inference_api
|
| 7 |
generation_kwargs:
|
| 8 |
-
max_new_tokens:
|
|
|
|
|
|
|
| 9 |
stop_sequences: []
|
| 10 |
streaming_callback: null
|
| 11 |
token:
|
| 12 |
env_vars:
|
| 13 |
-
|
| 14 |
strict: true
|
| 15 |
type: env_var
|
| 16 |
type: haystack.components.generators.hugging_face_api.HuggingFaceAPIGenerator
|
|
|
|
|
|
|
|
|
|
| 17 |
prompt_builder:
|
| 18 |
init_parameters:
|
| 19 |
required_variables: null
|
| 20 |
-
template: "
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
- Subtopics for each Main Topic
|
| 33 |
-
|
| 34 |
-
- Interactive Activities (if applicable)
|
| 35 |
-
|
| 36 |
-
- Estimated time for each topic within {{ time }}
|
| 37 |
-
|
| 38 |
-
- Assessments or quizzes (if any)
|
| 39 |
-
|
| 40 |
-
- Additional Resources
|
| 41 |
-
|
| 42 |
-
- Conclusion
|
| 43 |
-
|
| 44 |
-
"
|
| 45 |
variables: null
|
| 46 |
type: haystack.components.builders.prompt_builder.PromptBuilder
|
| 47 |
connections:
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
metadata: {}
|
|
|
|
| 1 |
components:
|
| 2 |
+
json_grabber:
|
| 3 |
+
init_parameters: {}
|
| 4 |
+
type: components.json_grabber.JSONGrabber
|
| 5 |
llm:
|
| 6 |
init_parameters:
|
| 7 |
api_params:
|
| 8 |
model: meta-llama/Meta-Llama-3-8B-Instruct
|
| 9 |
api_type: serverless_inference_api
|
| 10 |
generation_kwargs:
|
| 11 |
+
max_new_tokens: 1024
|
| 12 |
+
stop:
|
| 13 |
+
- <stop>
|
| 14 |
stop_sequences: []
|
| 15 |
streaming_callback: null
|
| 16 |
token:
|
| 17 |
env_vars:
|
| 18 |
+
- HF_API_TOKEN
|
| 19 |
strict: true
|
| 20 |
type: env_var
|
| 21 |
type: haystack.components.generators.hugging_face_api.HuggingFaceAPIGenerator
|
| 22 |
+
output_validator:
|
| 23 |
+
pydantic_model: classes.CourseOutline
|
| 24 |
+
type: components.output_validator.OutputValidator
|
| 25 |
prompt_builder:
|
| 26 |
init_parameters:
|
| 27 |
required_variables: null
|
| 28 |
+
template: "\nYou are a training manager. You are tasked to create an online,\
|
| 29 |
+
\ asynchronous course intended for new employees.\nCreate one JSON object\
|
| 30 |
+
\ based on the requested topic of {{topic}} within the requested estimated\
|
| 31 |
+
\ time of {{time}}.\nFollow this JSON schema, but only return the actual instance\
|
| 32 |
+
\ without any additional schema definitions:\n{{schema}}\nMake sure your response\
|
| 33 |
+
\ is a dict and not a list.\nPut this string: \"<start>\" right before the\
|
| 34 |
+
\ JSON object.\nPut this string: \"<stop>\" right after the JSON object.\n\
|
| 35 |
+
{% if invalid_replies and error_message %}\n You already created the following\
|
| 36 |
+
\ output in a previous attempt: {{invalid_replies}}\n However, this doesn't\
|
| 37 |
+
\ comply with the format requirements from above and triggered this Python\
|
| 38 |
+
\ exception: {{error_message}}\n Correct the output and try again. Just return\
|
| 39 |
+
\ the corrected output without any extra explanations.\n{% endif %}\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
variables: null
|
| 41 |
type: haystack.components.builders.prompt_builder.PromptBuilder
|
| 42 |
connections:
|
| 43 |
+
- receiver: llm.prompt
|
| 44 |
+
sender: prompt_builder.prompt
|
| 45 |
+
- receiver: json_grabber.replies
|
| 46 |
+
sender: llm.replies
|
| 47 |
+
- receiver: output_validator.body
|
| 48 |
+
sender: json_grabber.body
|
| 49 |
+
- receiver: prompt_builder.invalid_replies
|
| 50 |
+
sender: output_validator.invalid_replies
|
| 51 |
+
- receiver: prompt_builder.error_message
|
| 52 |
+
sender: output_validator.error_message
|
| 53 |
+
max_runs_per_component: 5
|
| 54 |
metadata: {}
|
requirements.txt
CHANGED
|
@@ -2,3 +2,4 @@ fastapi[standard]
|
|
| 2 |
haystack-ai
|
| 3 |
uvicorn[standard]
|
| 4 |
huggingface_hub
|
|
|
|
|
|
| 2 |
haystack-ai
|
| 3 |
uvicorn[standard]
|
| 4 |
huggingface_hub
|
| 5 |
+
colorama
|