CananD commited on
Commit
0872fe3
·
verified ·
1 Parent(s): 3036fde

Upload app.py

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