Skip to content

Commit 80ad1c5

Browse files
committed
added intent detection code
1 parent 0d96634 commit 80ad1c5

File tree

5 files changed

+101
-2
lines changed

5 files changed

+101
-2
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
.venv/*
22
__pycache__
33
db/*
4+
db-intents/*

data/intent.csv

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
sentence,intent
2+
where is my order, order_status
3+
i want to check my order status, order_status

detect.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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)

intent.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import csv
2+
from langchain_text_splitters import RecursiveCharacterTextSplitter
3+
from langchain_ollama import OllamaEmbeddings
4+
from langchain_chroma import Chroma
5+
from langchain.schema import Document
6+
import os
7+
8+
def ingest_csv_to_chroma(csv_path):
9+
messages = []
10+
local_embeddings = OllamaEmbeddings(model="llama3.1:8b")
11+
persist_directory = "db-intents"
12+
13+
if os.path.exists(persist_directory):
14+
vectorstore = Chroma(persist_directory=persist_directory, embedding_function=local_embeddings)
15+
messages.append("Loaded the existing Chroma DB")
16+
else:
17+
vectorstore = Chroma(persist_directory=persist_directory, embedding_function=local_embeddings)
18+
messages.append("Created the Chroma DB")
19+
20+
# Load data from CSV
21+
documents = []
22+
with open(csv_path, 'r') as csv_file:
23+
reader = csv.DictReader(csv_file)
24+
for row in reader:
25+
sentence = row['sentence']
26+
intent = row['intent']
27+
# Create a Document object with metadata for intent data
28+
doc = Document(page_content=sentence, metadata={"intent": intent, "type": "intent_data"})
29+
documents.append(doc)
30+
31+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)
32+
all_splits = text_splitter.split_documents(documents)
33+
34+
vectorstore.add_documents(documents=all_splits)
35+
messages.append("Added intent data to Chroma DB")
36+
37+
return messages
38+
39+
# Example usage
40+
csv_path = "data/intent.csv"
41+
42+
# Ingest CSV data
43+
csv_messages = ingest_csv_to_chroma(csv_path)
44+
for message in csv_messages:
45+
print(message)

scrape.py

-2
Original file line numberDiff line numberDiff line change
@@ -27,5 +27,3 @@ def fetch_and_persist_article(url):
2727
messages.append(f"Added to Chroma DB")
2828

2929
return messages
30-
31-

0 commit comments

Comments
 (0)