|
| 1 | +from langchain_ollama import OllamaEmbeddings, ChatOllama |
| 2 | +from langchain_chroma import Chroma |
| 3 | +from langchain_core.prompts import ChatPromptTemplate |
| 4 | +from langchain_core.runnables import RunnablePassthrough |
| 5 | +from langchain_core.output_parsers import StrOutputParser |
| 6 | + |
| 7 | +def format_docs(docs): |
| 8 | + return "\n\n".join(f"Sentence: {doc.page_content}\nIntent: {doc.metadata.get('intent', 'Unknown')}" for doc in docs) |
| 9 | + |
| 10 | +def detect_intent_with_context(sentence): |
| 11 | + messages = [] |
| 12 | + persist_directory = "db-intents" |
| 13 | + local_embeddings = OllamaEmbeddings(model="llama3.1:8b") |
| 14 | + |
| 15 | + vectorstore = Chroma(persist_directory=persist_directory, embedding_function=local_embeddings) |
| 16 | + |
| 17 | + docs = vectorstore.similarity_search(sentence) |
| 18 | + if not docs: |
| 19 | + messages.append("No relevant intent was found.") |
| 20 | + return {"response": "No matching intent found.", "messages": messages} |
| 21 | + |
| 22 | + # Define the RAG prompt template for intent detection |
| 23 | + INTENT_TEMPLATE = """ |
| 24 | + You are an assistant for detecting the intent of a sentence. Use the following pieces of retrieved context to determine the intent. If you cannot determine the intent, just say that you don't know. |
| 25 | +
|
| 26 | + <context> |
| 27 | + {context} |
| 28 | + </context> |
| 29 | +
|
| 30 | + What is the intent of the following sentence? Just reply with the intent name and nothing else as response. |
| 31 | +
|
| 32 | + {sentence}""" |
| 33 | + |
| 34 | + intent_prompt = ChatPromptTemplate.from_template(INTENT_TEMPLATE) |
| 35 | + model = ChatOllama(model="llama3.1:8b") |
| 36 | + |
| 37 | + chain = ( |
| 38 | + RunnablePassthrough.assign(context=lambda input: format_docs(input["context"])) |
| 39 | + | intent_prompt |
| 40 | + | model |
| 41 | + | StrOutputParser() |
| 42 | + ) |
| 43 | + |
| 44 | + response = chain.invoke({"context": docs, "sentence": sentence}) |
| 45 | + return {"response": response, "messages": messages} |
| 46 | + |
| 47 | +# Example usage |
| 48 | +test_sentence = "Where is it?" |
| 49 | +result = detect_intent_with_context(test_sentence) |
| 50 | +print(f"{result['response']}") |
| 51 | +for message in result["messages"]: |
| 52 | + print(message) |
0 commit comments