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
+
import streamlit as st
|
| 2 |
+
import openai
|
| 3 |
+
import re
|
| 4 |
+
from duckduckgo_search import DDGS
|
| 5 |
+
|
| 6 |
+
# --- Araçların Tanımlanması ---
|
| 7 |
+
|
| 8 |
+
def search_tool(query: str):
|
| 9 |
+
"""A web search tool that uses DuckDuckGo to find information."""
|
| 10 |
+
st.write(f"🔎 Web'de aranıyor: `{query}`")
|
| 11 |
+
try:
|
| 12 |
+
with DDGS() as ddgs:
|
| 13 |
+
results = [r for r in ddgs.text(query, max_results=5)]
|
| 14 |
+
return "\n".join(results) if results else "Aramada sonuç bulunamadı."
|
| 15 |
+
except Exception as e:
|
| 16 |
+
return f"Arama sırasında bir hata oluştu: {e}"
|
| 17 |
+
|
| 18 |
+
def calculator_tool(expression: str):
|
| 19 |
+
"""A calculator tool that evaluates a mathematical expression."""
|
| 20 |
+
st.write(f"🧮 Hesaplama yapılıyor: `{expression}`")
|
| 21 |
+
try:
|
| 22 |
+
# Güvenlik için sadece güvenli karakterlere izin ver
|
| 23 |
+
if not re.match(r"^[0-9+\-*/.() \t]+$", expression):
|
| 24 |
+
return "Geçersiz karakterler içerdiği için hesaplama yapılamadı."
|
| 25 |
+
result = eval(expression)
|
| 26 |
+
return f"Sonuç: {result}"
|
| 27 |
+
except Exception as e:
|
| 28 |
+
return f"Hesaplama hatası: {e}"
|
| 29 |
+
|
| 30 |
+
# --- LLM (Büyük Dil Modeli) İstek Fonksiyonu ---
|
| 31 |
+
|
| 32 |
+
def call_llm(prompt, api_key):
|
| 33 |
+
"""Calls the OpenAI API to get the agent's next thought and action."""
|
| 34 |
+
openai.api_key = api_key
|
| 35 |
+
try:
|
| 36 |
+
response = openai.chat.completions.create(
|
| 37 |
+
model="gpt-4o", # veya "gpt-3.5-turbo"
|
| 38 |
+
messages=[{"role": "user", "content": prompt}],
|
| 39 |
+
temperature=0.0,
|
| 40 |
+
max_tokens=500,
|
| 41 |
+
)
|
| 42 |
+
return response.choices[0].message.content
|
| 43 |
+
except Exception as e:
|
| 44 |
+
st.error(f"OpenAI API çağrısı sırasında hata: {e}")
|
| 45 |
+
return None
|
| 46 |
+
|
| 47 |
+
# --- Ana Ajan Döngüsü ---
|
| 48 |
+
|
| 49 |
+
def run_agent_loop(goal, api_key):
|
| 50 |
+
"""Runs the main ReAct (Reason-Act) agent loop."""
|
| 51 |
+
|
| 52 |
+
# Ajanın nasıl çalışacağını açıklayan ana prompt (talimat)
|
| 53 |
+
system_prompt_template = f"""
|
| 54 |
+
Sen, bir amaca ulaşmak için adım adım düşünen ve araçları kullanan bir AI ajanısın.
|
| 55 |
+
Her adımda, amacına yönelik bir 'Düşünce' ve bu düşünceyi hayata geçirecek bir 'Eylem' üretmelisin.
|
| 56 |
+
|
| 57 |
+
Kullanabileceğin araçlar şunlardır:
|
| 58 |
+
1. `search(sorgu)`: İnternette arama yapmak için kullanılır. Örneğin: `search(Türkiye'nin başkenti)`
|
| 59 |
+
2. `calculator(ifade)`: Matematiksel bir ifadeyi hesaplamak için kullanılır. Örneğin: `calculator(100 * (3 + 5))`
|
| 60 |
+
3. `finish(cevap)`: Görevi tamamladığında ve nihai cevabı bulduğunda kullanılır. Örneğin: `finish(Ankara, Türkiye'nin başkentidir.)`
|
| 61 |
+
|
| 62 |
+
Süreç şu şekilde işler:
|
| 63 |
+
1. Amacı analiz edersin.
|
| 64 |
+
2. Bir 'Düşünce' oluşturursun.
|
| 65 |
+
3. Bir 'Eylem' seçersin.
|
| 66 |
+
4. Ben sana 'Gözlem' olarak eylemin sonucunu veririm.
|
| 67 |
+
5. Amaca ulaşana kadar 2-4 adımlarını tekrarlarsın.
|
| 68 |
+
|
| 69 |
+
Amacımız: "{goal}"
|
| 70 |
+
|
| 71 |
+
Şimdi, ilk Düşünce ve Eylemini yaz.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
history = [system_prompt_template]
|
| 75 |
+
max_steps = 10
|
| 76 |
+
|
| 77 |
+
for step in range(max_steps):
|
| 78 |
+
st.write("---")
|
| 79 |
+
st.info(f"🚀 Adım {step + 1}")
|
| 80 |
+
|
| 81 |
+
prompt = "\n".join(history)
|
| 82 |
+
|
| 83 |
+
with st.spinner("Ajan düşünüyor..."):
|
| 84 |
+
response = call_llm(prompt, api_key)
|
| 85 |
+
|
| 86 |
+
if not response:
|
| 87 |
+
st.error("Ajan bir yanıt üretemedi. Lütfen API anahtarınızı kontrol edin veya tekrar deneyin.")
|
| 88 |
+
break
|
| 89 |
+
|
| 90 |
+
# LLM'in ürettiği Düşünce ve Eylemi ayıkla
|
| 91 |
+
try:
|
| 92 |
+
thought = re.search(r"Düşünce: (.*?)\n", response, re.DOTALL).group(1).strip()
|
| 93 |
+
action_full = re.search(r"Eylem: (.*?)$", response, re.DOTALL).group(1).strip()
|
| 94 |
+
except AttributeError as e:
|
| 95 |
+
st.error("Ajan geçerli bir 'Düşünce' veya 'Eylem' formatı üretmedi.")
|
| 96 |
+
st.write(response) # Hata mesajı ve yanıtı tam olarak görmek için
|
| 97 |
+
break
|
| 98 |
+
|
| 99 |
+
with st.expander("🤖 Ajanın Düşünce Süreci", expanded=True):
|
| 100 |
+
st.markdown(f"**Düşünce:** {thought}")
|
| 101 |
+
st.markdown(f"**Eylem:** `{action_full}`")
|
| 102 |
+
|
| 103 |
+
# Eylemi formatına göre ayıklama
|
| 104 |
+
action_name_match = re.match(r"(\w+)\((.*)\)", action_full)
|
| 105 |
+
if not action_name_match:
|
| 106 |
+
st.error(f"Geçersiz eylem formatı: {action_full}")
|
| 107 |
+
break
|
| 108 |
+
|
| 109 |
+
action_name = action_name_match.group(1)
|
| 110 |
+
action_input = action_name_match.group(2).strip(' "')
|
| 111 |
+
|
| 112 |
+
# Eylemi gerçekleştir ve gözlemi al
|
| 113 |
+
observation = ""
|
| 114 |
+
if action_name == "search":
|
| 115 |
+
observation = search_tool(action_input)
|
| 116 |
+
elif action_name == "calculator":
|
| 117 |
+
observation = calculator_tool(action_input)
|
| 118 |
+
elif action_name == "finish":
|
| 119 |
+
st.success(f"✅ Ajan görevi tamamladı!")
|
| 120 |
+
st.balloons()
|
| 121 |
+
st.markdown("### Nihai Cevap:")
|
| 122 |
+
st.write(action_input)
|
| 123 |
+
break
|
| 124 |
+
else:
|
| 125 |
+
observation = f"Bilinmeyen eylem: {action_name}. Lütfen `search`, `calculator` veya `finish` kullanın."
|
| 126 |
+
|
| 127 |
+
st.warning(f"**Gözlem:**\n{observation}")
|
| 128 |
+
|
| 129 |
+
# Geçmişi güncelle
|
| 130 |
+
history.append(response)
|
| 131 |
+
history.append(f"Gözlem: {observation}")
|
| 132 |
+
else:
|
| 133 |
+
st.error("Ajan maksimum adım sayısına ulaştı ama görevi tamamlayamadı.")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# --- Streamlit Arayüzü ---
|
| 137 |
+
|
| 138 |
+
st.set_page_config(page_title="AI Agentic App", page_icon="🤖")
|
| 139 |
+
|
| 140 |
+
st.title("🤖 AI Agentic Uygulaması")
|
| 141 |
+
st.markdown("""
|
| 142 |
+
Bu uygulama, bir amaca ulaşmak için **ReAct (Reason + Act)** mantığıyla çalışan bir AI ajanıdır.
|
| 143 |
+
Ajan, hedefe ulaşmak için **düşünür**, **araçlar kullanır** (web araması, hesap makinesi) ve sonuçları **gözlemler**.
|
| 144 |
+
""")
|
| 145 |
+
|
| 146 |
+
st.sidebar.header("Yapılandırma")
|
| 147 |
+
api_key = st.sidebar.text_input("OpenAI API Anahtarınız", type="password", help="API anahtarınız asla saklanmaz.")
|
| 148 |
+
|
| 149 |
+
st.header("Ajanın Amacını Belirleyin")
|
| 150 |
+
goal = st.text_input(
|
| 151 |
+
"Amaç:",
|
| 152 |
+
placeholder="Örnek: 'Matrix filminin başrol oyuncusunun bugünkü yaşı kaçtır ve bu yaşın karekökü nedir?'"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
if st.button("Ajanı Başlat", disabled=(not api_key or not goal)):
|
| 156 |
+
if api_key and goal:
|
| 157 |
+
run_agent_loop(goal, api_key)
|
| 158 |
+
else:
|
| 159 |
+
st.warning("Lütfen OpenAI API anahtarınızı ve bir amaç girin.")
|