File size: 8,256 Bytes
958590b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Job Application Simulator - Client"""

from typing import Optional, List, Union
from openenv.core import EnvClient

from models import (
    JobAppState,
    JobAppObservation,
    SearchJobs,
    AnalyzeJob,
    WriteCoverLetter,
    SubmitApplication,
    NextJob,
    StepResult,
)


class JobAppEnv(EnvClient):
    """
    Client for the Job Application Simulator environment.
    
    Usage (async):
        async with JobAppEnv(base_url="...") as env:
            obs = await env.reset(profile_name="software_engineer")
            obs = await env.step(SearchJobs(keywords=["python", "remote"]))
    
    Usage (sync):
        with JobAppEnv(base_url="...").sync() as env:
            obs = env.reset()
            obs = env.step(AnalyzeJob(job_id="job_001"))
    """
    
    def __init__(self, base_url: str = "http://localhost:8000"):
        super().__init__(base_url)
        self._episode_id: Optional[str] = None
    
    async def reset(
        self,
        profile_name: str = "default",
        budget: int = 10,
        difficulty: str = "normal"
    ) -> JobAppObservation:
        """
        Reset the environment and start a new episode.
        
        Args:
            profile_name: Name of applicant profile to load
            budget: Maximum number of applications allowed
            difficulty: 'easy', 'normal', or 'hard' (affects job market)
        
        Returns:
            Initial observation with applicant profile
        """
        result = await self._send_action({
            "type": "reset",
            "profile_name": profile_name,
            "budget": budget,
            "difficulty": difficulty
        })
        self._episode_id = result.get("episode_id")
        return self._parse_observation(result)
    
    async def step(
        self,
        action: Union[SearchJobs, AnalyzeJob, WriteCoverLetter, SubmitApplication, NextJob]
    ) -> StepResult:
        """
        Execute an action in the environment.
        
        Args:
            action: One of SearchJobs, AnalyzeJob, WriteCoverLetter, SubmitApplication, NextJob
        
        Returns:
            StepResult with observation, reward, and done flag
        """
        action_dict = self._action_to_dict(action)
        result = await self._send_action(action_dict)
        
        observation = self._parse_observation(result)
        return StepResult(
            observation=observation,
            reward=result.get("reward", 0.0),
            done=result.get("done", False),
            info=result.get("info", {})
        )
    
    async def state(self) -> JobAppState:
        """Get current episode state."""
        result = await self._send_action({"type": "state"})
        return self._parse_state(result)
    
    # ========================================================================
    # CONVENIENCE METHODS
    # ========================================================================
    
    async def search(
        self,
        keywords: List[str],
        location: Optional[str] = None,
        salary_min: Optional[int] = None,
        remote_only: bool = False
    ) -> JobAppObservation:
        """Search for jobs with given criteria."""
        return await self.step(SearchJobs(
            keywords=keywords,
            location=location,
            salary_min=salary_min,
            remote_only=remote_only
        ))
    
    async def analyze(self, job_id: str) -> JobAppObservation:
        """Analyze a specific job for fit."""
        return await self.step(AnalyzeJob(job_id=job_id))
    
    async def write_letter(
        self,
        job_id: str,
        tone: str = "professional",
        highlight_skills: Optional[List[str]] = None
    ) -> JobAppObservation:
        """Write a cover letter for a job."""
        return await self.step(WriteCoverLetter(
            job_id=job_id,
            tone=tone,
            highlight_skills=highlight_skills or []
        ))
    
    async def apply(
        self,
        job_id: str,
        cover_letter: str,
        tailored_sections: Optional[dict] = None
    ) -> JobAppObservation:
        """Submit an application."""
        return await self.step(SubmitApplication(
            job_id=job_id,
            cover_letter=cover_letter,
            tailored_resume_sections=tailored_sections or {}
        ))
    
    async def next_job(self) -> JobAppObservation:
        """Move to next job in results."""
        return await self.step(NextJob())
    
    # ========================================================================
    # INTERNAL HELPERS
    # ========================================================================
    
    def _action_to_dict(self, action) -> dict:
        """Convert action dataclass to dictionary."""
        if isinstance(action, SearchJobs):
            return {
                "type": "search_jobs",
                "keywords": action.keywords,
                "location": action.location,
                "salary_min": action.salary_min,
                "job_type": action.job_type,
                "remote_only": action.remote_only
            }
        elif isinstance(action, AnalyzeJob):
            return {
                "type": "analyze_job",
                "job_id": action.job_id
            }
        elif isinstance(action, WriteCoverLetter):
            return {
                "type": "write_cover_letter",
                "job_id": action.job_id,
                "tone": action.tone,
                "highlight_skills": action.highlight_skills
            }
        elif isinstance(action, SubmitApplication):
            return {
                "type": "submit_application",
                "job_id": action.job_id,
                "cover_letter": action.cover_letter,
                "tailored_resume_sections": action.tailored_resume_sections
            }
        elif isinstance(action, NextJob):
            return {"type": "next_job"}
        else:
            raise ValueError(f"Unknown action type: {type(action)}")
    
    def _parse_observation(self, data: dict) -> JobAppObservation:
        """Parse server response into observation."""
        from models import JobPosting, JobAnalysis
        
        job_listings = [
            JobPosting(**job) for job in data.get("job_listings", [])
        ]
        
        current_job = None
        if data.get("current_job"):
            current_job = JobPosting(**data["current_job"])
        
        analysis_result = None
        if data.get("analysis_result"):
            analysis_result = JobAnalysis(**data["analysis_result"])
        
        return JobAppObservation(
            job_listings=job_listings,
            current_job=current_job,
            analysis_result=analysis_result,
            cover_letter=data.get("cover_letter"),
            cover_letter_quality=data.get("cover_letter_quality"),
            application_status=data.get("application_status"),
            budget_remaining=data.get("budget_remaining", 10),
            applications_count=data.get("applications_count", 0),
            message=data.get("message", ""),
            done=data.get("done", False),
            reward=data.get("reward", 0.0)
        )
    
    def _parse_state(self, data: dict) -> JobAppState:
        """Parse server response into state."""
        from models import JobPosting, ApplicantProfile, SubmittedApplication
        
        state = JobAppState(
            episode_id=data.get("episode_id", ""),
            step_count=data.get("step_count", 0),
            budget_remaining=data.get("budget_remaining", 10),
            total_reward=data.get("total_reward", 0.0)
        )
        
        if data.get("current_job"):
            state.current_job = JobPosting(**data["current_job"])
        
        if data.get("applicant_profile"):
            state.applicant_profile = ApplicantProfile(**data["applicant_profile"])
        
        state.applications_submitted = [
            SubmittedApplication(**app) 
            for app in data.get("applications_submitted", [])
        ]
        
        state.last_search_results = [
            JobPosting(**job) 
            for job in data.get("last_search_results", [])
        ]
        
        return state