Coverage for ppedit/claude.py: 82.3%
495 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 17:40 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 17:40 +0000
1"""Claude assistant sessions
3A `Sessions` object holds any number of conversations with Claude (the
4Anthropic Messages API) that read and edit the case open in the editor.
5Each session runs its own tool-use loop in a background thread; every
6change Claude makes goes through the same `ppedit.case.Case` methods and
7`ppedit.server.Editor.edit` as the browser, so it is checked, shows up in
8the browser on its next refresh, and can be undone like any other edit.
10Configuration
11-------------
13 - Agent: `AGENTS` lists the agent back ends a session can use (chosen in
14 the editor's Settings tab, decision #64); only `claude` exists.
16 - API key: given per session as `api_key` (the key text) or `api_key_file`
17 (a file on the server machine whose first line is the key), or else the
18 server default: the `ANTHROPIC_API_KEY` environment variable, or the
19 first line of `~/.anthropic`. With no server default the Agent tab says
20 so, and a session starts only when the Settings tab gives a key. A key
21 is kept in server memory with its session and never returned in the
22 session state.
24 - Model: chosen per session from `MODELS`; the default is
25 `PPEDIT_CLAUDE_MODEL` from the environment or `DEFAULT_MODEL`.
27Data sources
28------------
30Every session can read and edit the case, validate it and run PF/OPF,
31including multistep OPF over the case time series (`multistep` and
32`window` of the `solve` tool, as in `/api/solve`). It can also read
33(issue #162):
35 - `get_series`: the time series of the case (`Case.series`) and their
36 combined horizon (`Case.combined_series`), as summaries or as step
37 rows, filtered by column name or prefix;
39 - `get_result`: the editor's last solution (`Editor.result`), whether
40 the page or the session ran it: its summary (with the result columns
41 of each table), result rows (with the extended columns on request),
42 the solver log, and for a multistep OPF the horizon cost and window,
43 the per-step summary (as the Results tab's Steps block), the rows and
44 storage of any step, and any result column of chosen rows at every
45 step (`column`, `rows`);
47 - `get_issues`: what the Issues tab lists: `Case.validate()` and the
48 last solve's `messages` with their `detail`.
50The `solve` tool refuses to run while a solve started from the page is
51still running (decision #63).
53Two optional data sources are chosen when a session is created:
55 - `web`: Anthropic's server-side web search tool and a `fetch_url` tool
56 that downloads a public `http(s)` page or data file through the
57 `ppedit` server (text, at most `FETCH_LIMIT` bytes).
59 - `local`: `list_files` and `read_file` tools for files under one
60 folder on the server machine (`root`, default: the folder of the open
61 case file, or the current folder). Paths that resolve outside `root`
62 are refused.
64Geodata can be loaded from either source with `load_geodata` (CSV text
65or a local CSV file).
67Caveats
68-------
70 - Sessions live in server memory and are lost when the server stops.
72 - Several sessions may edit the case at the same time; each tool call is
73 one undoable edit, so concurrent sessions interleave their edits.
75 - Tool results sent to Claude are cut to `RESULT_LIMIT` characters.
76"""
78import itertools
79import json
80import os
81import threading
82import time
83import urllib.error
84import urllib.request
86from ppedit.case import COLUMNS, TABLES, RESULT_COLUMNS, PF_SOLVERS, OPF_SOLVERS, CaseError
88API_URL = "https://api.anthropic.com/v1/messages"
89"""Anthropic Messages API endpoint"""
91API_VERSION = "2023-06-01"
92"""Value of the `anthropic-version` header"""
94AGENTS = ["claude"]
95"""Agent back ends sessions can use (the editor's Settings tab picks one)"""
97MODELS = ["claude-sonnet-5-5","claude-opus-5-5","claude-haiku-5-5"]
98"""Models offered in the editor (first is the default)"""
100DEFAULT_MODEL = os.environ.get("PPEDIT_CLAUDE_MODEL",MODELS[0])
101"""Model used when a session does not choose one"""
103MAX_TOKENS = 8192
104"""Maximum tokens per Claude response"""
106MAX_STEPS = 40
107"""Maximum API calls in one turn (a user message and the tool use it causes)"""
109RESULT_LIMIT = 30000
110"""Maximum characters of one tool result sent to Claude"""
112FETCH_LIMIT = 2000000
113"""Maximum bytes read by `fetch_url`"""
115READ_LIMIT = 2000000
116"""Maximum bytes read by `read_file`"""
118def api_key() -> str|None:
119 """Return the Anthropic API key from the environment or `~/.anthropic`"""
120 key = os.environ.get("ANTHROPIC_API_KEY")
121 if key: 121 ↛ 122line 121 didn't jump to line 122 because the condition on line 121 was never true
122 return key.strip()
123 try:
124 with open(os.path.expanduser("~/.anthropic"),encoding="utf-8") as fh:
125 return fh.readline().strip() or None
126 except OSError:
127 return None
129def read_key_file(path:str) -> str:
130 """Return the API key in the first line of a file on the server machine
132 Arguments
133 ---------
135 - `path`: file name (`~` is expanded)
137 Raises `CaseError` when the file cannot be read or its first line is
138 empty. The message names the file, never its contents.
139 """
140 name = os.path.expanduser(str(path or "").strip())
141 if not name: 141 ↛ 142line 141 didn't jump to line 142 because the condition on line 141 was never true
142 raise CaseError("no API key file given")
143 try:
144 with open(name,encoding="utf-8") as fh:
145 key = fh.readline().strip()
146 except OSError as err:
147 raise CaseError(f"cannot read API key file '{path}': {err.strerror}") from err
148 if not key:
149 raise CaseError(f"API key file '{path}' is empty")
150 return key
152def http_client(payload:dict,key:str|None=None) -> dict:
153 """Send one Messages API request and return the response
155 Arguments
156 ---------
158 - `payload`: request body (`model`, `system`, `messages`, `tools`, ...)
160 - `key`: API key (default: `api_key()`)
162 Returns
163 -------
165 - `dict`: the API response
167 Raises `RuntimeError` with the API's error message on failure.
168 """
169 key = key or api_key()
170 if not key:
171 raise RuntimeError("no Anthropic API key (set ANTHROPIC_API_KEY or create ~/.anthropic)")
172 req = urllib.request.Request(API_URL,data=json.dumps(payload).encode(),method="POST",
173 headers={"x-api-key":key,"anthropic-version":API_VERSION,
174 "content-type":"application/json"})
175 try:
176 with urllib.request.urlopen(req,timeout=600) as res:
177 return json.loads(res.read())
178 except urllib.error.HTTPError as err:
179 try:
180 msg = json.loads(err.read())["error"]["message"]
181 except Exception: # pylint: disable=broad-exception-caught
182 msg = str(err)
183 raise RuntimeError(f"Claude API error {err.code}: {msg}") from err
184 except urllib.error.URLError as err:
185 raise RuntimeError(f"cannot reach the Claude API: {err.reason}") from err
187# ---------------------------------------------------------------------------
188# tools
189# ---------------------------------------------------------------------------
191_TABLE = {"type":"string","enum":TABLES}
193_SERIES_ROWS = 24
194"""Steps `get_series` returns when `count` is not given"""
196_RESULT_ROWS = 200
197"""Rows `get_result` returns when `count` is not given"""
199_RESULT_TABLES = ["bus","gen","branch","dcline","areas","steps","storage"]
201CASE_TOOLS = [
202 {"name":"get_case","description":"Summary of the open case: name, baseMVA, "
203 "version, row count of each table, geodata row count, and load notes.",
204 "input_schema":{"type":"object","properties":{}}},
205 {"name":"get_table","description":"Rows of one table as objects keyed by "
206 "column name, with their 0-based row index. Use start/count to page "
207 "through large tables.",
208 "input_schema":{"type":"object","properties":{"table":_TABLE,
209 "start":{"type":"integer","minimum":0},"count":{"type":"integer","minimum":1}},
210 "required":["table"]}},
211 {"name":"set_cell","description":"Set one cell. Renumbering a bus renumbers "
212 "its references. Returns whether other cells changed as a result.",
213 "input_schema":{"type":"object","properties":{"table":_TABLE,
214 "row":{"type":"integer","minimum":0},"column":{"type":"string"},
215 "value":{"type":["number","string"]}},"required":["table","row","column","value"]}},
216 {"name":"set_cells","description":"Set several cells as one undoable edit; "
217 "all are rolled back if any fails.",
218 "input_schema":{"type":"object","properties":{"edits":{"type":"array","items":{
219 "type":"object","properties":{"table":_TABLE,"row":{"type":"integer","minimum":0},
220 "column":{"type":"string"},"value":{"type":["number","string"]}},
221 "required":["table","row","column","value"]}}},"required":["edits"]}},
222 {"name":"add_rows","description":"Add rows to a table as one undoable edit. "
223 "Each row is an object of column values (missing columns get defaults) "
224 "or a full list in column order. Adding a gen or dcline also adds its "
225 "cost row when the case has costs. Returns the new row indexes.",
226 "input_schema":{"type":"object","properties":{"table":_TABLE,
227 "rows":{"type":"array","items":{"type":["object","array"]}},
228 "after":{"type":"integer","minimum":0,"description":"insert after this row (default: append)"}},
229 "required":["table","rows"]}},
230 {"name":"delete_rows","description":"Delete rows by 0-based index. Deleting "
231 "buses that have connections needs cascade=true (connections are deleted too).",
232 "input_schema":{"type":"object","properties":{"table":_TABLE,
233 "rows":{"type":"array","items":{"type":"integer","minimum":0}},
234 "cascade":{"type":"boolean"}},"required":["table","rows"]}},
235 {"name":"set_global","description":"Set the case name, baseMVA or version.",
236 "input_schema":{"type":"object","properties":{"key":{"type":"string",
237 "enum":["name","baseMVA","version"]},"value":{"type":["number","string"]}},
238 "required":["key","value"]}},
239 {"name":"validate","description":"Check the case; returns the list of errors and warnings.",
240 "input_schema":{"type":"object","properties":{}}},
241 {"name":"solve","description":"Run a PYPOWER power flow (pf) or optimal power "
242 "flow (opf, needs gencost). algorithm: for pf one of "+", ".join(PF_SOLVERS)
243 +" (default NR); for opf one of "+", ".join(OPF_SOLVERS)+" (default PIPS; "
244 "DC-* solve the DC OPF; IPOPT, CPLEX, MOSEK and Gurobi need their Python "
245 "module installed; CVXOPF-* use cvxopf if installed: AC, SOCP relaxation, "
246 "lossy DC network flow, copper plate (1NODE), no prices; options for CVXOPF-* only: "
247 "preparation default|recommended, solver (CVXPY solver for the convex models), verbose, "
248 "solver_options {name: value}). Returns a summary with messages (solver errors and "
249 "warnings; a warning's detail gives its physical meaning and the constraints and case rows "
250 "involved); the full result is shown in the editor's Results tab and read with "
251 "get_result. multistep=true solves the combined time series (get_series) as one "
252 "multistep OPF (opf with a CVXOPF-* solver only), over the combined steps "
253 "window [first, last] (counted from 0, both included; default all).",
254 "input_schema":{"type":"object","properties":{"kind":{"type":"string","enum":["pf","opf"]},
255 "algorithm":{"type":"string","enum":[*PF_SOLVERS,*OPF_SOLVERS]},
256 "multistep":{"type":"boolean"},
257 "window":{"type":"array","items":{"type":"integer","minimum":0},
258 "minItems":2,"maxItems":2},
259 "options":{"type":"object","properties":{
260 "preparation":{"type":"string","enum":["default","recommended"]},
261 "solver":{"type":"string"},"verbose":{"type":"boolean"},
262 "solver_options":{"type":"object"}}}}}},
263 {"name":"apply_result","description":"Copy the last solution (voltages, "
264 "generator outputs) into the case; for a multistep solution, the step "
265 "given by step (counted from 0 in the solved window, default 0).",
266 "input_schema":{"type":"object","properties":{"step":{"type":"integer","minimum":0}}}},
267 {"name":"get_series","description":"Time series of case values used by multistep "
268 "OPF. Without name: the summary of every series (columns, steps, hours per step, "
269 "first and last labels) and of the combined series the multistep OPF solves "
270 "(or why the series cannot be combined). With name (a series name, or "
271 "\"combined\"): its step rows {step (0-based), label, values {column: value}} "
272 "from start, count steps (default "+str(_SERIES_ROWS)+"). Columns are "
273 "table.column.key: bus.Pd.<bus_i>, bus.Qd.<bus_i>, gen.Pmin.<gen row from 1>, "
274 "gen.Pmax.<n>, dcline.Pmin.<n>, dcline.Pmax.<n>; columns limits them to the "
275 "names or prefixes given (e.g. [\"bus.Pd\", \"gen.Pmax.3\"]).",
276 "input_schema":{"type":"object","properties":{"name":{"type":"string"},
277 "start":{"type":"integer","minimum":0},"count":{"type":"integer","minimum":1},
278 "columns":{"type":"array","items":{"type":"string"}}}}},
279 {"name":"get_result","description":"The last solution in the editor, whether the "
280 "user (Results tab) or this session ran it; edits clear it. Without table: its "
281 "summary (success, solver, objective, losses, row counts, multistep horizon "
282 "and window, message count). table bus|gen|branch|dcline|areas: result rows "
283 "(extended=true adds prices and multipliers when the solver gives them); "
284 "table steps: one summary row per step of a multistep solution; table storage: "
285 "storage dispatch of a multistep step. step (counted from 0 in the solved "
286 "window) picks a multistep step (default 0). For a multistep solution, "
287 "table with column (a result column such as Pg, Vm, loading_pct, Pd, E, or an "
288 "extended column such as lam_P; the summary lists them) gives that column "
289 "of every row, or of rows (0-based), at every step: the optimization "
290 "result over the horizon. start/count page the rows (the steps with column). "
291 "log=true adds the end of the solver log (the step's report with step).",
292 "input_schema":{"type":"object","properties":{"table":{"type":"string",
293 "enum":_RESULT_TABLES},"step":{"type":"integer","minimum":0},
294 "column":{"type":"string"},
295 "rows":{"type":"array","items":{"type":"integer","minimum":0}},
296 "start":{"type":"integer","minimum":0},"count":{"type":"integer","minimum":1},
297 "extended":{"type":"boolean"},"log":{"type":"boolean"}}}},
298 {"name":"get_issues","description":"Everything the editor's Issues tab lists: "
299 "case issues (the same as validate) and the errors and warnings of the last "
300 "solve, each warning with its detail when known (physical meaning, constraints "
301 "and case rows involved).",
302 "input_schema":{"type":"object","properties":{}}},
303 {"name":"load_geodata","description":"Replace the case geodata (bus "
304 "locations) from CSV with columns BUS_I, LAT, LON (others kept as "
305 "auxiliary data), given as text or as a local file path.",
306 "input_schema":{"type":"object","properties":{"text":{"type":"string"},
307 "path":{"type":"string"}}}},
308]
310WEB_TOOLS = [
311 {"type":"web_search_20250305","name":"web_search","max_uses":10},
312 {"name":"fetch_url","description":"Download a public http(s) page or data "
313 "file (CSV, JSON, text, HTML) and return its text.",
314 "input_schema":{"type":"object","properties":{"url":{"type":"string"}},"required":["url"]}},
315]
317LOCAL_TOOLS = [
318 {"name":"list_files","description":"List files and folders in a folder under "
319 "the local data folder (path relative to it; default: the folder itself).",
320 "input_schema":{"type":"object","properties":{"path":{"type":"string"}}}},
321 {"name":"read_file","description":"Read a text file under the local data folder "
322 "(path relative to it). Use offset/limit (characters) for large files.",
323 "input_schema":{"type":"object","properties":{"path":{"type":"string"},
324 "offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1}},
325 "required":["path"]}},
326]
328def _columns_text():
329 lines = []
330 for table,cols in COLUMNS.items():
331 lines.append(f"- {table}: " + ", ".join(
332 c["name"] + (f" [{c['unit']}]" if c["unit"] else "")
333 + (f" {{{', '.join(f'{k}={v}' for k,v in c['options'].items())}}}" if c["options"] else "")
334 for c in cols))
335 return "\n".join(lines)
337SYSTEM = """You are working inside ppedit, a browser editor for PYPOWER power \
338system cases (also Arras Energy GridLAB-D `module pypower` models). You read \
339and change the case open in the editor only through the tools provided; the \
340user sees every change immediately in the editor and can undo each tool call.
342Tables and columns (PYPOWER caseformat; row indexes are 0-based):
343{columns}
345Conventions:
346- gencost and dclinecost rows follow gen and dcline row by row; costs is a \
347comma-separated string of coefficients (polynomial, highest order first) or \
348x,y pairs (piecewise).
349- areas rows are [area, price_ref_bus, name]; bus.area holds each bus's area number
350 (the key); name is an optional free-text label (e.g. a balancing authority code).
351- storage rows are discharged by generator row gen_i (counted from 1, unlike \
352row indexes) and charge at bus bus_i, or through that generator when bus_i is \
353-1; only multistep CVXOPF OPF models them (Es is the starting energy, Eend -1 \
354leaves the final energy free).
355- Infinite limits are the strings "Inf" and "-Inf".
356- Enum columns accept the code or the keyword shown in braces.
357- Multistep data: get_series reads the time series of loads and limits; the \
358multistep OPF solves their combined series (solve with multistep=true). Step \
359numbers in tools count from 0; the editor shows them counted from 1.
360- Results and issues: get_result reads the last solution, including one the \
361user ran in the editor and each step of a multistep solution; get_issues \
362reads what the Issues tab shows (case issues and the last solve's messages). \
363For a multistep OPF, get_result with table steps summarizes every step, and \
364with table and column gives one quantity (e.g. gen Pg, bus lam_P, branch \
365loading_pct, storage E) of the rows you choose across all steps. \
366Read them before explaining a result or an issue, and do not solve again \
367just to see a result that already exists.
369Work carefully: read the tables you need before editing, prefer one \
370set_cells or add_rows call for related changes, validate after editing, and \
371tell the user briefly what you changed and why. When you use outside data, \
372say where it came from.{sources}"""
374def _system(web,local,root):
375 sources = []
376 if web: 376 ↛ 377line 376 didn't jump to line 377 because the condition on line 376 was never true
377 sources.append("You may search the web and fetch public data with web_search and fetch_url.")
378 if local: 378 ↛ 379line 378 didn't jump to line 379 because the condition on line 378 was never true
379 sources.append(f"You may read local files under the data folder {root} with list_files and read_file.")
380 if not sources: 380 ↛ 382line 380 didn't jump to line 382 because the condition on line 380 was always true
381 sources.append("No outside data sources are enabled in this session; use only the case and what the user tells you.")
382 return SYSTEM.format(columns=_columns_text(),sources="\n\n"+" ".join(sources))
384def _row_dict(table,row):
385 return {c["name"]:v for c,v in zip(COLUMNS[table],row)}
387def _page(rows,args,default):
388 """Rows `start` to `start + count` (`count` default `default`) as
389 `(start, rows)`"""
390 start = int(args.get("start") or 0)
391 count = int(args.get("count") or default)
392 return start,rows[start:start+count]
394def _series_tool(case,args) -> dict:
395 """Result of the `get_series` tool"""
396 name = args.get("name")
397 if not name:
398 combined = case._combined_info() # pylint: disable=protected-access
399 return {"series":[{"name":s["name"],"columns":len(s["columns"]),"steps":len(s["values"]),
400 "delta_h":s["delta"],"timed":s["timed"],
401 "first":s["index"][0] if s["index"] else None,
402 "last":s["index"][-1] if s["index"] else None} for s in case.series],
403 "combined":{k:v for k,v in combined.items() if k != "index"} if combined else None,
404 **({} if case.series else {"note":"the case has no time series"})}
405 ser = case.get_series(name)
406 if ser is None and name == "combined":
407 ser = case.combined_series()
408 if ser is None:
409 raise CaseError(f"no series '{name}' (series: "
410 + (", ".join(s["name"] for s in case.series) or "none") + "; or 'combined')")
411 prefixes = [str(p).strip().lower() for p in args.get("columns") or [] if str(p).strip()]
412 keep = [j for j,c in enumerate(ser["columns"]) if not prefixes
413 or any(c.lower() == p or c.lower().startswith(p + ".") for p in prefixes)]
414 start,steps = _page(list(range(len(ser["values"]))),args,_SERIES_ROWS)
415 return {"name":name,"steps":len(ser["values"]),"delta_h":ser["delta"],"timed":ser["timed"],
416 "columns":len(ser["columns"]),"columns_shown":len(keep),"start":start,
417 "rows":[{"step":t,"label":ser["index"][t],
418 "values":{ser["columns"][j]:ser["values"][t][j] for j in keep}} for t in steps]}
420def _multistep_info(result) -> dict:
421 """Multistep horizon of a result, without the full list of step labels"""
422 info = result.get("multistep") or {}
423 index = info.get("index") or []
424 steps = result.get("steps") or []
425 return {**{k:v for k,v in info.items() if k != "index"},
426 "first_label":index[0] if index else None,"last_label":index[-1] if index else None,
427 "horizon_objective":result.get("horizon_objective"),
428 "steps_solved":sum(1 for s in steps if s.get("success"))}
430def _result_summary(result) -> dict:
431 """Summary of a solver result"""
432 messages = result.get("messages") or []
433 out = {k:result.get(k) for k in ("success","kind","algorithm","solver","dc","stopped",
434 "iterations","objective","losses_MW","dcline_losses_MW","options")}
435 out["rows"] = {t:len(result.get(t) or []) for t in ("bus","gen","branch","dcline","areas")}
436 out["messages"] = {level:sum(1 for m in messages if m.get("level") == level)
437 for level in ("error","warning")}
438 if result.get("multistep"):
439 out["multistep"] = _multistep_info(result)
440 if result.get("success"): 440 ↛ 442line 440 didn't jump to line 442 because the condition on line 440 was always true
441 out["columns"] = _result_columns((result.get("steps") or [result])[0])
442 return out
444def _result_step(result,step):
445 """The result of multistep step `step` (counted from 0), or the result
446 itself when it is not multistep and `step` is 0 or `None`"""
447 if not result: 447 ↛ 448line 447 didn't jump to line 448 because the condition on line 447 was never true
448 raise CaseError("no solution: the case has not been solved since the last edit")
449 steps = result.get("steps")
450 if not steps:
451 if step not in (None,0):
452 raise CaseError("the last solution is not a multistep solution")
453 return result
454 step = int(step or 0)
455 if not 0 <= step < len(steps):
456 raise CaseError(f"the multistep solution has steps 0 to {len(steps)-1}")
457 return steps[step]
459def _result_columns(step) -> dict:
460 """Column names of each result table of one (step) result, extended
461 columns included"""
462 out = {}
463 for table in ("bus","gen","branch","dcline","areas","storage"):
464 rows = step.get(table) or []
465 if rows:
466 out[table] = list(rows[0]) + [c["name"] for c in RESULT_COLUMNS.get(table,[])
467 if (step.get("extended") or {}).get(table)]
468 return out
470def _value(step,table,column,n):
471 """Value of `column` in row `n` of `table` of one (step) result, from
472 the result rows or the extended columns"""
473 rows = step.get(table) or []
474 if n >= len(rows): 474 ↛ 475line 474 didn't jump to line 475 because the condition on line 474 was never true
475 return None
476 if column in rows[n]:
477 return rows[n][column]
478 names = [c["name"] for c in RESULT_COLUMNS.get(table,[])]
479 ext = (step.get("extended") or {}).get(table)
480 if column in names and ext and n < len(ext): 480 ↛ 481line 480 didn't jump to line 481 because the condition on line 480 was never true
481 return ext[n][names.index(column)]
482 raise CaseError(f"result table '{table}' has no column '{column}' (columns: "
483 + ", ".join(_result_columns(step).get(table,[])) + ")")
485def _trajectory(result,table,args) -> dict:
486 """`get_result` with `column`: one result column of the chosen rows at
487 every step of a multistep solution (one value per row and step)"""
488 steps = result.get("steps")
489 if not steps:
490 raise CaseError("column needs a multistep solution (read one step's rows with table)")
491 if table not in ("bus","gen","branch","dcline","areas","storage"): 491 ↛ 492line 491 didn't jump to line 492 because the condition on line 491 was never true
492 raise CaseError("column needs table bus, gen, branch, dcline, areas or storage")
493 column = args["column"]
494 total = len(steps[0].get(table) or [])
495 rows = [int(n) for n in args.get("rows") or range(total)]
496 bad = [n for n in rows if not 0 <= n < total]
497 if bad:
498 raise CaseError(f"result table '{table}' has rows 0 to {total-1}, not {bad}")
499 start,picked = _page(list(range(len(steps))),args,_RESULT_ROWS)
500 values = [[_value(steps[t],table,column,n) for n in rows] for t in picked]
501 keys = {"bus":"bus_i","areas":"area"}.get(table)
502 return {"table":table,"column":column,"rows":rows,
503 **({keys:[(steps[0][table][n] or {}).get(keys) for n in rows]} if keys else {}),
504 "steps":len(steps),"start":start,
505 "values":[{"step":t,"label":steps[t].get("label"),"values":v} for t,v in zip(picked,values)]}
507def _result_tool(result,args) -> dict:
508 """Result of the `get_result` tool"""
509 if not result:
510 return {"solution":None,"note":"no solution: the case has not been solved since the "
511 "last edit (edits, undo and opening a case clear it)"}
512 table,step = args.get("table"),args.get("step")
513 if args.get("column"):
514 return _trajectory(result,table,args)
515 if table == "steps":
516 if not result.get("steps"):
517 raise CaseError("the last solution is not a multistep solution")
518 rows = [{"step":t,"label":s.get("label"),"success":s.get("success"),
519 "objective":s.get("objective"),"losses_MW":s.get("losses_MW"),
520 "dcline_losses_MW":s.get("dcline_losses_MW"),
521 "Pg_MW":sum(g.get("Pg") or 0 for g in s.get("gen") or []),
522 "Pd_MW":sum(a.get("Pd") or 0 for a in s.get("areas") or []),
523 **({"storage_MW":sum((x.get("Pdis") or 0) - (x.get("Pch") or 0)
524 for x in s["storage"] if x.get("solved")),
525 "stored_MWh":sum(x.get("E") or 0 for x in s["storage"] if x.get("solved"))}
526 if any(x.get("solved") for x in s.get("storage") or []) else {})}
527 for t,s in enumerate(result["steps"])]
528 start,rows = _page(rows,args,_RESULT_ROWS)
529 return {"table":"steps","total":len(result["steps"]),"start":start,"rows":rows}
530 target = _result_step(result,step)
531 if table is None:
532 out = _result_summary(result)
533 if result.get("steps"):
534 out["step"] = {"step":int(step or 0),**{k:target.get(k) for k in ("label","success",
535 "objective","losses_MW","dcline_losses_MW","areas")}}
536 else:
537 if table not in _RESULT_TABLES: 537 ↛ 538line 537 didn't jump to line 538 because the condition on line 537 was never true
538 raise CaseError(f"unknown result table '{table}'")
539 rows = target.get(table) or []
540 ext = target.get("extended",{}).get(table) if args.get("extended") else None
541 names = [c["name"] for c in RESULT_COLUMNS.get(table,[])]
542 out_rows = []
543 for n,row in enumerate(rows):
544 item = {"row":n,**row}
545 if ext and n < len(ext):
546 item.update({k:v for k,v in zip(names,ext[n]) if v is not None})
547 out_rows.append(item)
548 start,out_rows = _page(out_rows,args,_RESULT_ROWS)
549 out = {"table":table,"total":len(rows),"start":start,"rows":out_rows}
550 if result.get("steps"):
551 out |= {"step":int(step or 0),"label":target.get("label")}
552 if args.get("log"):
553 out["log"] = (target.get("log") or "")[-6000:]
554 return out
556def _clip(text):
557 if len(text) <= RESULT_LIMIT: 557 ↛ 559line 557 didn't jump to line 559 because the condition on line 557 was always true
558 return text
559 return text[:RESULT_LIMIT] + f"\n... [cut: {len(text)-RESULT_LIMIT} more characters]"
561# ---------------------------------------------------------------------------
562# sessions
563# ---------------------------------------------------------------------------
565class Session:
566 """One conversation with Claude about the open case
568 Arguments
569 ---------
571 - `sid`: session id
573 - `editor`: the `ppedit.server.Editor` being edited
575 - `client`: function sending one API request (see `http_client`)
577 - `title`: display title
579 - `model`: Claude model name
581 - `web`: enable the web data source
583 - `local`: enable the local files data source
585 - `root`: local data folder
587 - `key`: API key for this session (default: the client's own)
588 """
590 def __init__(self,sid,editor,client,title="",model=None,web=False,local=False,root=None,
591 key=None):
592 self.id = sid
593 self.editor = editor
594 self.client = client
595 self.title = title or f"Session {sid}"
596 self.model = model or DEFAULT_MODEL
597 self.web = bool(web)
598 self.local = bool(local)
599 self.root = os.path.realpath(os.path.expanduser(root)) if root else None
600 if self.local and (not self.root or not os.path.isdir(self.root)): 600 ↛ 601line 600 didn't jump to line 601 because the condition on line 600 was never true
601 raise CaseError(f"local data folder '{root}' not found")
602 self.messages = []
603 """Conversation sent to the API"""
604 self.transcript = []
605 """Items shown in the editor: `{"kind": "user"|"assistant"|"tool"|"error", ...}`"""
606 self.status = "idle"
607 """`idle`, `running`, or `stopping`"""
608 self.edits = 0
609 """Number of tool calls that changed the case"""
610 self.usage = {"input_tokens":0,"output_tokens":0}
611 self.created = time.time()
612 self.agent = "claude"
613 """Agent back end (see `AGENTS`)"""
614 self._key = key or None
615 self._stop = False
616 self._thread = None
617 self._lock = threading.Lock()
619 def summary(self) -> dict:
620 """Return the session for the browser"""
621 with self._lock:
622 return {"id":self.id,"title":self.title,"agent":self.agent,"model":self.model,
623 "web":self.web,"local":self.local,"root":self.root,
624 "status":self.status,"edits":self.edits,"usage":dict(self.usage),
625 "transcript":list(self.transcript)}
627 def _add(self,**item):
628 with self._lock:
629 item["time"] = time.time()
630 self.transcript.append(item)
632 def send(self,text:str):
633 """Add a user message and start working on it in the background"""
634 text = (text or "").strip()
635 if not text:
636 raise CaseError("empty message")
637 with self._lock:
638 if self.status != "idle": 638 ↛ 639line 638 didn't jump to line 639 because the condition on line 638 was never true
639 raise CaseError("this session is still working")
640 self.status = "running"
641 self._stop = False
642 self.messages.append({"role":"user","content":[{"type":"text","text":text}]})
643 self._add(kind="user",text=text)
644 self._thread = threading.Thread(target=self._run,daemon=True)
645 self._thread.start()
647 def stop(self):
648 """Ask the session to stop after the current step"""
649 with self._lock:
650 if self.status == "running": 650 ↛ 651line 650 didn't jump to line 651 because the condition on line 650 was never true
651 self.status = "stopping"
652 self._stop = True
654 def wait(self,timeout:float|None=None):
655 """Wait for the background work to finish (for tests and scripts)"""
656 if self._thread: 656 ↛ exitline 656 didn't return from function 'wait' because the condition on line 656 was always true
657 self._thread.join(timeout)
659 def _tools(self):
660 return CASE_TOOLS + (WEB_TOOLS if self.web else []) + (LOCAL_TOOLS if self.local else [])
662 def _run(self):
663 try:
664 for _ in range(MAX_STEPS): 664 ↛ 699line 664 didn't jump to line 699 because the loop on line 664 didn't complete
665 if self._stop: 665 ↛ 666line 665 didn't jump to line 666 because the condition on line 665 was never true
666 self._add(kind="error",text="stopped")
667 break
668 payload = {"model":self.model,"max_tokens":MAX_TOKENS,
669 "system":[{"type":"text","text":_system(self.web,self.local,self.root),
670 "cache_control":{"type":"ephemeral"}}],
671 "tools":self._tools(),"messages":self.messages}
672 res = self.client(payload,key=self._key) if self._key else self.client(payload)
673 usage = res.get("usage") or {}
674 with self._lock:
675 for k in self.usage:
676 self.usage[k] += int(usage.get(k) or 0)
677 content = res.get("content") or []
678 self.messages.append({"role":"assistant","content":content})
679 results = []
680 for block in content:
681 kind = block.get("type")
682 if kind == "text" and block.get("text","").strip():
683 self._add(kind="assistant",text=block["text"])
684 elif kind == "server_tool_use": 684 ↛ 685line 684 didn't jump to line 685 because the condition on line 684 was never true
685 self._add(kind="tool",name=block.get("name"),input=block.get("input"),
686 result="(searched by Claude)",ok=True)
687 elif kind == "tool_use": 687 ↛ 680line 687 didn't jump to line 680 because the condition on line 687 was always true
688 results.append(self._call(block))
689 stop = res.get("stop_reason")
690 if results:
691 self.messages.append({"role":"user","content":results})
692 continue
693 if stop == "pause_turn": 693 ↛ 694line 693 didn't jump to line 694 because the condition on line 693 was never true
694 continue
695 if stop == "max_tokens": 695 ↛ 696line 695 didn't jump to line 696 because the condition on line 695 was never true
696 self._add(kind="error",text="response cut off (max_tokens)")
697 break
698 else:
699 self._add(kind="error",text=f"stopped after {MAX_STEPS} steps")
700 except Exception as err: # pylint: disable=broad-exception-caught
701 self._add(kind="error",text=str(err))
702 # keep the conversation valid for the next message
703 if self.messages and self.messages[-1]["role"] == "user" \
704 and any(b.get("type") == "tool_result" for b in self.messages[-1]["content"]):
705 self.messages.append({"role":"assistant","content":[{"type":"text","text":"(interrupted)"}]})
706 finally:
707 if self.messages and self.messages[-1]["role"] == "assistant" \ 707 ↛ 710line 707 didn't jump to line 710 because the condition on line 707 was never true
708 and any(b.get("type") == "tool_use" for b in self.messages[-1]["content"]):
709 # stopped before the tool results were sent
710 self.messages.append({"role":"user","content":[{"type":"tool_result",
711 "tool_use_id":b["id"],"content":"not run (stopped)","is_error":True}
712 for b in self.messages[-1]["content"] if b.get("type") == "tool_use"]})
713 self.messages.append({"role":"assistant","content":[{"type":"text","text":"(stopped)"}]})
714 with self._lock:
715 self.status = "idle"
717 def _call(self,block):
718 name,args = block.get("name"),block.get("input") or {}
719 try:
720 out,changed = self.run_tool(name,args)
721 ok = True
722 except Exception as err: # pylint: disable=broad-exception-caught
723 out,changed,ok = f"error: {err}",False,False
724 text = out if isinstance(out,str) else json.dumps(out,default=str)
725 if changed:
726 with self._lock:
727 self.edits += 1
728 self._add(kind="tool",name=name,input=args,result=_clip(text)[:2000],ok=ok,changed=changed)
729 return {"type":"tool_result","tool_use_id":block["id"],"content":_clip(text),
730 **({} if ok else {"is_error":True})}
732 def _edit(self,func):
733 editor = self.editor
734 with editor.lock:
735 before = editor.revision
736 out = editor.edit(func)
737 return out,editor.revision != before
739 def run_tool(self,name:str,args:dict):
740 """Run one tool call; return `(result, changed)`"""
741 # pylint: disable=too-many-return-statements,too-many-branches,too-many-locals,too-many-statements
742 editor = self.editor
743 if name == "get_case":
744 with editor.lock:
745 case = editor.case
746 combined = case._combined_info() # pylint: disable=protected-access
747 return {"name":case.name,"baseMVA":case.baseMVA,"version":case.version,
748 "rows":{t:len(r) for t,r in case.tables.items()},
749 "geodata_rows":len(case.geodata),"notes":case.notes,
750 "file":editor.path,"unsaved_changes":editor.dirty,
751 "series":[s["name"] for s in case.series],
752 "combined_series":{k:v for k,v in combined.items() if k != "index"}
753 if combined else None,
754 "issues":len(case.validate()),
755 "solution":_result_summary(editor.result) if editor.result else None},False
756 if name == "get_table":
757 table = args["table"]
758 if table not in COLUMNS: 758 ↛ 759line 758 didn't jump to line 759 because the condition on line 758 was never true
759 raise CaseError(f"unknown table '{table}'")
760 start = int(args.get("start") or 0)
761 count = int(args.get("count") or 200)
762 with editor.lock:
763 rows = editor.case.tables[table]
764 return {"table":table,"total":len(rows),"start":start,
765 "rows":[{"row":i,**_row_dict(table,r)}
766 for i,r in enumerate(rows[start:start+count],start)]},False
767 if name == "set_cell":
768 cascade,changed = self._edit(lambda: editor.case.set_value(
769 args["table"],int(args["row"]),args["column"],args["value"]))
770 return {"ok":True,"other_cells_changed":bool(cascade)},changed
771 if name == "set_cells":
772 def apply():
773 for e in args["edits"]:
774 editor.case.set_value(e["table"],int(e["row"]),e["column"],e["value"])
775 return len(args["edits"])
776 n,changed = self._edit(apply)
777 return {"ok":True,"cells":n},changed
778 if name == "add_rows":
779 def add():
780 after = args.get("after")
781 out = []
782 for values in args["rows"]:
783 out.append(editor.case.add_row(args["table"],values,after))
784 if after is not None: 784 ↛ 785line 784 didn't jump to line 785 because the condition on line 784 was never true
785 after = out[-1]
786 return out
787 rows,changed = self._edit(add)
788 return {"ok":True,"rows":rows},changed
789 if name == "delete_rows": 789 ↛ 790line 789 didn't jump to line 790 because the condition on line 789 was never true
790 removed,changed = self._edit(lambda: editor.case.delete_rows(args["table"],
791 [int(x) for x in args["rows"]],bool(args.get("cascade"))))
792 return {"ok":True,"removed":removed},changed
793 if name == "set_global": 793 ↛ 794line 793 didn't jump to line 794 because the condition on line 793 was never true
794 _,changed = self._edit(lambda: editor.case.set_global(args["key"],args["value"]))
795 return {"ok":True},changed
796 if name == "validate": 796 ↛ 797line 796 didn't jump to line 797 because the condition on line 796 was never true
797 with editor.lock:
798 issues = editor.case.validate()
799 return {"issues":issues} if issues else "no issues found",False
800 if name == "solve":
801 with editor.lock:
802 job = getattr(editor,"job",None)
803 if job is not None and not job.done:
804 raise CaseError("a solve started in the editor is still running: "
805 "wait for it to end, then read it with get_result")
806 result = editor.case.solve(args.get("kind","pf"),args.get("algorithm"),
807 args.get("options"),bool(args.get("multistep")),window=args.get("window"))
808 editor.result = result
809 out = {k:result.get(k) for k in ("success","kind","algorithm","iterations","objective",
810 "losses_MW","areas","messages")}
811 if result.get("multistep"):
812 out["multistep"] = _multistep_info(result)
813 out["note"] = ("areas and objective are those of step 0; "
814 "read every step with get_result")
815 return out | {"log":(result.get("log") or "")[-6000:]},False
816 if name == "apply_result":
817 def apply_result():
818 result = _result_step(editor.result,args.get("step"))
819 editor.case.apply_result(result)
820 _,changed = self._edit(apply_result)
821 return {"ok":True},changed
822 if name == "get_series":
823 with editor.lock:
824 return _series_tool(editor.case,args),False
825 if name == "get_result":
826 with editor.lock:
827 return _result_tool(editor.result,args),False
828 if name == "get_issues":
829 with editor.lock:
830 issues = editor.case.validate()
831 result = editor.result
832 last = None
833 if result:
834 last = {"kind":result.get("kind"),"algorithm":result.get("algorithm"),
835 "success":result.get("success"),"messages":result.get("messages") or []}
836 note = {} if result else {"note":"no solution since the last edit, "
837 "so no solve messages"}
838 return {"case":issues,"last_solve":last,**note},False
839 if name == "load_geodata": 839 ↛ 840line 839 didn't jump to line 840 because the condition on line 839 was never true
840 if args.get("text"):
841 n,changed = self._edit(lambda: editor.case.load_geodata("geodata.csv",args["text"]))
842 elif args.get("path"):
843 path = self._local(args["path"])
844 n,changed = self._edit(lambda: editor.case.load_geodata(path))
845 else:
846 raise CaseError("give text or path")
847 return {"ok":True,"rows":n},changed
848 if name == "fetch_url" and self.web: 848 ↛ 849line 848 didn't jump to line 849 because the condition on line 848 was never true
849 return _fetch(args["url"]),False
850 if name == "list_files" and self.local:
851 path = self._local(args.get("path") or ".")
852 return [e.name + ("/" if e.is_dir() else "") for e in sorted(os.scandir(path),
853 key=lambda e: e.name) if not e.name.startswith(".")][:1000],False
854 if name == "read_file" and self.local:
855 path = self._local(args["path"])
856 with open(path,encoding="utf-8",errors="replace") as fh:
857 text = fh.read(READ_LIMIT)
858 offset = int(args.get("offset") or 0)
859 limit = int(args.get("limit") or RESULT_LIMIT)
860 return {"path":args["path"],"size":len(text),"offset":offset,
861 "text":text[offset:offset+limit]},False
862 raise CaseError(f"tool '{name}' is not available in this session")
864 def _local(self,path):
865 """Resolve a path under the local data folder"""
866 if not self.local: 866 ↛ 867line 866 didn't jump to line 867 because the condition on line 866 was never true
867 raise CaseError("local files are not enabled in this session")
868 full = os.path.realpath(os.path.join(self.root,os.path.expanduser(path)))
869 if os.path.commonpath([full,self.root]) != self.root:
870 raise CaseError(f"'{path}' is outside the local data folder")
871 if not os.path.exists(full): 871 ↛ 872line 871 didn't jump to line 872 because the condition on line 871 was never true
872 raise CaseError(f"'{path}' not found")
873 return full
875def _fetch(url):
876 if not url.lower().startswith(("http://","https://")):
877 raise CaseError("only http and https URLs can be fetched")
878 req = urllib.request.Request(url,headers={"User-Agent":"ppedit"})
879 try:
880 with urllib.request.urlopen(req,timeout=60) as res:
881 data = res.read(FETCH_LIMIT+1)
882 ctype = res.headers.get("Content-Type","")
883 except urllib.error.HTTPError as err:
884 raise CaseError(f"HTTP {err.code} from {url}") from err
885 except urllib.error.URLError as err:
886 raise CaseError(f"cannot fetch {url}: {err.reason}") from err
887 cut = len(data) > FETCH_LIMIT
888 text = data[:FETCH_LIMIT].decode("utf-8",errors="replace")
889 return {"url":url,"content_type":ctype,"truncated":cut,"text":text}
891class Sessions:
892 """All Claude sessions of one editor
894 Arguments
895 ---------
897 - `editor`: the `ppedit.server.Editor` the sessions edit
899 - `client`: function sending one API request (default `http_client`);
900 tests pass a fake
901 """
903 def __init__(self,editor,client=None):
904 self.editor = editor
905 self.client = client or http_client
906 self.items = {}
907 self._ids = itertools.count(1)
908 self.lock = threading.Lock()
910 def available(self) -> bool:
911 """Whether sessions can reach Claude without a key from the Settings tab
912 (a server default key is set, or a test client)"""
913 return self.client is not http_client or bool(api_key())
915 def default_root(self) -> str:
916 """Default local data folder: the open case's folder, else the current folder"""
917 return os.path.dirname(self.editor.path) if self.editor.path else os.getcwd()
919 def create(self,**options) -> Session:
920 """Start a new session
922 Arguments
923 ---------
925 - `agent`: agent back end, one of `AGENTS` (default `claude`)
927 - `api_key`: API key text for this session
929 - `api_key_file`: file on the server machine whose first line is
930 the API key (used when `api_key` is not given)
932 - `title`, `model`, `web`, `local`, `root`: see `Session`
934 Without `api_key` or `api_key_file` the server default key is used
935 (see `api_key`). Raises `CaseError` for an unknown agent, an
936 unreadable key file, or when there is no key at all.
937 """
938 agent = options.get("agent") or "claude"
939 if agent not in AGENTS:
940 raise CaseError(f"unknown agent '{agent}' (available: {', '.join(AGENTS)})")
941 key = str(options.get("api_key") or "").strip() or None
942 if not key and options.get("api_key_file"):
943 key = read_key_file(options["api_key_file"])
944 if not key and not self.available():
945 raise CaseError("no Anthropic API key (set ANTHROPIC_API_KEY, create ~/.anthropic, "
946 "or give a key in the Settings tab)")
947 model = options.get("model") or DEFAULT_MODEL
948 if options.get("local") and not options.get("root"): 948 ↛ 949line 948 didn't jump to line 949 because the condition on line 948 was never true
949 options["root"] = self.default_root()
950 with self.lock:
951 sid = next(self._ids)
952 session = Session(sid,self.editor,self.client,options.get("title",""),model,
953 options.get("web"),options.get("local"),options.get("root"),key)
954 self.items[sid] = session
955 return session
957 def get(self,sid) -> Session:
958 """Return a session by id"""
959 try:
960 return self.items[int(sid)]
961 except (KeyError,TypeError,ValueError) as err:
962 raise CaseError(f"no Claude session {sid}") from err
964 def delete(self,sid):
965 """Stop and forget a session"""
966 session = self.get(sid)
967 session.stop()
968 with self.lock:
969 del self.items[session.id]
971 def to_dict(self) -> dict:
972 """Return all sessions for the browser"""
973 with self.lock:
974 items = list(self.items.values())
975 return {"available":self.available(),"agents":AGENTS,"models":MODELS,"default_model":DEFAULT_MODEL,
976 "default_root":self.default_root(),"revision":self.editor.revision,
977 "sessions":[s.summary() for s in items]}