|
| 1 | +import logging |
| 2 | +from typing import Any, Dict |
| 3 | +from sqlalchemy.orm import Session |
| 4 | +from database import db_session |
| 5 | +import contextlib |
| 6 | +import io |
| 7 | + |
| 8 | +from fastapi import APIRouter, HTTPException, Depends |
| 9 | + |
| 10 | +from langflow.interface.run import load_langchain_object, save_cache, fix_memory_inputs |
| 11 | + |
| 12 | +from database_utils.chatbot import get_chatbot |
| 13 | +from schemas.prompt_schema import PromptSchema |
| 14 | + |
| 15 | +# build router |
| 16 | +router = APIRouter(tags=["prompts"]) |
| 17 | +# add docs to router |
| 18 | +router.__doc__ = """ |
| 19 | +# Prompts API |
| 20 | +""" |
| 21 | + |
| 22 | +logger = logging.getLogger(__name__) |
| 23 | + |
| 24 | + |
| 25 | +def format_intermediate_steps(intermediate_steps): |
| 26 | + formatted_chain = [] |
| 27 | + for step in intermediate_steps: |
| 28 | + action = step[0] |
| 29 | + observation = step[1] |
| 30 | + |
| 31 | + formatted_chain.append( |
| 32 | + { |
| 33 | + "action": action.tool, |
| 34 | + "action_input": action.tool_input, |
| 35 | + "observation": observation, |
| 36 | + } |
| 37 | + ) |
| 38 | + return formatted_chain |
| 39 | + |
| 40 | + |
| 41 | +def get_result_and_thought_using_graph(langchain_object, message: str): |
| 42 | + """Get result and thought from extracted json""" |
| 43 | + try: |
| 44 | + if hasattr(langchain_object, "verbose"): |
| 45 | + langchain_object.verbose = True |
| 46 | + chat_input = None |
| 47 | + memory_key = "" |
| 48 | + if hasattr(langchain_object, "memory") and langchain_object.memory is not None: |
| 49 | + memory_key = langchain_object.memory.memory_key |
| 50 | + |
| 51 | + for key in langchain_object.input_keys: |
| 52 | + if key not in [memory_key, "chat_history"]: |
| 53 | + chat_input = {key: message} |
| 54 | + |
| 55 | + if hasattr(langchain_object, "return_intermediate_steps"): |
| 56 | + # https://github.com/hwchase17/langchain/issues/2068 |
| 57 | + # Deactivating until we have a frontend solution |
| 58 | + # to display intermediate steps |
| 59 | + langchain_object.return_intermediate_steps = True |
| 60 | + |
| 61 | + fix_memory_inputs(langchain_object) |
| 62 | + |
| 63 | + with io.StringIO() as output_buffer, contextlib.redirect_stdout(output_buffer): |
| 64 | + try: |
| 65 | + output = langchain_object(chat_input) |
| 66 | + except ValueError as exc: |
| 67 | + # make the error message more informative |
| 68 | + logger.debug(f"Error: {str(exc)}") |
| 69 | + output = langchain_object.run(chat_input) |
| 70 | + |
| 71 | + intermediate_steps = output.get("intermediate_steps", []) if isinstance(output, dict) else [] |
| 72 | + |
| 73 | + result = output.get(langchain_object.output_keys[0]) if isinstance(output, dict) else output |
| 74 | + if intermediate_steps: |
| 75 | + thought = format_intermediate_steps(intermediate_steps) |
| 76 | + else: |
| 77 | + thought = {"steps": output_buffer.getvalue()} |
| 78 | + |
| 79 | + except Exception as exc: |
| 80 | + raise ValueError(f"Error: {str(exc)}") from exc |
| 81 | + return result, thought |
| 82 | + |
| 83 | + |
| 84 | +def process_graph(message, chat_history, data_graph): |
| 85 | + """ |
| 86 | + Process graph by extracting input variables and replacing ZeroShotPrompt |
| 87 | + with PromptTemplate,then run the graph and return the result and thought. |
| 88 | + """ |
| 89 | + # Load langchain object |
| 90 | + logger.debug("Loading langchain object") |
| 91 | + is_first_message = len(chat_history) == 0 |
| 92 | + computed_hash, langchain_object = load_langchain_object(data_graph, is_first_message) |
| 93 | + logger.debug("Loaded langchain object") |
| 94 | + |
| 95 | + if langchain_object is None: |
| 96 | + # Raise user facing error |
| 97 | + raise ValueError("There was an error loading the langchain_object. Please, check all the nodes and try again.") |
| 98 | + |
| 99 | + # Generate result and thought |
| 100 | + logger.debug("Generating result and thought") |
| 101 | + result, thought = get_result_and_thought_using_graph(langchain_object, message) |
| 102 | + logger.debug("Generated result and thought") |
| 103 | + |
| 104 | + # Save langchain_object to cache |
| 105 | + # We have to save it here because if the |
| 106 | + # memory is updated we need to keep the new values |
| 107 | + logger.debug("Saving langchain object to cache") |
| 108 | + save_cache(computed_hash, langchain_object, is_first_message) |
| 109 | + logger.debug("Saved langchain object to cache") |
| 110 | + return {"result": str(result), "thought": thought} |
| 111 | + |
| 112 | + |
| 113 | +@router.post("/chatbot/{chatbot_id}/prompt") |
| 114 | +def get_prompt(chatbot_id: int, prompt: PromptSchema, db: Session = Depends(db_session)): |
| 115 | + try: |
| 116 | + chatbot = get_chatbot(db, chatbot_id) |
| 117 | + |
| 118 | + # Process graph |
| 119 | + logger.debug("Processing graph") |
| 120 | + result = process_graph(prompt.new_message, prompt.chat_history, chatbot.dag) |
| 121 | + |
| 122 | + logger.debug("Processed graph") |
| 123 | + return result |
| 124 | + |
| 125 | + except Exception as e: |
| 126 | + logger.exception(e) |
| 127 | + raise HTTPException(status_code=500, detail=str(e)) from e |
0 commit comments