"""
if link:
content = f'{content}'
st.markdown(content, unsafe_allow_html=True)
if idx in [1, 3, 5]:
st.markdown("", unsafe_allow_html=True)
# Header
st.markdown("""
رزمیار ارتش
دستیارهوشمند ارتش جمهوری اسلامی ایران
""", unsafe_allow_html=True)
# Initialize LangChain LLM with Apifree
llm = init_chat_model(
"gpt-5-mini",
base_url="https://api.apifree.ai/gpt-5-mini",
api_key="sk-p6nSSQGZ3174esjkw7YcFpcXj6XNp",
max_tokens=4096,
temperature=0.7,
)
EMBEDDING_FILE = "embeddings.json"
@st.cache_data
def load_embeddings(file_path):
with open(file_path, "r", encoding="utf-8") as f:
return json.load(f)
def get_query_embedding_apifree(query: str):
url = "https://api.apifree.ai/"
headers = {
"Authorization": "Bearer sk-p6nSSQGZ3174esjkw7YcFpcXj6XNp",
"Content-Type": "application/json"
}
payload = {
"model": "gpt-5-mini",
"input": query
}
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
return response.json()["data"][0]["embedding"]
def find_most_similar_chunks(query_embedding, data, top_n=20):
query_vec = np.array(query_embedding).reshape(1, -1)
similarities = []
for item in data:
chunk_vec = np.array(item["embedding"]).reshape(1, -1)
sim = cosine_similarity(query_vec, chunk_vec)[0][0]
similarities.append((item["chunk"], sim))
similarities.sort(key=lambda x: x[1], reverse=True)
return [chunk for chunk, _ in similarities[:top_n]]
def clean_text(text):
import re
return re.sub(r'[^آ-یa-zA-Z0-9۰-۹,.،؟!؛\s]+', '', text)
query = st.chat_input("چطور میتونم کمک کنم؟")
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if query:
thinking = st.empty()
thinking.markdown("⏳ در حال پردازش...")
try:
query_embedding = get_query_embedding_apifree(query)
data = load_embeddings(EMBEDDING_FILE)
top_chunks = find_most_similar_chunks(query_embedding, data, top_n=20)
context = "\n".join(top_chunks)
prompt = f"""
به سؤال زیر فقط بر اساس اطلاعات موجود در خطوط مرتبط پاسخ بده
از تحلیل، مقدمهچینی، توضیح مراحل تفکر، یا حدس شخصی خودداری کن
اگر اطلاعات کافی برای پاسخ دقیق در خطوط مرتبط وجود نداشت، فقط در آن صورت
میتوانی از دانش عمومی خود استفاده کنی تا یک پاسخ حرفهای و دقیق ارائه دهی
پاسخ باید نهایی، روان، و در حدود 256 تا 1024 کاراکتر باشد اگر در دیتا موجود نبود نزدیک ترین پاسخ به متن
سوال:
{query}
خطوط مرتبط:
{top_chunks}
پاسخ نهایی:
"""
response = llm.invoke([
SystemMessage(
content=" تو یک دستیار دقیق هستی که فقط با اطلاعات موجود در متن پاسخ میدهی و اگر در متن موجود نبود از شبیه ترین پاسخ به دیتای متن "
),
HumanMessage(content=prompt)
])
final_answer = clean_text(response.content.strip())
except Exception as e:
final_answer = f"❗ خطا: {str(e)}"
thinking.empty()
st.session_state.chat_history.append(("🧑", query))
st.session_state.chat_history.append(("🤖", final_answer))
st.markdown("""
""", unsafe_allow_html=True)
st.markdown("---")
for sender, message in st.session_state.chat_history:
st.markdown(f'