|
| 1 | +from typing import Optional |
| 2 | +from langgraph.graph import END, START, MessagesState, StateGraph |
| 3 | +from langgraph.types import Command, interrupt |
| 4 | +from pydantic import BaseModel, Field |
| 5 | +from uipath import UiPath |
| 6 | +from langchain_openai import AzureChatOpenAI |
| 7 | +from langchain_core.output_parsers import PydanticOutputParser |
| 8 | +import logging |
| 9 | +import os |
| 10 | +import time |
| 11 | +from uipath._models import InvokeProcess, IngestionInProgressException |
| 12 | +from langchain_core.messages import HumanMessage, SystemMessage |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | +llm = AzureChatOpenAI( |
| 17 | + azure_deployment="gpt-4o-mini", |
| 18 | + api_key=os.getenv("AZURE_OPENAI_API_KEY"), |
| 19 | + azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"), |
| 20 | + api_version="2024-10-21" |
| 21 | +) |
| 22 | + |
| 23 | +class Quiz(BaseModel): |
| 24 | + question: str = Field( |
| 25 | + description="One quiz question" |
| 26 | + ) |
| 27 | + difficulty: float = Field( |
| 28 | + description="How difficult is the question", ge=0.0, le=1.0 |
| 29 | + ) |
| 30 | + answer: str = Field( |
| 31 | + description="The expected answer to the question", |
| 32 | + ) |
| 33 | + |
| 34 | +output_parser = PydanticOutputParser(pydantic_object=Quiz) |
| 35 | + |
| 36 | +system_message ="""You are a quiz generator. Generate a quiz based on the user input. Your only context is the following one: |
| 37 | +
|
| 38 | +{context} |
| 39 | +
|
| 40 | +{format_instructions} |
| 41 | +
|
| 42 | +Respond with the classification in the requested JSON format.""" |
| 43 | + |
| 44 | +uipath = UiPath() |
| 45 | + |
| 46 | + |
| 47 | +class GraphOutput(BaseModel): |
| 48 | + quiz: Quiz |
| 49 | + |
| 50 | +class GraphInput(MessagesState): |
| 51 | + general_category: str |
| 52 | + quiz_topic: str |
| 53 | + bucket_name: str |
| 54 | + index_name: str |
| 55 | + bucket_folder: Optional[str] |
| 56 | + # create_bucket: Optional[bool] |
| 57 | + |
| 58 | +class GraphState(MessagesState): |
| 59 | + quiz_topic: str |
| 60 | + bucket_name: str |
| 61 | + bucket_folder: Optional[str] |
| 62 | + index_name: str |
| 63 | + |
| 64 | +# def decide_next_node(state: GraphState) -> Literal["get_context", "create_bucket"]: |
| 65 | +# if state.create_bucket: |
| 66 | +# return "create_bucket" |
| 67 | +# return "get_context" |
| 68 | +# |
| 69 | +# def create_bucket(state: GraphState) -> GraphState: |
| 70 | +# # to be implemented after sdk support for bucket creation is added |
| 71 | + |
| 72 | +async def invoke_researcher(state: GraphInput) -> Command: |
| 73 | + state["messages"].append(HumanMessage(f"Fetch data about {state['general_category']}")), |
| 74 | + input_args_json = { |
| 75 | + "messages": state["messages"], |
| 76 | + "bucket_name": state["bucket_name"], |
| 77 | + "bucket_folder": state.get("bucket_folder", None), |
| 78 | + } |
| 79 | + agent_response = interrupt(InvokeProcess( |
| 80 | + name = "researcher-and-uploader-agent", |
| 81 | + input_arguments = input_args_json, |
| 82 | + )) |
| 83 | + quiz_topic = state["quiz_topic"] |
| 84 | + return Command( |
| 85 | + update={ |
| 86 | + "messages": [agent_response["messages"][-1], ("user", f"create a quiz about {quiz_topic}")], |
| 87 | + }) |
| 88 | + |
| 89 | +async def create_quiz(state: GraphState) -> GraphOutput: |
| 90 | + # retriever = ContextGroundingRetriever( |
| 91 | + # index_name=state["index_name"], |
| 92 | + # uipath_sdk=uipath, |
| 93 | + # number_of_results=10 |
| 94 | + # ) |
| 95 | + # retriever._get_relevant_documents(state["quiz_topic"], run_manager = CallbackManagerForRetrieverRun()) |
| 96 | + no_of_retries = 5 |
| 97 | + context_data = None |
| 98 | + index = uipath.context_grounding.get_or_create_index(state["index_name"],storage_bucket_name=state["bucket_name"]) |
| 99 | + uipath.context_grounding.ingest_data(index) |
| 100 | + while no_of_retries != 0: |
| 101 | + try: |
| 102 | + context_data = uipath.context_grounding.search(state["index_name"], state["quiz_topic"], 10) |
| 103 | + break |
| 104 | + except IngestionInProgressException as ex: |
| 105 | + logger.info(ex.message) |
| 106 | + no_of_retries -= 1 |
| 107 | + logger.info(f"{no_of_retries} retries left") |
| 108 | + time.sleep(5) |
| 109 | + if not context_data: |
| 110 | + raise Exception("Ingestion is taking too long!") |
| 111 | + |
| 112 | + state["messages"].append(SystemMessage(system_message.format(format_instructions=output_parser.get_format_instructions(), |
| 113 | + context= context_data,))) |
| 114 | + result = llm.invoke(state["messages"]) |
| 115 | + return GraphOutput( quiz=output_parser.parse(result.content)) |
| 116 | + |
| 117 | + |
| 118 | +# Build the state graph |
| 119 | +builder = StateGraph(input=GraphInput, output=GraphOutput) |
| 120 | +builder.add_node("invoke_researcher", invoke_researcher) |
| 121 | +builder.add_node("create_quiz", create_quiz) |
| 122 | + |
| 123 | +builder.add_edge(START, "invoke_researcher") |
| 124 | +builder.add_edge("invoke_researcher", "create_quiz") |
| 125 | +builder.add_edge("create_quiz", END) |
| 126 | + |
| 127 | +# Compile the graph |
| 128 | +graph = builder.compile() |
0 commit comments