jankip20 commited on
Commit
ecaf142
·
verified ·
1 Parent(s): 47a9696

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. create_db.py +34 -0
  2. server/sql_env_environment.py +100 -8
  3. sql_env.db +0 -0
create_db.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+
3
+ conn = sqlite3.connect("sql_env.db")
4
+ cursor = conn.cursor()
5
+
6
+ # Create tables
7
+ cursor.executescript("""
8
+ CREATE TABLE IF NOT EXISTS employees (
9
+ id INTEGER PRIMARY KEY,
10
+ name TEXT NOT NULL,
11
+ department TEXT,
12
+ salary REAL
13
+ );
14
+
15
+ CREATE TABLE IF NOT EXISTS departments (
16
+ id INTEGER PRIMARY KEY,
17
+ name TEXT NOT NULL,
18
+ budget REAL
19
+ );
20
+
21
+ INSERT INTO departments VALUES (1, 'Engineering', 500000);
22
+ INSERT INTO departments VALUES (2, 'Marketing', 200000);
23
+ INSERT INTO departments VALUES (3, 'HR', 150000);
24
+
25
+ INSERT INTO employees VALUES (1, 'Alice', 'Engineering', 95000);
26
+ INSERT INTO employees VALUES (2, 'Bob', 'Engineering', 88000);
27
+ INSERT INTO employees VALUES (3, 'Carol', 'Marketing', 72000);
28
+ INSERT INTO employees VALUES (4, 'Dave', 'HR', 65000);
29
+ INSERT INTO employees VALUES (5, 'Eve', 'Marketing', 78000);
30
+ """)
31
+
32
+ conn.commit()
33
+ conn.close()
34
+ print("✓ sql_env.db created successfully")
server/sql_env_environment.py CHANGED
@@ -7,10 +7,13 @@
7
  """
8
  Sql Env Environment Implementation.
9
 
10
- A simple test environment that echoes back messages sent to it.
11
- Perfect for testing HTTP server infrastructure.
12
  """
13
 
 
 
 
14
  from uuid import uuid4
15
 
16
  from openenv.core.env_server.interfaces import Environment
@@ -21,33 +24,122 @@ try:
21
  except ImportError:
22
  from models import SqlAction, SqlObservation
23
 
 
 
 
 
 
 
24
  class SqlEnvironment(Environment):
25
  SUPPORTS_CONCURRENT_SESSIONS: bool = True
26
 
27
  def __init__(self):
28
  self._state = State(episode_id=str(uuid4()), step_count=0)
29
  self._reset_count = 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  def reset(self) -> SqlObservation:
32
  self._state = State(episode_id=str(uuid4()), step_count=0)
33
  self._reset_count += 1
 
34
 
35
  return SqlObservation(
36
  echoed_message="Sql Env environment ready!",
37
  message_length=0,
38
- metadata={}
39
  )
40
 
41
  def step(self, action: SqlAction) -> SqlObservation:
42
  self._state.step_count += 1
43
 
44
- message = action.query
45
- length = len(message)
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  return SqlObservation(
48
- echoed_message=message,
49
- message_length=length,
50
- metadata={}
 
 
 
 
 
 
 
51
  )
52
 
53
  @property
 
7
  """
8
  Sql Env Environment Implementation.
9
 
10
+ Executes SQL queries against a SQLite database and returns results
11
+ as structured observations.
12
  """
13
 
14
+ import json
15
+ import os
16
+ import sqlite3
17
  from uuid import uuid4
18
 
19
  from openenv.core.env_server.interfaces import Environment
 
24
  except ImportError:
25
  from models import SqlAction, SqlObservation
26
 
27
+
28
+ # Path to the SQLite database file.
29
+ # Place your .db file here, or it will be created automatically.
30
+ DB_PATH = os.environ.get("SQL_ENV_DB_PATH", "sql_env.db")
31
+
32
+
33
  class SqlEnvironment(Environment):
