File size: 9,976 Bytes
9540270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7320560
 
 
9540270
 
 
 
 
 
7320560
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9540270
 
 
 
 
 
 
 
 
 
7320560
 
9540270
 
7320560
 
9540270
7320560
 
 
 
 
 
 
 
 
9540270
 
 
 
 
 
 
 
 
 
 
 
7320560
 
 
 
9540270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d68d941
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9540270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d68d941
9540270
 
 
 
 
d68d941
9540270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7320560
9540270
7320560
9540270
 
 
 
 
 
 
 
 
 
 
 
 
7320560
 
 
 
9540270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7320560
 
 
 
 
 
9540270
7320560
9540270
 
 
 
 
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import json
import os
import random
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

import gymnasium as gym
import numpy as np
from gymnasium import spaces


BASE_DIR = Path(__file__).parent
ROOT_DIR = BASE_DIR / "root"
QA_PAIRS_PATH = BASE_DIR / "qa_pairs.json"

with open(QA_PAIRS_PATH) as f:
    QA_PAIRS = json.load(f)

ACTIONS = {0: "ls", 1: "cd", 2: "read", 3: "submit_answer"}

OLLAMA_BASE_URL = os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434")
OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "qwen3.5")


def load_text_file(path: Path) -> str:
    with open(path) as f:
        return f.read()


def call_ollama(prompt: str, system: str = "") -> str:
    try:
        import requests
        response = requests.post(
            f"{OLLAMA_BASE_URL}/api/generate",
            json={
                "model": OLLAMA_MODEL,
                "prompt": prompt,
                "system": system,
                "stream": False,
            },
            timeout=30,
        )
        if response.status_code == 200:
            return response.json().get("response", "")
        return ""
    except Exception as e:
        print(f"Ollama error: {e}")
        return ""


def call_policy_model(observation: Dict[str, Any], qa_pairs: List[Dict]) -> int:
    prompt = f"""You are an AI agent navigating a file system to answer technical questions.

Current state:
- Current path: {observation['current_path']}
- Directory contents: {observation['dir_contents']}
- User query: {observation['user_query']}

Available actions:
- 0: ls (list directory contents)
- 1: cd <target> (change directory to a subdirectory)
- 2: read <file> (read a file to find the answer)
- 3: submit_answer <text> (submit your final answer)

Based on the user query and current state, pick the best action (0, 1, 2, or 3).
Think step by step, then respond with just the action number: """

    system_prompt = "You are a helpful AI that chooses actions to navigate a file system. Respond with only the action number (0, 1, 2, or 3)."
    
    response = call_ollama(prompt, system_prompt)
    
    try:
        action = int(response.strip()[0])
        return action if 0 <= action <= 3 else random.randint(0, 3)
    except (ValueError, IndexError):
        return random.randint(0, 3)


def call_tool_model(file_content: str, user_query: str) -> str:
    prompt = f"""Given the following file content and user query, provide the answer.

File content:
{file_content}

User query: {user_query}

If the answer is found in the file content, return it. Otherwise, return "Not Found"."""

    system_prompt = "You are a helpful AI that extracts answers from documentation. If the answer is found in the file content, return it exactly. If not found, return exactly 'Not Found'."
    
    response = call_ollama(prompt, system_prompt)
    return response if response else "Not Found"


