|
| 1 | +from typing import Optional, List, Literal |
| 2 | +from langgraph.graph import END, START, MessagesState, StateGraph |
| 3 | +from langgraph.types import Command, interrupt |
| 4 | +from pydantic import BaseModel, Field, field_validator, ValidationInfo |
| 5 | +from uipath import UiPath |
| 6 | +from langchain_core.output_parsers import PydanticOutputParser |
| 7 | +import logging |
| 8 | +import time |
| 9 | +from uipath.models import InvokeProcess, IngestionInProgressException |
| 10 | +from langchain_core.messages import HumanMessage |
| 11 | +from uipath_langchain.retrievers import ContextGroundingRetriever |
| 12 | +from langchain_anthropic import ChatAnthropic |
| 13 | + |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | +llm = ChatAnthropic(model="claude-3-5-sonnet-latest") |
| 18 | + |
| 19 | +class QuizItem(BaseModel): |
| 20 | + question: str = Field( |
| 21 | + description="One quiz question" |
| 22 | + ) |
| 23 | + difficulty: float = Field( |
| 24 | + description="How difficult is the question", ge=0.0, le=1.0 |
| 25 | + ) |
| 26 | + answer: str = Field( |
| 27 | + description="The expected answer to the question", |
| 28 | + ) |
| 29 | +class Quiz(BaseModel): |
| 30 | + quiz_items: List[QuizItem] = Field( |
| 31 | + description="A list of quiz items" |
| 32 | + ) |
| 33 | +class QuizOrInsufficientInfo(BaseModel): |
| 34 | + quiz: Optional[Quiz] = Field( |
| 35 | + description="A quiz based on user input and available documents." |
| 36 | + ) |
| 37 | + additional_info: Optional[str] = Field( |
| 38 | + description="String that controls whether additional information is required", |
| 39 | + ) |
| 40 | + |
| 41 | + @field_validator("quiz") |
| 42 | + def check_quiz(cls, v, info: ValidationInfo): |
| 43 | + additional_info = info.data.get("additional_info") |
| 44 | + if additional_info == "false" and v is None: |
| 45 | + raise ValueError("Quiz should be None when additional_info is not 'false'") |
| 46 | + return v |
| 47 | + |
| 48 | +output_parser = PydanticOutputParser(pydantic_object=QuizOrInsufficientInfo) |
| 49 | + |
| 50 | +system_message ="""You are a quiz generator. Try to generate a quiz about {quiz_topic} with multiple questions ONLY based on the following documents. Do not use any extra information from your knowledgebase. |
| 51 | +If the documents do not provide enough info, respond with as little words as possible in the format 'additional_info=Need data about ...'. The additional_info should be around 10-15 words. |
| 52 | +If they provide enough info, create the quiz and set additional_info='false' |
| 53 | +
|
| 54 | +This is the context data: {context} |
| 55 | +
|
| 56 | +{format_instructions} |
| 57 | +
|
| 58 | +Respond with the classification in the requested JSON format.""" |
| 59 | + |
| 60 | +uipath = UiPath() |
| 61 | + |
| 62 | + |
| 63 | +class GraphOutput(BaseModel): |
| 64 | + quiz: Quiz |
| 65 | + |
| 66 | +class GraphInput(BaseModel): |
| 67 | + quiz_topic: str |
| 68 | + bucket_name: str |
| 69 | + index_name: str |
| 70 | + bucket_folder: Optional[str] = None |
| 71 | + |
| 72 | +class GraphState(MessagesState): |
| 73 | + quiz_topic: str |
| 74 | + bucket_name: str |
| 75 | + bucket_folder: Optional[str] |
| 76 | + index_name: str |
| 77 | + additional_info: Optional[bool] |
| 78 | + quiz: Optional[Quiz] |
| 79 | + |
| 80 | +def prepare_input(state: GraphInput) -> GraphState: |
| 81 | + return GraphState( |
| 82 | + quiz_topic=state.quiz_topic, |
| 83 | + bucket_name=state.bucket_name, |
| 84 | + index_name=state.index_name, |
| 85 | + additional_info="false", |
| 86 | + messages=("user", f"create a quiz about {state.quiz_topic}"), |
| 87 | + bucket_folder=state.bucket_folder, |
| 88 | + ) |
| 89 | + |
| 90 | +async def invoke_researcher(state: GraphState) -> Command: |
| 91 | + state["messages"].append(HumanMessage(f"{state['additional_info']}")), |
| 92 | + |
| 93 | + input_args_json = { |
| 94 | + "messages": state["messages"], |
| 95 | + "bucket_name": state["bucket_name"], |
| 96 | + "bucket_folder": state.get("bucket_folder", None), |
| 97 | + } |
| 98 | + agent_response = interrupt(InvokeProcess( |
| 99 | + name = "researcher-and-uploader-agent", |
| 100 | + input_arguments = input_args_json, |
| 101 | + )) |
| 102 | + |
| 103 | + return Command( |
| 104 | + update={ |
| 105 | + "messages": [agent_response["messages"][-1]], |
| 106 | + }) |
| 107 | + |
| 108 | +async def create_quiz(state: GraphState) -> Command: |
| 109 | + no_of_retries = 5 |
| 110 | + context_data = None |
| 111 | + data_queried = False |
| 112 | + index = uipath.context_grounding.get_or_create_index(state["index_name"], storage_bucket_name=state["bucket_name"], storage_bucket_folder_path=state["bucket_folder"]) |
| 113 | + uipath.context_grounding.ingest_data(index) |
| 114 | + while no_of_retries != 0: |
| 115 | + try: |
| 116 | + context_data = await ContextGroundingRetriever( |
| 117 | + index_name=state["index_name"], |
| 118 | + uipath_sdk=uipath, |
| 119 | + number_of_results=10 |
| 120 | + ).ainvoke(state["quiz_topic"]) |
| 121 | + data_queried = True |
| 122 | + break |
| 123 | + except IngestionInProgressException as ex: |
| 124 | + logger.info(ex.message) |
| 125 | + no_of_retries -= 1 |
| 126 | + logger.info(f"{no_of_retries} retries left") |
| 127 | + time.sleep(5) |
| 128 | + if not data_queried: |
| 129 | + raise Exception("Ingestion is taking too long.") |
| 130 | + message = system_message.format(format_instructions=output_parser.get_format_instructions(), |
| 131 | + context = context_data if context_data else "No context available yet", |
| 132 | + quiz_topic=state["quiz_topic"]) |
| 133 | + result = llm.invoke(message) |
| 134 | + try: |
| 135 | + llm_response = output_parser.parse(result.content) |
| 136 | + return Command( |
| 137 | + update={ |
| 138 | + "quiz": llm_response.quiz if llm_response.additional_info == "false" else None, |
| 139 | + "additional_info": llm_response.additional_info, |
| 140 | + } |
| 141 | + ) |
| 142 | + except Exception as e: |
| 143 | + print(f"Failed to parse {e}") |
| 144 | + return Command(goto=END) |
| 145 | + |
| 146 | +def check_quiz_creation(state: GraphState) -> Literal["invoke_researcher", "return_quiz"]: |
| 147 | + if state["additional_info"] != "false": |
| 148 | + return "invoke_researcher" |
| 149 | + return "return_quiz" |
| 150 | + |
| 151 | +def return_quiz(state: GraphState) -> GraphOutput: |
| 152 | + return GraphOutput(quiz=state["quiz"]) |
| 153 | + |
| 154 | +# Build the state graph |
| 155 | +builder = StateGraph(input=GraphInput, output=GraphOutput) |
| 156 | +builder.add_node("invoke_researcher", invoke_researcher) |
| 157 | +builder.add_node("create_quiz", create_quiz) |
| 158 | +builder.add_node("return_quiz", return_quiz) |
| 159 | +builder.add_node("prepare_input", prepare_input) |
| 160 | + |
| 161 | +builder.add_edge(START, "prepare_input") |
| 162 | +builder.add_edge("prepare_input", "create_quiz") |
| 163 | +builder.add_conditional_edges("create_quiz", check_quiz_creation) |
| 164 | +builder.add_edge("invoke_researcher", "create_quiz") |
| 165 | +builder.add_edge("return_quiz", END) |
| 166 | + |
| 167 | +# Compile the graph |
| 168 | +graph = builder.compile() |
0 commit comments