File size: 4,198 Bytes
5c06db1
 
10ed581
5c06db1
d260382
5c06db1
cb249ff
78fe5ad
10ed581
85f2639
78fe5ad
5c06db1
78fe5ad
5c06db1
 
 
281c0ae
5c06db1
d260382
a741062
8724f47
d260382
 
a741062
5c06db1
85f2639
 
 
 
 
 
 
 
 
 
 
 
 
d260382
5c06db1
 
 
 
 
 
 
 
ea42e08
d260382
 
185ff32
 
 
 
014f4b5
185ff32
 
 
 
014f4b5
185ff32
 
014f4b5
d260382
 
014f4b5
186714c
 
 
 
d260382
5c06db1
 
186714c
 
bdc07c3
 
186714c
 
e644d16
8724f47
78fe5ad
 
 
 
bdc07c3
 
186714c
5c06db1
bdc07c3
8724f47
 
5c06db1
 
 
 
014f4b5
 
186714c
d260382
 
186714c
 
 
d260382
186714c
 
 
 
 
 
 
d260382
186714c
5c06db1
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import pandas as pd
import numpy as np
import os
import sys
import json
import pickle
import gradio as gr
import openai
from sentence_transformers import SentenceTransformer
from pinecone import Pinecone, ServerlessSpec

# تنظیم کلیدهای API
openai.api_key = os.getenv("openai")
api_key = os.getenv("PINECONE_API_KEY")
region = os.getenv("PINECONE_ENVIRONMENT", "us-west1-gcp")
index_name = os.getenv("PINECONE_INDEX_NAME", "tiyam-chat")

# بارگذاری مدل
model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')

# بارگذاری داده‌ها
with open("tiyam_qa_data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

# اتصال به Pinecone
pc = Pinecone(api_key=api_key)
existing_indexes = pc.list_indexes().names()
if index_name not in existing_indexes:
    pc.create_index(
        name=index_name,
        dimension=384,
        metric="cosine",
        spec=ServerlessSpec(
            cloud="aws",
            region=region
        )
    )
index = pc.Index(index_name)

# سیستم کش
cache_file = "chat_cache.pkl"
try:
    with open(cache_file, "rb") as f:
        cache = pickle.load(f)
except FileNotFoundError:
    cache = {}

def retrieve_answer(query, threshold=0.4, top_k=1):
    query_embedding = model.encode([query])[0]
    result = index.query(vector=query_embedding.tolist(), top_k=top_k, include_metadata=True)
    try:
        result_dict = result.to_dict()
    except Exception:
        result_dict = str(result)
    print("=== Pinecone query result ===")
    if isinstance(result_dict, dict):
        print(json.dumps(result_dict, indent=2, ensure_ascii=False))
    else:
        print(result_dict)
    print("============================")
    if hasattr(result, 'matches') and result.matches and len(result.matches) > 0 and result.matches[0].score > threshold:
        metadata = result.matches[0].metadata
        print("Matched answer:", metadata.get('answer'))
        return metadata.get('answer', 'پاسخ یافت نشد')
    else:
        print("No good match found.")
        return None

def generate_human_response(context_text):
    if not context_text:
        return "متأسفم، پاسخ دقیقی برای این سوال نداریم. لطفاً با ما تماس بگیرید."
    if context_text in cache:
        return cache[context_text]
    prompt = (
        f"این متن پاسخ سوال مشتری است: \"{context_text}\".\n"
        "لطفاً یک پاسخ کوتاه، رسمی و کاملاً مختصر به زبان فارسی تولید کن که فقط بر اساس همین متن باشد. "
        "پاسخ باید یک جمله‌ی کامل با یک فعل مناسب و پایان مشخص باشد. از تولید جمله‌های ناقص یا جمله‌هایی با بیش از یک فعل خودداری کن."
    )
    try:
        response = openai.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "شما یک پاسخگوی رسمی شرکت هستید."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.3,  # افزایش به 0.3 برای انعطاف‌پذیری بیشتر
            max_tokens=100,
        )
        answer = response.choices[0].message.content.strip()
        # فقط اطمینان از وجود نقطه در پایان
        if answer and not answer.endswith(('.', '!', '؟')):
            answer += '.'
        cache[context_text] = answer
        with open(cache_file, "wb") as f:
            pickle.dump(cache, f)
        return answer
    except Exception as e:
        print("OpenAI API error:", e)
        return "خطا در پردازش درخواست."

def chat_interface(question):
    answer = retrieve_answer(question)
    final_answer = generate_human_response(answer)
    return final_answer

demo = gr.Interface(
    fn=chat_interface,
    inputs="text",
    outputs="text",
    title="چت‌بات تیام",
    description="سؤالات خود را از آژانس دیجیتال مارکتینگ تیام بپرسید."
)

if __name__ == "__main__":
    demo.launch()