34
  SUPPORTS_CONCURRENT_SESSIONS: bool = True
35
 
36
  def __init__(self):
37
  self._state = State(episode_id=str(uuid4()), step_count=0)
38
  self._reset_count = 0
39
+ self._conn: sqlite3.Connection | None = None
40
+ self._connect()
41
+
42
+ # ------------------------------------------------------------------
43
+ # Internal helpers
44
+ # ------------------------------------------------------------------
45
+
46
+ def _connect(self):
47
+ """Open (or reopen) a connection to the SQLite database."""
48
+ if self._conn:
49
+ try:
50
+ self._conn.close()
51
+ except Exception:
52
+ pass
53
+ self._conn = sqlite3.connect(DB_PATH, check_same_thread=False)
54
+ self._conn.row_factory = sqlite3.Row # enables column-name access
55
+
56
+ def _execute(self, query: str) -> dict:
57
+ """
58
+ Execute a SQL query and return a result dict with keys:
59
+ - columns : list[str]
60
+ - rows : list[list]
61
+ - rowcount: int (affected rows for INSERT/UPDATE/DELETE)
62
+ - error : str | None
63
+ """
64
+ try:
65
+ cursor = self._conn.cursor()
66
+ cursor.execute(query)
67
+ self._conn.commit()
68
+
69
+ if cursor.description:
70
+ # SELECT (or any query that returns rows)
71
+ columns = [desc[0] for desc in cursor.description]
72
+ rows = [list(row) for row in cursor.fetchall()]
73
+ return {
74
+ "columns": columns,
75
+ "rows": rows,
76
+ "rowcount": len(rows),
77
+ "error": None,
78
+ }
79
+ else:
80
+ # INSERT / UPDATE / DELETE / CREATE / DROP …
81
+ return {
82
+ "columns": [],
83
+ "rows": [],
84
+ "rowcount": cursor.rowcount,
85
+ "error": None,
86
+ }
87
+ except sqlite3.Error as e:
88
+ return {
89
+ "columns": [],
90
+ "rows": [],
91
+ "rowcount": 0,
92
+ "error": str(e),
93
+ }
94
+
95
+ @staticmethod
96
+ def _reward(result: dict) -> float:
97
+ """Simple reward signal: +1 for success, -1 for error."""
98
+ return -1.0 if result["error"] else 1.0
99
+
100
+ # ------------------------------------------------------------------
101
+ # Environment interface
102
+ # ------------------------------------------------------------------
103
 
104
  def reset(self) -> SqlObservation:
105
  self._state = State(episode_id=str(uuid4()), step_count=0)
106
  self._reset_count += 1
107
+ self._connect() # fresh connection each episode
108
 
109
  return SqlObservation(
110
  echoed_message="Sql Env environment ready!",
111
  message_length=0,
112
+ metadata={"db_path": DB_PATH},
113
  )
114
 
115
  def step(self, action: SqlAction) -> SqlObservation:
116
  self._state.step_count += 1
117
 
118
+ query = action.query.strip()
119
+ result = self._execute(query)
120
+
121
+ # Build a human-readable summary for echoed_message
122
+ if result["error"]:
123
+ summary = f"ERROR: {result['error']}"
124
+ elif result["columns"]:
125
+ summary = (
126
+ f"{result['rowcount']} row(s) returned. "
127
+ f"Columns: {result['columns']}"
128
+ )
129
+ else:
130
+ summary = f"Query OK. {result['rowcount']} row(s) affected."
131
 
132
  return SqlObservation(
133
+ echoed_message=summary,
134
+ message_length=len(query),
135
+ metadata={
136
+ "query": query,
137
+ "columns": result["columns"],
138
+ "rows": result["rows"],
139
+ "rowcount": result["rowcount"],
140
+ "error": result["error"],
141
+ "reward": self._reward(result),
142
+ },
143
  )
144
 
145
  @property
sql_env.db ADDED
Binary file (12.3 kB). View file