Spaces:
Sleeping
Sleeping
File size: 11,867 Bytes
d477d5c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 |
from __future__ import annotations
import ast
import json
import os
import random
import logging
import requests
from dotenv import load_dotenv
from griptape.artifacts import ListArtifact, TextArtifact
from griptape.configs import Defaults
from griptape.configs.drivers import OpenAiDriversConfig
from griptape.drivers import (
LocalStructureRunDriver,
OpenAiChatPromptDriver,
GriptapeCloudVectorStoreDriver,
)
from griptape.artifacts import ListArtifact, TextArtifact
from griptape.rules import Ruleset, Rule
import json
import requests
import random
import os
from dotenv import load_dotenv
from griptape.engines.rag import RagEngine
from griptape.engines.rag.modules import (
VectorStoreRetrievalRagModule,
TextChunksResponseRagModule,
)
from griptape.engines.rag.stages import ResponseRagStage, RetrievalRagStage
from griptape.tools import RagTool
from griptape.configs.logging import TruncateLoggingFilter
from griptape_statemachine.parsers.uw_csv_parser import CsvParser
load_dotenv()
# openai default config pass in a new openai driver
Defaults.drivers_config = OpenAiDriversConfig(
prompt_driver=OpenAiChatPromptDriver(model="gpt-4o", max_tokens=4096)
)
# logger = logging.getLogger(Defaults.logging_config.logger_name)
# logger.setLevel(logging.ERROR)
# logger.addFilter(TruncateLoggingFilter(max_log_length=5000))
# ALL METHODS RELATING TO THE WORKFLOW AND PIPELINE
def end_workflow(task: CodeExecutionTask) -> ListArtifact:
parent_outputs = task.parent_outputs
questions = []
for output in parent_outputs.values():
output = output.value
try:
output = ast.literal_eval(output)
question = {output["Question"]: output}
questions.append(TextArtifact(question))
except SyntaxError:
pass
return ListArtifact(questions)
def get_questions_workflow() -> Workflow:
workflow = Workflow(id="create_question_workflow")
# How many questions still need to be created
for _ in range(10):
task = StructureRunTask(
driver=LocalStructureRunDriver(create_structure=get_single_question),
child_ids=["end_task"],
)
workflow.add_task(task)
end_task = CodeExecutionTask(id="end_task", on_run=end_workflow)
workflow.add_task(end_task)
return workflow
def single_question_last_task(task: CodeExecutionTask) -> TextArtifact:
parent_outputs = task.parent_outputs
print(f"PARENT OUTPUTS ARE: {parent_outputs}")
wrong_answers = parent_outputs["wrong_answers"].value # Output is a list
wrong_answers = wrong_answers.split("\n")
question_and_answer = parent_outputs["get_question"].value # Output is a json
question_and_answer = json.loads(question_and_answer)
inputs = task.input.value.split(",")
question = {
"Question": question_and_answer["Question"],
"Answer": question_and_answer["Answer"],
"Wrong Answers": wrong_answers,
"Page": int(inputs[0]),
"Taxonomy": inputs[1],
}
return TextArtifact(question)
def get_question_for_wrong_answers(task: CodeExecutionTask) -> TextArtifact:
parent_outputs = task.parent_outputs
question = parent_outputs["get_question"].value
print(question)
question = json.loads(question)["Question"]
return TextArtifact(question)
def get_single_question() -> Workflow:
question_generator = Workflow()
page_number = random.choice(list(range(1, 9)))
taxonomy = random.choice(["Knowledge", "Comprehension", "Application"])
taxonomyprompt = {
"Knowledge": "Generate a quiz question based ONLY on this information: {{parent_outputs['information_task']}}, then write the answer to the question. The interrogative verb for the question should be one of 'define', 'list', 'state', 'identify', or 'label'.",
"Comprehension": "Generate a quiz question based ONLY on this information: {{parent_outputs['information_task']}}, then write the answer to the question. The interrogative verb for the question should be one of 'explain', 'predict', 'interpret', 'infer', 'summarize', 'convert', or 'give an example of x'.",
"Application": "Generate a quiz question based ONLY on this information: {{parent_outputs['information_task']}}, then write the answer to the question. The structure of the question should be one of 'How could x be used to y?' or 'How would you show/make use of/modify/demonstrate/solve/apply x to conditions y?'",
}
# Get KBs and select it, assign it to the structure or create the structure right here.
# Rules for subject matter expert: return only a json with question and answer as keys.
generate_q_task = StructureRunTask(
id="get_question",
input=taxonomyprompt[taxonomy],
driver=LocalStructureRunDriver(
create_structure=lambda: get_structure("subject_matter_expert", page_number)
),
)
get_question_code_task = CodeExecutionTask(
id="get_only_question",
on_run=get_question_for_wrong_answers,
parent_ids=["get_question"],
child_ids=["wrong_answers"],
)
# This will use the same KB as the previous task
generate_wrong_answers = StructureRunTask(
id="wrong_answers",
input="""Write and return three incorrect answers for this question: {{parent_outputs['get_only_question']}} with this context: {{parent_outputs['information_task']}}""",
structure_run_driver=LocalStructureRunDriver(
create_structure=lambda: get_structure("wrong_answers_generator")
),
parent_ids=["get_only_question"],
)
compile_task = CodeExecutionTask(
id="compile_task",
input=f"{page_number}, {taxonomy})",
on_run=single_question_last_task,
parent_ids=["wrong_answers", "get_question"],
)
question_generator.add_tasks(
generate_q_task,
get_question_code_task,
generate_wrong_answers,
compile_task,
)
return question_generator
def get_structure(structure_id: str, page_number=0) -> Structure:
match structure_id:
case "subject_matter_expert":
rulesets = Ruleset(
name="specific_question_creator",
rules=[
Rule(
"Return ONLY a json with 'Question' and 'Answer' as keys. No markdown, no commentary, no code, no backticks."
),
Rule(
"Query to knowledge base should always be 'find information for quiz question'"
),
Rule("Use ONLY information from your knowledge base"),
Rule(
"Question should be a question based on the knowledge base. Answer should be from knowledge base."
),
Rule(
"The answer to the question should be short, but should not omit important information."
),
Rule("Answer length should be 10 words maximum, 5 words minimum"),
],
)
structure = Agent(
id="subject_matter_expert",
prompt_driver=OpenAiChatPromptDriver(model="gpt-4o"),
rulesets=[rulesets],
tools=[tool],
)
case "taxonomy_expert":
rulesets = Ruleset(
name="KB Rules",
rules=[
Rule(
"Use only your knowledge base. Do not make up any additional information."
),
Rule("Maximum 10 words."),
Rule(
"Return information an AI chatbot could use to write a question on a subject."
),
],
)
kb_driver = get_taxonomy_vs()
tool = build_rag_tool(build_rag_engine(kb_driver))
structure = Agent(
id="taxonomy_expert",
prompt_driver=OpenAiChatPromptDriver(model="gpt-4o"),
tools=[tool],
)
case "wrong_answers_generator":
rulesets = Ruleset(
name="incorrect_answers_creator",
rules=[
Rule(
"Return ONLY a list of 3 incorrect answers. No markdown, no commentary, no backticks."
),
Rule(
"All incorrect answers should be different, but plausible answers to the question."
),
Rule(
"Incorrect answers may reference material from the knowledge base, but must not be correct answers to the question"
),
Rule(
"Length of incorrect answers should be 10 words max, 5 words minimum"
),
],
)
kb_driver = get_vector_store_id_from_page(page_number)
tool = build_rag_tool(build_rag_engine(kb_driver))
structure = Agent(
id="wrong_answers_generator",
prompt_driver=OpenAiChatPromptDriver(model="gpt-4o"),
rulesets=[rulesets],
tools=[tool],
)
case _:
structure = Agent(prompt_driver=OpenAiChatPromptDriver(model="gpt-4o"))
return structure
def get_vector_store_id_from_page(page: int) -> GriptapeCloudVectorStoreDriver | None:
base_url = "https://cloud.griptape.ai/api/"
kb_url = f"{base_url}/knowledge-bases"
headers = {"Authorization": f"Bearer {os.getenv('GT_CLOUD_API_KEY')}"}
# TODO: This needs to change when I have my own bucket. Right now, I'm doing the 10 most recently made KBs
response = requests.get(url=kb_url, headers=headers)
response = requests.get(
url=kb_url,
headers=headers,
)
response.raise_for_status()
if response.status_code == 200:
data = response.json()
for kb in data["knowledge_bases"]:
name = kb["name"]
if "KB_section" not in name:
continue
page_nums = name.split("pg")[1].split("-")
start_page = int(page_nums[0])
end_page = int(page_nums[1])
if end_page <= 40 and start_page >= 1:
possible_kbs[kb["knowledge_base_id"]] = f"{start_page}-{end_page}"
kb_id = random.choice(list(possible_kbs.keys()))
page_value = possible_kbs[kb_id]
return page_value, GriptapeCloudVectorStoreDriver(
api_key=os.getenv("GT_CLOUD_API_KEY", ""),
knowledge_base_id=kb_id,
)
else:
raise ValueError(response.status_code)
return None
def get_taxonomy_vs() -> GriptapeCloudVectorStoreDriver:
return GriptapeCloudVectorStoreDriver(
api_key=os.getenv("GT_CLOUD_API_KEY", ""),
knowledge_base_id="2c3a6f19-51a8-43c3-8445-c7fbe06bf460",
)
def build_rag_engine(vector_store_driver) -> RagEngine:
return RagEngine(
retrieval_stage=RetrievalRagStage(
retrieval_modules=[
VectorStoreRetrievalRagModule(
vector_store_driver=vector_store_driver,
query_params={
"count": 100,
},
)
],
),
response_stage=ResponseRagStage(
response_modules=[TextChunksResponseRagModule()]
),
)
def build_rag_tool(engine) -> RagTool:
return RagTool(
description="Contains information about the textbook. Use it to answer any related questions.",
rag_engine=engine,
)
if __name__ == "__main__":
# workflow = get_questions_workflow()
# workflow.run()
CsvParser("uw_programmatic").csv_parser()
|