class DocParserEnv(gym.Env):
    metadata = {"render_modes": ["human"]}

    def __init__(self, max_steps: int = 20):
        super().__init__()
        self.max_steps = max_steps
        self.current_path = ROOT_DIR
        self.user_query = ""
        self.ground_truth_answer = ""
        self.ground_truth_file = ""
        self.step_count = 0
        self.last_action = None
        self.last_action_result = ""
        self.done = False
        self.target_dir = ""

        self.observation_space = spaces.Dict({
            "current_path": spaces.Text(max_length=512),
            "dir_contents": spaces.Text(max_length=2048),
            "user_query": spaces.Text(max_length=512),
        })
        self.action_space = spaces.Discrete(4)

    def _get_obs(self) -> Dict[str, Any]:
        try:
            contents = list(self.current_path.iterdir())
            dir_names = [c.name for c in contents]
        except Exception:
            dir_names = []
        
        return {
            "current_path": str(self.current_path),
            "dir_contents": ", ".join(dir_names) if dir_names else "empty",
            "user_query": self.user_query,
        }

    def _get_info(self) -> Dict[str, Any]:
        return {
            "step_count": self.step_count,
            "last_action": self.last_action,
            "last_action_result": self.last_action_result,
            "ground_truth": self.ground_truth_answer,
        }

    def reset(self, seed: Optional[int] = None, options: Optional[Dict] = None) -> Tuple[Dict, Dict]:
        super().reset(seed=seed)

        task_id = None
        if options and isinstance(options, dict):
            task_id = options.get("task_id")

        # Deterministic task selection for validator tasks 1..3.
        task_map = {
            1: 0,  # SSL config
            2: 1,  # Postgres port
            3: 2,  # OAuth2 auth steps
        }

        if isinstance(task_id, int) and task_id in task_map:
            qa_pair = QA_PAIRS[task_map[task_id]]
        else:
            qa_pair = random.choice(QA_PAIRS)
        self.user_query = qa_pair["query"]
        self.ground_truth_answer = qa_pair["answer"]
        self.ground_truth_file = qa_pair["file_path"]
        
        self.current_path = ROOT_DIR
        self.step_count = 0
        self.done = False
        self.last_action = None
        self.last_action_result = ""
        self.target_dir = ""
        
        return self._get_obs(), self._get_info()

    def step(self, action: int) -> Tuple[Dict, float, bool, bool, Dict]:
        self.step_count += 1
        self.last_action = ACTIONS[action]
        reward = -1
        
        if action == 0:
            try:
                contents = list(self.current_path.iterdir())
                self.last_action_result = f"Contents: {[c.name for c in contents]}"
            except Exception as e:
                self.last_action_result = f"Error: {str(e)}"
                reward = -5
        
        elif action == 1:
            target = self.target_dir
            if not target:
                self.last_action_result = "No target specified"
                reward = -5
            else:
                new_path = self.current_path / target
                if new_path.exists() and new_path.is_dir():
                    self.current_path = new_path
                    self.last_action_result = f"Changed to: {new_path}"
                else:
                    self.last_action_result = f"Invalid directory: {target}"
                    reward = -5
        
        elif action == 2:
            target = self.target_dir
            if not target:
                self.last_action_result = "No file specified"
                reward = -5
            else:
                file_path = self.current_path / target
                if file_path.exists() and file_path.is_file():
                    content = load_text_file(file_path)
                    extracted = call_tool_model(content, self.user_query)
                    self.last_action_result = extracted
                else:
                    self.last_action_result = f"Cannot read: {target}"
                    reward = -5
        
        elif action == 3:
            answer = self.target_dir
            if answer.lower().strip() == self.ground_truth_answer.lower().strip():
                reward = 100
                self.done = True
            else:
                reward = -20
                self.done = True
        
        if self.step_count >= self.max_steps:
            self.done = True
        
        return self._get_obs(), reward, self.done, False, self._get_info()

    def render(self):
        print(f"Path: {self.current_path}")
        print(f"Query: {self.user_query}")
        print(f"Step: {self.step_count}")

    def close(self):
        pass


def run_training_loop(env: gym.Env, num_steps: int = 100, use_llm: bool = False):
    print(f"Starting training for {num_steps} steps...")
    print(f"Using LLM: {use_llm}")
    print("=" * 50)
    
    total_reward = 0
    episode_count = 0
    successful_episodes = 0
    
    obs, info = env.reset()
    print(f"\nEpisode {episode_count + 1}")
    print(f"User Query: {obs['user_query']}")
    print(f"Ground Truth: {info['ground_truth']}")
    print(f"Start Path: {obs['current_path']}")
    
    for step in range(num_steps):
        if use_llm:
            action = call_policy_model(obs, QA_PAIRS)
        else:
            action = env.action_space.sample()
        
        obs, reward, done, truncated, info = env.step(action)
        total_reward += reward
        
        if step % 10 == 0:
            print(f"  Step {step + 1}: Action={ACTIONS[action]}, Reward={reward}, Done={done}")
        
        if done:
            episode_count += 1
            
            if reward == 100:
                successful_episodes += 1
                print(f"  Episode {episode_count + 1} SUCCESS! Reward: {reward}")
            else:
                print(f"  Episode {episode_count + 1} ended. Reward: {reward}")
            
            obs, info = env.reset()
            print(f"\nEpisode {episode_count + 2}")
            print(f"User Query: {obs['user_query']}")
            print(f"Ground Truth: {info['ground_truth']}")
    
    print("=" * 50)
    print(f"Training complete!")
    print(f"Total steps: {num_steps}")
    print(f"Total reward: {total_reward}")
    print(f"Episodes: {episode_count}")
    print(f"Successful: {successful_episodes}")
    print(f"Success rate: {successful_episodes / max(1, episode_count) * 100:.1f}%")


def main():
    import argparse
    parser = argparse.ArgumentParser(description="RL Documentation Parser")
    parser.add_argument("--use-llm", action="store_true", help="Use Ollama LLM for decision making")
    parser.add_argument("--steps", type=int, default=100, help="Number of training steps")
    args = parser.parse_args()
    
    env = DocParserEnv(max_steps=20)
    run_training_loop(env, num_steps=args.steps, use_llm=args.use_llm)
    env.close()


if __name__ == "__main__":
    main()