File size: 3,965 Bytes
1b64cdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Document Classification Environment Client.

Connects to the running OpenEnv server (FastAPI + WebSocket) and provides
a typed interface for interacting with the document classification environment.

Example (sync):
    from document_classification_env import DocEnv, DocAction

    with DocEnv(base_url="https://tanujinsane-document-classification-env.hf.space").sync() as env:
        result = env.reset()
        print("Documents to classify:", result.observation.total_documents)

        for i in range(5):
            action = DocAction(action_id=i % 5, difficulty="easy")
            result = env.step(action)
            print(f"reward={result.reward:.2f}  done={result.done}")
            if result.done:
                break

Example (async):
    import asyncio
    from document_classification_env import DocEnv, DocAction

    async def main():
        async with DocEnv(base_url="http://localhost:7860") as env:
            result = await env.reset()
            result = await env.step(DocAction(action_id=0, difficulty="easy"))
            print(result.reward)

    asyncio.run(main())
"""

from __future__ import annotations

from typing import Any, Dict

from openenv.core.env_client import EnvClient
from openenv.core.client_types import StepResult

from .models import DocAction, DocObservation, DocState


class DocEnv(EnvClient[DocAction, DocObservation, DocState]):
    """
    Client for the Document Classification Environment.

    Maintains a persistent WebSocket connection to the environment server,
    enabling efficient multi-step interactions with lower latency.

    Supports three difficulty levels:
      - easy   : 5 categories,  100 documents, no SLA
      - medium : 10 categories, 500 documents, SLA 120s
      - hard   : 22 categories, 1000 documents, SLA 60s

    Actions:
      action_id 0..N-1  → classify document into category N
      action_id N       → request metadata (tool, costs -0.05 reward)
      action_id N+1     → escalate to human (safe fallback, 0.0 reward)
    """

    def _step_payload(self, action: DocAction) -> Dict[str, Any]:
        """Convert DocAction to JSON payload for the step request."""
        return {
            "action_id": action.action_id,
            "difficulty": action.difficulty,
        }

    def _parse_result(self, payload: Dict[str, Any]) -> StepResult[DocObservation]:
        """Parse server WebSocket response into a typed StepResult."""
        obs_data = payload.get("observation", payload)

        observation = DocObservation(
            document_id=obs_data.get("document_id", ""),
            content=obs_data.get("content", ""),
            word_count=obs_data.get("word_count", 0),
            has_urgency_markers=obs_data.get("has_urgency_markers", False),
            features=obs_data.get("features", []),
            document_index=obs_data.get("document_index", 0),
            total_documents=obs_data.get("total_documents", 0),
            metadata_response=obs_data.get("metadata_response", "Not requested."),
            sla_remaining=obs_data.get("sla_remaining", 999.0),
            reward=obs_data.get("reward", payload.get("reward", 0.0)),
            done=obs_data.get("done", payload.get("done", False)),
            metadata=obs_data.get("metadata", payload.get("info", {})),
        )

        return StepResult(
            observation=observation,
            reward=observation.reward,
            done=observation.done,
        )

    def _parse_state(self, payload: Dict[str, Any]) -> DocState:
        """Parse server /state response into a typed DocState."""
        return DocState(
            episode_id=payload.get("episode_id", ""),
            step_count=payload.get("step_count", 0),
            difficulty=payload.get("difficulty", "easy"),
            accuracy=payload.get("accuracy", 0.0),
            total_reward=payload.get("total_reward", 0.0),
            sla_breaches=payload.get("sla_breaches", 0),
        )