Update app.py
Browse files63 unmodified lines6465666768697079 unmodified lines15015115215363 unmodified linesif __name__ == "__main__":demo.launch()'''import gradio as grfrom langchain.chains import LLMChain79 unmodified lines# Launch the Gradio applicationdemo.launch()63 unmodified lines6465666768697079 unmodified lines15015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233363 unmodified linesif __name__ == "__main__":demo.launch()import gradio as grfrom langchain.chains import LLMChain79 unmodified lines# Launch the Gradio applicationdemo.launch()'''from typing import Annotated, Sequence, TypedDictimport operatorimport functoolsfrom langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholderfrom langchain_core.messages import BaseMessage, HumanMessage, SystemMessagefrom langchain_community.tools.tavily_search import TavilySearchResultsfrom langchain_experimental.tools import PythonREPLToolfrom langchain.agents import create_openai_tools_agentfrom langchain_huggingface import HuggingFacePipelinefrom langgraph.graph import StateGraph, ENDfrom transformers import AutoTokenizer, AutoModelForCausalLM, pipeline# SETUP: HuggingFace Model and Pipeline#name = "meta-llama/Llama-3.2-1B"#name="deepseek-ai/DeepSeek-R1-Distill-Qwen-32B"#name="deepseek-ai/deepseek-llm-7b-chat"#name="openai-community/gpt2"#name="deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"#name="microsoft/Phi-3.5-mini-instruct"name="Qwen/Qwen2.5-7B-Instruct-1M"tokenizer = AutoTokenizer.from_pretrained(name,truncation=True)tokenizer.pad_token = tokenizer.eos_tokenmodel = AutoModelForCausalLM.from_pretrained(name)pipe = pipeline("text-generation",model=model,tokenizer=tokenizer,device_map="auto",max_new_tokens=500, # text to generate for outputs)print ("pipeline is created")# Wrap in LangChain's HuggingFacePipelinellm = HuggingFacePipeline(pipeline=pipe)# Members and Final Optionsmembers = ["Researcher", "Coder"]options = ["FINISH"] + members# Supervisor promptsystem_prompt = ("You are a supervisor tasked with managing a conversation between the following workers: {members}."" Given the following user request, respond with the workers to act next. Each worker will perform a task"" and respond with their results and status. When all workers are finished, respond with FINISH.")# Prompt template required for the workflowprompt = ChatPromptTemplate.from_messages([("system", system_prompt),MessagesPlaceholder(variable_name="messages"),("system", "Given the conversation above, who should act next? Or Should we FINISH? Select one of: {options}"),]).partial(options=str(options), members=", ".join(members))print ("Prompt Template created")# Supervisor routing logicdef route_tool_response(llm_response):"""Parse the LLM response to determine the next step based on routing logic."""if "FINISH" in llm_response:return "FINISH"for member in members:if member in llm_response:return memberreturn "Unknown"def supervisor_chain(state):"""Supervisor logic to interact with HuggingFacePipeline and decide the next worker."""messages = state.get("messages", [])print(f"[TRACE] Supervisor received messages: {messages}") # Trace input messagesuser_prompt = prompt.format(messages=messages)try:llm_response = pipe(user_prompt, max_new_tokens=500)[0]["generated_text"]print(f"[TRACE] LLM Response: {llm_response}") # Trace LLM interactionexcept Exception as e:raise RuntimeError(f"LLM processing error: {e}")next_action = route_tool_response(llm_response)print(f"[TRACE] Supervisor deciding next action: {next_action}") # Trace state changesreturn {"next": next_action}# AgentState definitionclass AgentState(TypedDict):messages: Annotated[Sequence[BaseMessage], operator.add]next: str# Create toolstavily_tool = TavilySearchResults(max_results=5)python_repl_tool = PythonREPLTool()# Create agents with their respective promptsresearch_agent = create_openai_tools_agent(llm=llm,tools=[tavily_tool],prompt=ChatPromptTemplate.from_messages([SystemMessage(content="You are a web researcher."),MessagesPlaceholder(variable_name="messages"),MessagesPlaceholder(variable_name="agent_scratchpad"), # Add required placeholder]),)print ("Created agents with their respective prompts")code_agent = create_openai_tools_agent(llm=llm,tools=[python_repl_tool],prompt=ChatPromptTemplate.from_messages([SystemMessage(content="You may generate safe Python code for analysis."),MessagesPlaceholder(variable_name="messages"),MessagesPlaceholder(variable_name="agent_scratchpad"), # Add required placeholder]),)print ("create_openai_tools_agent")# Create the workflowworkflow = StateGraph(AgentState)# Nodesworkflow.add_node("Researcher", research_agent) # Pass the agent directly (no .run required)workflow.add_node("Coder", code_agent) # Pass the agent directlyworkflow.add_node("supervisor", supervisor_chain)# Add edges for workflow transitionsfor member in members:workflow.add_edge(member, "supervisor")workflow.add_conditional_edges("supervisor",lambda x: x["next"],{k: k for k in members} | {"FINISH": END} # Dynamically map workers to their actions)print("[DEBUG] Workflow edges added: supervisor -> members/FINISH based on 'next'")# Define entry pointworkflow.set_entry_point("supervisor")print(workflow)# Compile the workflowgraph = workflow.compile()from IPython.display import display, Imagedisplay(Image(graph.get_graph().draw_mermaid_png()))# Properly formatted initial stateinitial_state = {"messages": [#HumanMessage(content="Code hello world and print it to the terminal.") # Correct format for user inputHumanMessage(content="Write Code for printing \"hello world\" in Python. Keep it precise.") # Correct format for user input]}# Execute the workflowtry:print(f"[TRACE] Initial workflow state: {initial_state}")result = graph.invoke(initial_state)print(f"[TRACE] Workflow Result: {result}") # Final workflow resultexcept Exception as e:print(f"[ERROR] Workflow execution failed: {e}")
app.py+181-1