lanny xu commited on
Commit
7c05a1b
·
1 Parent(s): ee37277

delete urls

Browse files
Files changed (1) hide show
  1. KAGGLE_FIX_OLLAMA_CONNECTION.py +208 -0
KAGGLE_FIX_OLLAMA_CONNECTION.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Kaggle Ollama 连接问题诊断和修复脚本
4
+ 解决 GraphRAG 异步处理时的连接错误
5
+ """
6
+
7
+ import subprocess
8
+ import time
9
+ import requests
10
+ import os
11
+
12
+ def check_ollama_service():
13
+ """检查 Ollama 服务状态"""
14
+ print("="*70)
15
+ print("🔍 Ollama 服务诊断")
16
+ print("="*70)
17
+
18
+ # 1. 检查进程
19
+ print("\n1️⃣ 检查 Ollama 进程...")
20
+ ps_check = subprocess.run(['pgrep', '-f', 'ollama serve'], capture_output=True)
21
+
22
+ if ps_check.returncode == 0:
23
+ print(" ✅ Ollama 进程正在运行")
24
+ pids = ps_check.stdout.decode().strip().split('\n')
25
+ print(f" 📊 进程 PID: {', '.join(pids)}")
26
+ else:
27
+ print(" ❌ Ollama 进程未运行")
28
+ return False
29
+
30
+ # 2. 检查端口
31
+ print("\n2️⃣ 检查端口 11434...")
32
+ port_check = subprocess.run(
33
+ ['netstat', '-tuln'],
34
+ capture_output=True,
35
+ text=True
36
+ )
37
+
38
+ if '11434' in port_check.stdout:
39
+ print(" ✅ 端口 11434 已监听")
40
+ else:
41
+ print(" ❌ 端口 11434 未监听")
42
+ return False
43
+
44
+ # 3. 测试 API 连接
45
+ print("\n3️⃣ 测试 API 连接...")
46
+ try:
47
+ response = requests.get('http://localhost:11434/api/tags', timeout=5)
48
+ if response.status_code == 200:
49
+ print(" ✅ API 连接正常")
50
+ models = response.json().get('models', [])
51
+ print(f" 📦 可用模型: {len(models)}")
52
+ for model in models:
53
+ print(f" • {model.get('name', 'unknown')}")
54
+ return True
55
+ else:
56
+ print(f" ❌ API 返回错误: {response.status_code}")
57
+ return False
58
+ except Exception as e:
59
+ print(f" ❌ API 连接失败: {e}")
60
+ return False
61
+
62
+ def start_ollama_service():
63
+ """启动 Ollama 服务"""
64
+ print("\n"+"="*70)
65
+ print("🚀 启动 Ollama 服务")
66
+ print("="*70)
67
+
68
+ # 先杀死可能存在的僵尸进程
69
+ print("\n1️⃣ 清理旧进程...")
70
+ subprocess.run(['pkill', '-9', 'ollama'], capture_output=True)
71
+ time.sleep(2)
72
+
73
+ # 启动服务
74
+ print("\n2️⃣ 启动新服务...")
75
+ process = subprocess.Popen(
76
+ ['ollama', 'serve'],
77
+ stdout=subprocess.PIPE,
78
+ stderr=subprocess.PIPE,
79
+ env=os.environ.copy()
80
+ )
81
+
82
+ print(f" ✅ 服务进程已启动 (PID: {process.pid})")
83
+
84
+ # 等待服务就绪
85
+ print("\n3️⃣ 等待服务就绪...")
86
+ max_wait = 30
87
+ for i in range(max_wait):
88
+ try:
89
+ response = requests.get('http://localhost:11434/api/tags', timeout=2)
90
+ if response.status_code == 200:
91
+ print(f" ✅ 服务就绪!(耗时 {i+1} 秒)")
92
+ return True
93
+ except:
94
+ pass
95
+
96
+ if i < max_wait - 1:
97
+ print(f" ⏳ 等待中... ({i+1}/{max_wait})", end='\r')
98
+ time.sleep(1)
99
+
100
+ print(f"\n ⚠️ 服务启动超时,但可能仍在初始化中")
101
+ return False
102
+
103
+ def test_generation():
104
+ """测试生成功能"""
105
+ print("\n"+"="*70)
106
+ print("🧪 测试文本生成")
107
+ print("="*70)
108
+
109
+ try:
110
+ response = requests.post(
111
+ 'http://localhost:11434/api/generate',
112
+ json={
113
+ "model": "mistral",
114
+ "prompt": "Say 'Hello' in one word",
115
+ "stream": False
116
+ },
117
+ timeout=30
118
+ )
119
+
120
+ if response.status_code == 200:
121
+ result = response.json()
122
+ print(f" ✅ 生成成功")
123
+ print(f" 📝 响应: {result.get('response', '')[:100]}")
124
+ return True
125
+ else:
126
+ print(f" ❌ 生成失败: {response.status_code}")
127
+ return False
128
+ except Exception as e:
129
+ print(f" ❌ 生成错误: {e}")
130
+ return False
131
+
132
+ def main():
133
+ """主函数"""
134
+ print("\n" + "="*70)
135
+ print("🔧 Kaggle Ollama 连接问题修复工具")
136
+ print("="*70)
137
+ print("\n解决问题: Cannot connect to host localhost:11434")
138
+ print("场景: GraphRAG 异步批处理时")
139
+
140
+ # 检查服务
141
+ is_running = check_ollama_service()
142
+
143
+ if not is_running:
144
+ print("\n⚠️ Ollama 服务未正常运行,正在修复...")
145
+ start_ollama_service()
146
+
147
+ # 再次检查
148
+ print("\n"+"="*70)
149
+ print("🔍 验证修复结果")
150
+ print("="*70)
151
+ is_running = check_ollama_service()
152
+
153
+ # 测试生成
154
+ if is_running:
155
+ test_generation()
156
+
157
+ # 输出建议
158
+ print("\n"+"="*70)
159
+ print("💡 使用建议")
160
+ print("="*70)
161
+
162
+ if is_running:
163
+ print("""
164
+ ✅ Ollama 服务正常!现在可以运行 GraphRAG 了
165
+
166
+ 📝 在 Kaggle Notebook 中运行:
167
+
168
+ from document_processor import DocumentProcessor
169
+ from graph_indexer import GraphRAGIndexer
170
+
171
+ # 初始化
172
+ processor = DocumentProcessor()
173
+ vectorstore, retriever, doc_splits = processor.setup_knowledge_base(
174
+ enable_graphrag=True
175
+ )
176
+
177
+ # GraphRAG 索引(异步处理)
178
+ indexer = GraphRAGIndexer(
179
+ enable_async=True, # 启用异步
180
+ async_batch_size=8 # 并发处理 8 个文档
181
+ )
182
+
183
+ graph = indexer.index_documents(doc_splits)
184
+ """)
185
+ else:
186
+ print("""
187
+ ❌ Ollama 服务仍然异常
188
+
189
+ 🔧 手动修复步骤:
190
+
191
+ 1. 在 Kaggle Notebook 新单元格运行:
192
+ !pkill -9 ollama
193
+ !ollama serve &
194
+
195
+ 2. 等待 15 秒后,运行:
196
+ !curl http://localhost:11434/api/tags
197
+
198
+ 3. 如果成功,重新运行此脚本验证
199
+
200
+ 4. 如果失败,检查 Ollama 是否正确安装:
201
+ !which ollama
202
+ !ollama --version
203
+ """)
204
+
205
+ print("="*70)
206
+
207
+ if __name__ == "__main__":
208
+ main()