File size: 2,296 Bytes
0411280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d82613a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import os
import requests
from openai import AzureOpenAI
from dotenv import load_dotenv

load_dotenv()

# Config
AZURE_SEARCH_ENDPOINT = os.getenv("AZURE_SEARCH_ENDPOINT")
AZURE_SEARCH_KEY = os.getenv("AZURE_SEARCH_KEY")
AZURE_SEARCH_INDEX_NAME = "it-ticket-solutions-index"

HF_TOKEN = os.getenv("HF_TOKEN")
API_BASE_URL = os.getenv("API_BASE_URL")
MODEL_NAME = os.getenv("MODEL_NAME")
# Use the specific deployment name for embeddings from your .env
EMBEDDING_MODEL = os.getenv("AZURE_OPENAI_DEPLOYMENT") 
AZURE_OPENAI_API_VERSION = "2024-02-15-preview"

# Clients
openai_client = AzureOpenAI(
    api_key=HF_TOKEN,
    api_version=AZURE_OPENAI_API_VERSION,
    azure_endpoint=API_BASE_URL
)

def embed_text(text: str):
    # FIX: Changed model from MODEL_NAME to EMBEDDING_MODEL
    response = openai_client.embeddings.create(
        input=[text],
        model=EMBEDDING_MODEL
    )
    return response.data[0].embedding

def search_similar_solution(query: str, category: str) -> str:
    embedding = embed_text(query)

    url = f"{AZURE_SEARCH_ENDPOINT}/indexes/{AZURE_SEARCH_INDEX_NAME}/docs/search?api-version=2023-07-01-Preview"

    headers = {
        "Content-Type": "application/json",
        "api-key": AZURE_SEARCH_KEY
    }

    payload = {
        "search": "",
        "vectors": [
            {
                "value": embedding,
                "fields": "embedding",
                "k": 3
            }
        ],
        "select": "category,problem,solution",
        "filter": f"category eq '{category}'"
    }

    response = requests.post(url, headers=headers, json=payload)
    if response.status_code != 200:
        return f"Error while searching: {response.text}"

    results = response.json().get("value", [])

    if not results:
        return "No matching solutions found."

    response_text = ""
    for idx, doc in enumerate(results, 1):
        response_text += (
            f"\nResult {idx}:\n"
            f"Category: {doc.get('category')}\n"
            f"Problem: {doc.get('problem')}\n"
            f"Solution: {doc.get('solution')}\n"
        )

    return response_text

if __name__ == "__main__":
    query = "My Outlook crashes every time I open it"
    rag_output = search_similar_solution(query, category="Software Bug")
    print(rag_output)