llm-wf-core 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ include README.md
2
+ include llm_wf_core/ontology.ttl
3
+ global-exclude __pycache__ *.pyc .DS_Store
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: llm-wf-core
3
+ Version: 0.5.0
4
+ Summary: Moteur de workflow LLM basé sur des graphes d'agents (framework, sans interface)
5
+ Home-page: https://gitlab.univ-nantes.fr/desmontils-e/llm-workflow
6
+ Author: Emmanuel Desmontils
7
+ Author-email: emmanuel.desmontils@univ-nantes.fr
8
+ License: CeCILL-B
9
+ Project-URL: Source, https://gitlab.univ-nantes.fr/desmontils-e/llm-workflow
10
+ Project-URL: Bug Tracker, https://gitlab.univ-nantes.fr/desmontils-e/llm-workflow/-/issues
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.11.0
16
+ Description-Content-Type: text/markdown
17
+ Requires-Dist: pyyaml>=6.0
18
+ Requires-Dist: jinja2>=3.1.6
19
+ Requires-Dist: colorama>=0.4.6
20
+ Requires-Dist: openai>=2.9.0
21
+ Requires-Dist: h2>=4.1
22
+ Requires-Dist: anthropic>=0.84.0
23
+ Requires-Dist: ollama>=0.4.7
24
+ Requires-Dist: google-genai>=1.61.0
25
+ Requires-Dist: lmstudio>=1.5.0
26
+ Requires-Dist: requests>=2.31.0
27
+ Requires-Dist: pypdf>=4.0
28
+ Provides-Extra: memory
29
+ Requires-Dist: rdflib>=6.3; extra == "memory"
30
+ Dynamic: author
31
+ Dynamic: author-email
32
+ Dynamic: classifier
33
+ Dynamic: description
34
+ Dynamic: description-content-type
35
+ Dynamic: home-page
36
+ Dynamic: license
37
+ Dynamic: project-url
38
+ Dynamic: provides-extra
39
+ Dynamic: requires-dist
40
+ Dynamic: requires-python
41
+ Dynamic: summary
42
+
43
+ # llm-wf-core
44
+
45
+ Moteur de workflow LLM basé sur des graphes d'agents (DAG) : agents `chatbot` et `agent` (boucle d'outils), providers (Ollama, OpenAI, Anthropic, Google, ProxyIAg…), RAG, mémoire, sandbox. **Aucune interface** : à utiliser comme bibliothèque dans un autre projet.
46
+
47
+ ```python
48
+ from llm_wf_core import WorkflowAgent, WorkflowExecutor, WorkflowGraph, register_tool
49
+ ```
50
+
51
+ Agents et outils se définissent en code (`prompt_text`, `register_tool`) ; voir `examples/code_defined/` dans le dépôt. Le CLI, les applications et le serveur de TP sont dans `llm-wf-lab` ; `pip install llm-wf` installe les deux.
52
+
53
+ Dépôt : https://gitlab.univ-nantes.fr/desmontils-e/llm-workflow — licence CeCILL-B.
@@ -0,0 +1,11 @@
1
+ # llm-wf-core
2
+
3
+ Moteur de workflow LLM basé sur des graphes d'agents (DAG) : agents `chatbot` et `agent` (boucle d'outils), providers (Ollama, OpenAI, Anthropic, Google, ProxyIAg…), RAG, mémoire, sandbox. **Aucune interface** : à utiliser comme bibliothèque dans un autre projet.
4
+
5
+ ```python
6
+ from llm_wf_core import WorkflowAgent, WorkflowExecutor, WorkflowGraph, register_tool
7
+ ```
8
+
9
+ Agents et outils se définissent en code (`prompt_text`, `register_tool`) ; voir `examples/code_defined/` dans le dépôt. Le CLI, les applications et le serveur de TP sont dans `llm-wf-lab` ; `pip install llm-wf` installe les deux.
10
+
11
+ Dépôt : https://gitlab.univ-nantes.fr/desmontils-e/llm-workflow — licence CeCILL-B.
@@ -0,0 +1,45 @@
1
+ """
2
+ llm-wf — Moteur de workflow LLM basé sur des graphes d'agents.
3
+
4
+ Exécute des pipelines d'agents LLM connectés par leurs variables,
5
+ avec parallélisation automatique des agents indépendants.
6
+
7
+ Usage CLI : llmwf -w workflow.yaml -v var=valeur
8
+ """
9
+
10
+ from llm_wf_core.agent import WorkflowAgent
11
+ from llm_wf_core.agent_services import ToolError
12
+ from llm_wf_core.agent_tools import ToolResult, register_tool, unregister_tool
13
+ from llm_wf_core.config import WorkflowConfig
14
+ from llm_wf_core.diagram import export_diagram, generate_plantuml
15
+ from llm_wf_core.executor import WorkflowCancelled, WorkflowExecutor
16
+ from llm_wf_core.graph import WorkflowGraph
17
+ from llm_wf_core.loader import load_file
18
+ from llm_wf_core.memory import MemoryStore
19
+ from llm_wf_core.providers import LLMProvider, build_provider, escape_markdown
20
+
21
+ from importlib.metadata import version, PackageNotFoundError
22
+
23
+ try:
24
+ __version__ = version("llm-wf-core")
25
+ except PackageNotFoundError:
26
+ __version__ = "unknown"
27
+
28
+ __all__ = [
29
+ "WorkflowAgent",
30
+ "register_tool",
31
+ "unregister_tool",
32
+ "ToolError",
33
+ "ToolResult",
34
+ "WorkflowConfig",
35
+ "WorkflowCancelled",
36
+ "WorkflowExecutor",
37
+ "WorkflowGraph",
38
+ "MemoryStore",
39
+ "export_diagram",
40
+ "generate_plantuml",
41
+ "load_file",
42
+ "LLMProvider",
43
+ "build_provider",
44
+ "escape_markdown",
45
+ ]
@@ -0,0 +1,161 @@
1
+ import re
2
+ from dataclasses import dataclass, field
3
+
4
+ from llm_wf_core.agent_tools import TOOLS
5
+
6
+ AGENT_TYPES = ("llm", "agent")
7
+ MAX_STEPS_LIMIT = 100
8
+ MAX_DELEGATIONS_LIMIT = 50
9
+ _RAG_KEYS = frozenset({"base", "query", "top_k", "as"})
10
+ _IDENT_RE = re.compile(r"^[^\W\d]\w*$")
11
+ _DOMAIN_RE = re.compile(r"^(\*\.)?[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$")
12
+
13
+
14
+ @dataclass
15
+ class ToolCall:
16
+ """Appel d'outil demandé par le LLM (format neutre, indépendant du fournisseur)."""
17
+
18
+ id: str
19
+ name: str
20
+ args: dict
21
+
22
+
23
+ @dataclass
24
+ class Turn:
25
+ """Un tour de LLM dans une boucle d'agent : texte et/ou appels d'outils."""
26
+
27
+ text: str = ""
28
+ tool_calls: list[ToolCall] = field(default_factory=list)
29
+ usage: dict = field(default_factory=dict)
30
+ # Contenu natif de la réponse, à rejouer tel quel dans l'historique (ex. blocs `thinking` d'Anthropic,
31
+ # exigés pour poursuivre un tour d'outils). Opaque pour la boucle ; ignoré par les providers qui n'en ont pas besoin.
32
+ raw: object = None
33
+
34
+
35
+ @dataclass
36
+ class WorkflowAgent:
37
+ """
38
+ Un nœud du workflow : agent LLM avec son prompt et ses variables.
39
+
40
+ - 1 output → la réponse LLM brute est assignée à cette variable
41
+ - N outputs → le prompt doit retourner un JSON {"var1": "...", ...}
42
+
43
+ `type` :
44
+ - "llm" (défaut) : un appel unique au LLM ;
45
+ - "agent" : boucle d'outils (`tools`), au plus `max_steps` tours et `timeout` secondes au total.
46
+ """
47
+
48
+ id: str
49
+ prompt_file: str
50
+ service: str
51
+ model: str
52
+ url: str = "None"
53
+ api_key: str = "None"
54
+ inputs: list[str] = field(default_factory=list)
55
+ outputs: list[str] = field(default_factory=list)
56
+ type: str = "llm"
57
+ tools: list[str] = field(default_factory=list)
58
+ max_steps: int = 10
59
+ timeout: float = 300.0
60
+ # Options des agents : sorties lues dans des fichiers (variable → chemin dans l'espace de travail),
61
+ # domaines que fetch_url peut contacter, nombre d'appels de ask_model par exécution.
62
+ output_files: dict = field(default_factory=dict)
63
+ allowed_domains: list[str] = field(default_factory=list)
64
+ max_delegations: int = 5
65
+ # RAG (cf. rag.py). `rag` (chatbot ou agent) : récupération automatique avant l'appel, {base, query, top_k, as} ;
66
+ # `knowledge` (agent) : bases que l'outil search_knowledge peut interroger.
67
+ rag: dict = field(default_factory=dict)
68
+ knowledge: list[str] = field(default_factory=list)
69
+ # Définition en code : template Jinja2 du prompt donné directement (au lieu d'un fichier). Dans ce cas
70
+ # `prompt_file` reste vide (""). Les deux ensemble sont refusés.
71
+ prompt_text: str = ""
72
+
73
+ def __post_init__(self):
74
+ self._check_rag()
75
+ if not self.id:
76
+ raise ValueError("L'identifiant de l'agent ne peut pas être vide")
77
+ if self.prompt_file and self.prompt_text:
78
+ raise ValueError(f"Agent '{self.id}' : prompt_file et prompt_text sont exclusifs")
79
+ if not (self.prompt_file or self.prompt_text.strip()):
80
+ raise ValueError(f"Agent '{self.id}' : prompt_file (ou prompt_text) requis")
81
+ if not self.service:
82
+ raise ValueError(f"Agent '{self.id}' : service requis")
83
+ if not self.model:
84
+ raise ValueError(f"Agent '{self.id}' : model requis")
85
+ if not self.outputs:
86
+ raise ValueError(f"Agent '{self.id}' : outputs ne peut pas être vide")
87
+ if self.type not in AGENT_TYPES:
88
+ raise ValueError(
89
+ f"Agent '{self.id}' : type '{self.type}' inconnu (attendu : {', '.join(AGENT_TYPES)})"
90
+ )
91
+ if self.type == "llm":
92
+ for name, value in (("tools", self.tools), ("output_files", self.output_files),
93
+ ("allowed_domains", self.allowed_domains), ("knowledge", self.knowledge)):
94
+ if value:
95
+ raise ValueError(f"Agent '{self.id}' : '{name}' n'a de sens que pour type: agent")
96
+ return
97
+ if not self.tools:
98
+ raise ValueError(f"Agent '{self.id}' : un agent (type: agent) doit déclarer au moins un outil")
99
+ unknown = [t for t in self.tools if t not in TOOLS]
100
+ if unknown:
101
+ raise ValueError(
102
+ f"Agent '{self.id}' : outil(s) inconnu(s) {unknown} "
103
+ f"(disponibles : {', '.join(sorted(TOOLS))})"
104
+ )
105
+ if len(set(self.tools)) != len(self.tools):
106
+ raise ValueError(f"Agent '{self.id}' : outils dupliqués dans 'tools'")
107
+ if not isinstance(self.max_steps, int) or not 1 <= self.max_steps <= MAX_STEPS_LIMIT:
108
+ raise ValueError(f"Agent '{self.id}' : max_steps doit être un entier entre 1 et {MAX_STEPS_LIMIT}")
109
+ if not self.timeout or self.timeout <= 0:
110
+ raise ValueError(f"Agent '{self.id}' : timeout doit être positif")
111
+ if not isinstance(self.max_delegations, int) or not 1 <= self.max_delegations <= MAX_DELEGATIONS_LIMIT:
112
+ raise ValueError(f"Agent '{self.id}' : max_delegations doit être un entier entre 1 et {MAX_DELEGATIONS_LIMIT}")
113
+ # Sorties lues dans des fichiers de l'espace de travail
114
+ if not isinstance(self.output_files, dict):
115
+ raise ValueError(f"Agent '{self.id}' : output_files doit associer une variable à un chemin")
116
+ for var, rel in self.output_files.items():
117
+ if var not in self.outputs:
118
+ raise ValueError(f"Agent '{self.id}' : output_files « {var} » n'est pas l'une de ses sorties")
119
+ parts = str(rel).replace("\\", "/").split("/")
120
+ if not isinstance(rel, str) or not rel.strip() or rel.startswith("/") or ".." in parts:
121
+ raise ValueError(f"Agent '{self.id}' : chemin invalide pour output_files « {var} » "
122
+ f"(relatif à l'espace de travail, sans « .. »)")
123
+ if "submit_result" in self.tools and all(o in self.output_files for o in self.outputs):
124
+ raise ValueError(f"Agent '{self.id}' : submit_result a besoin d'au moins une sortie qui ne vient pas d'un fichier")
125
+ # Réseau : fetch_url ne contacte que des domaines déclarés (sans domaine, il refuse tout)
126
+ if self.allowed_domains and "fetch_url" not in self.tools:
127
+ raise ValueError(f"Agent '{self.id}' : allowed_domains n'a de sens qu'avec l'outil fetch_url")
128
+ if not isinstance(self.allowed_domains, list) or not all(
129
+ isinstance(d, str) and _DOMAIN_RE.match(d.strip()) for d in self.allowed_domains):
130
+ raise ValueError(f"Agent '{self.id}' : allowed_domains attend des noms de domaine "
131
+ f"(ex. example.org ou *.example.org), sans schéma ni chemin")
132
+ # Bases de connaissances : l'outil search_knowledge et la liste `knowledge` vont ensemble
133
+ if not isinstance(self.knowledge, list) or not all(isinstance(b, str) and b for b in self.knowledge):
134
+ raise ValueError(f"Agent '{self.id}' : 'knowledge' doit être une liste d'identifiants de bases")
135
+ if "search_knowledge" in self.tools and not self.knowledge:
136
+ raise ValueError(f"Agent '{self.id}' : search_knowledge exige 'knowledge' (ex. [cours])")
137
+ if self.knowledge and "search_knowledge" not in self.tools:
138
+ raise ValueError(f"Agent '{self.id}' : 'knowledge' n'a de sens qu'avec l'outil search_knowledge")
139
+ if len(set(self.knowledge)) != len(self.knowledge):
140
+ raise ValueError(f"Agent '{self.id}' : bases dupliquées dans 'knowledge'")
141
+
142
+ def _check_rag(self) -> None:
143
+ """Récupération automatique (`rag`), pour un chatbot comme pour un agent."""
144
+ if not self.rag:
145
+ return
146
+ r = self.rag
147
+ if not isinstance(r, dict) or set(r) - _RAG_KEYS:
148
+ raise ValueError(f"Agent '{self.id}' : 'rag' attend {{base, query, top_k, as}}")
149
+ if not isinstance(r.get("base"), str) or not r["base"]:
150
+ raise ValueError(f"Agent '{self.id}' : rag.base (identifiant de base de connaissances) requis")
151
+ if r.get("query") not in self.inputs:
152
+ raise ValueError(f"Agent '{self.id}' : rag.query doit être l'une des entrées de la tâche "
153
+ f"({', '.join(self.inputs) or 'aucune'})")
154
+ top_k = r.get("top_k")
155
+ if top_k is not None and (not isinstance(top_k, int) or isinstance(top_k, bool) or not 1 <= top_k <= 20):
156
+ raise ValueError(f"Agent '{self.id}' : rag.top_k doit être un entier entre 1 et 20")
157
+ name = r.get("as", "contexte")
158
+ if not isinstance(name, str) or not _IDENT_RE.match(name):
159
+ raise ValueError(f"Agent '{self.id}' : rag.as doit être un nom de variable valide")
160
+ if name in self.inputs or name in self.outputs:
161
+ raise ValueError(f"Agent '{self.id}' : rag.as « {name} » est déjà une entrée ou une sortie")
@@ -0,0 +1,205 @@
1
+ """
2
+ Boucle d'un nœud « agent » : le LLM appelle des outils, observe, recommence, puis répond.
3
+
4
+ La boucle ne connaît ni le provider, ni le retry, ni le circuit breaker : l'exécuteur lui fournit
5
+ `call_turn(messages, specs) -> Turn` (un tour de LLM déjà protégé). Les outils renvoient leurs erreurs au
6
+ LLM sous forme de texte (cf. `agent_tools.call_tool`) ; seule une défaillance du LLM lui-même remonte.
7
+
8
+ Limites : `agent.max_steps` tours, `agent.timeout` secondes pour l'ensemble (un appel LLM déjà parti n'est pas
9
+ interrompu). Si une limite est atteinte, un dernier tour avec `tool_choice="none"` (aucun appel d'outil permis)
10
+ demande la réponse finale.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import time
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass, field
19
+
20
+ from llm_wf_core.agent import Turn, WorkflowAgent
21
+ from llm_wf_core.agent_tools import Workspace, call_tool, tool_specs
22
+
23
+ TRACE_CHARS = 2000 # taille maximale d'un argument ou résultat dans la trace
24
+
25
+ MAX_REMINDERS = 2 # rappels envoyés à un agent qui s'apprête à conclure sans avoir fini son travail
26
+ SUBMIT_REMINDER = (
27
+ "Tu n'as pas remis ton résultat. Appelle maintenant l'outil submit_result, avec une valeur pour chacune de ces "
28
+ "sorties : {sorties}."
29
+ )
30
+ FILES_REMINDER = (
31
+ "Le fichier attendu comme sortie n'existe pas dans ton espace de travail : {fichiers}. Écris-le avec write_file"
32
+ "{suite}."
33
+ )
34
+
35
+ FINAL_REQUEST = (
36
+ "Limite atteinte ({raison}). Donne maintenant ta réponse finale à partir de ce qui a déjà été fait, "
37
+ "sans appeler d'outil."
38
+ )
39
+
40
+
41
+ @dataclass
42
+ class AgentLoopResult:
43
+ text: str
44
+ ended: str # "answer" | "submitted" (submit_result) | "max_steps" | "timeout"
45
+ steps: int = 0
46
+ tool_calls: int = 0
47
+ input_tokens: int = 0
48
+ output_tokens: int = 0
49
+ trace: str = "" # Markdown, pour --prompts-dir
50
+ workspace: str = ""
51
+ errors: list[str] = field(default_factory=list) # erreurs d'outils rencontrées (pour le diagnostic)
52
+
53
+
54
+ def _missing_output_files(agent: WorkflowAgent, workspace: Workspace) -> list[str]:
55
+ """Fichiers de sortie déclarés (`output_files`) que l'agent n'a pas produits."""
56
+ missing = []
57
+ for rel in agent.output_files.values():
58
+ try:
59
+ if not workspace.resolve(rel).is_file():
60
+ missing.append(rel)
61
+ except Exception:
62
+ missing.append(rel)
63
+ return missing
64
+
65
+
66
+ def _exit_reminder(agent: WorkflowAgent, workspace: Workspace, submitted: bool) -> str | None:
67
+ """Rappel à envoyer à un agent qui s'apprête à conclure alors que son travail n'est pas fini : résultat non
68
+ remis avec submit_result, ou fichier de sortie absent. None si tout est en ordre."""
69
+ parts = []
70
+ if "submit_result" in agent.tools and not submitted:
71
+ parts.append(SUBMIT_REMINDER.format(sorties=", ".join(workspace.services.outputs)))
72
+ missing = _missing_output_files(agent, workspace)
73
+ if missing:
74
+ suite = " ; si tu avais déjà remis ton résultat, rappelle submit_result ensuite" if "submit_result" in agent.tools else ""
75
+ parts.append(FILES_REMINDER.format(fichiers=", ".join(missing), suite=suite))
76
+ return " ".join(parts) or None
77
+
78
+
79
+ def _clip(text: str, limit: int = TRACE_CHARS) -> str:
80
+ return text if len(text) <= limit else text[:limit] + f"\n[… {len(text) - limit} caractère(s) omis]"
81
+
82
+
83
+ def _fmt_args(args) -> str:
84
+ try:
85
+ return json.dumps(args, ensure_ascii=False, indent=1) if isinstance(args, dict) else repr(args)
86
+ except (TypeError, ValueError):
87
+ return repr(args)
88
+
89
+
90
+ def run_agent_loop(
91
+ agent: WorkflowAgent,
92
+ system_prompt: str,
93
+ user_prompt: str,
94
+ workspace: Workspace,
95
+ call_turn: Callable[[list[dict], list[dict], str], Turn],
96
+ check_cancelled: Callable[[], None] = lambda: None,
97
+ on_step: Callable[[dict], None] | None = None,
98
+ clock: Callable[[], float] = time.monotonic,
99
+ ) -> AgentLoopResult:
100
+ specs = tool_specs(agent.tools, workspace.services)
101
+ messages: list[dict] = [{"role": "user", "content": user_prompt}]
102
+ deadline = clock() + agent.timeout
103
+ res = AgentLoopResult(text="", ended="max_steps", workspace=str(workspace.root))
104
+ trace = [f"# Trace de l'agent `{agent.id}`\n",
105
+ f"Modèle : {agent.service}/{agent.model} — outils : {', '.join(agent.tools)} — "
106
+ f"max_steps={agent.max_steps}, timeout={agent.timeout:g} s\n",
107
+ f"Espace de travail : `{workspace.root}`\n"]
108
+
109
+ def account(turn: Turn) -> None:
110
+ res.input_tokens += turn.usage.get("input_tokens", 0) or 0
111
+ res.output_tokens += turn.usage.get("output_tokens", 0) or 0
112
+
113
+ reminders = 0
114
+ for step in range(1, agent.max_steps + 1):
115
+ check_cancelled()
116
+ if clock() >= deadline + workspace.services.paused: # l'attente de l'utilisateur n'use pas le délai
117
+ res.ended = "timeout"
118
+ break
119
+
120
+ turn = call_turn(messages, specs, "auto")
121
+ res.steps = step
122
+ account(turn)
123
+ trace.append(f"\n## Tour {step}\n")
124
+ if turn.text.strip():
125
+ trace.append(f"**Assistant** :\n\n{_clip(turn.text)}\n")
126
+
127
+ messages.append({"role": "assistant", "text": turn.text, "tool_calls": turn.tool_calls, "raw": turn.raw})
128
+ if not turn.tool_calls:
129
+ reminder = _exit_reminder(agent, workspace, workspace.services.submitted is not None)
130
+ if reminder and reminders < MAX_REMINDERS:
131
+ # L'agent conclut en texte alors qu'il doit remettre ses sorties avec submit_result, ou sans avoir
132
+ # écrit un fichier de sortie : sans ce rappel, le moteur échouerait plus loin avec un message
133
+ # trompeur (« aucun JSON trouvé », « fichier introuvable »).
134
+ reminders += 1
135
+ trace.append("\n*Conclusion prématurée : rappel envoyé à l'agent.*\n")
136
+ messages.append({"role": "user", "content": reminder})
137
+ continue
138
+ res.text, res.ended = turn.text, "answer"
139
+ trace.append("\n*Réponse finale.*\n")
140
+ break
141
+
142
+ for call in turn.tool_calls:
143
+ res.tool_calls += 1
144
+ if clock() >= deadline + workspace.services.paused:
145
+ content, is_error = "Non exécuté : délai global de l'agent dépassé.", True
146
+ else:
147
+ r = call_tool(workspace, call.name, call.args, agent.tools)
148
+ content, is_error = r.content, r.is_error
149
+ if is_error:
150
+ res.errors.append(f"{call.name} : {content.splitlines()[0] if content else ''}")
151
+ trace.append(
152
+ f"\n### Appel `{call.name}`{' — ERREUR' if is_error else ''}\n\n"
153
+ f"Arguments :\n~~~~json\n{_clip(_fmt_args(call.args))}\n~~~~\n\n"
154
+ f"Résultat :\n~~~~\n{_clip(content)}\n~~~~\n"
155
+ )
156
+ messages.append({"role": "tool", "tool_call_id": call.id, "name": call.name,
157
+ "content": content, "is_error": is_error})
158
+ if on_step:
159
+ on_step({"step": step, "tool": call.name, "error": is_error})
160
+ submitted = workspace.services.submitted
161
+ if submitted is not None and _missing_output_files(agent, workspace) and reminders < MAX_REMINDERS:
162
+ # Résultat remis mais un fichier de sortie manque : on rouvre la remise, l'agent doit d'abord l'écrire.
163
+ reminders += 1
164
+ workspace.services.submitted = None
165
+ trace.append("\n*Résultat remis sans le fichier de sortie : rappel envoyé à l'agent.*\n")
166
+ messages.append({"role": "user", "content": FILES_REMINDER.format(
167
+ fichiers=", ".join(_missing_output_files(agent, workspace)),
168
+ suite=" ; rappelle ensuite submit_result")})
169
+ continue
170
+ if submitted is not None: # submit_result : le travail est remis, pas besoin d'un tour de plus
171
+ res.text = next(iter(submitted.values())) if len(submitted) == 1 else json.dumps(submitted, ensure_ascii=False)
172
+ res.ended = "submitted"
173
+ trace.append("\n*Résultat remis par submit_result.*\n")
174
+ break
175
+ else:
176
+ res.ended = "max_steps"
177
+
178
+ if res.ended not in ("answer", "submitted"):
179
+ raison = (f"{agent.max_steps} tours" if res.ended == "max_steps"
180
+ else f"délai de {agent.timeout:g} s")
181
+ trace.append(f"\n## Limite atteinte ({raison}) : demande de réponse finale\n")
182
+ check_cancelled()
183
+ messages.append({"role": "user", "content": FINAL_REQUEST.format(raison=raison)})
184
+ turn = call_turn(messages, specs, "none") # outils décrits (l'historique en contient) mais interdits
185
+ account(turn)
186
+ res.text = turn.text
187
+ trace.append(f"{_clip(turn.text) or '(aucune réponse)'}\n")
188
+ if not turn.text.strip():
189
+ res.trace = "".join(trace)
190
+ raise AgentLimitError(
191
+ f"l'agent '{agent.id}' n'a pas produit de réponse finale ({raison} atteint)", res
192
+ )
193
+
194
+ trace.append(f"\n---\n{res.steps} tour(s), {res.tool_calls} appel(s) d'outil, "
195
+ f"{res.input_tokens} tokens en entrée, {res.output_tokens} en sortie.\n")
196
+ res.trace = "".join(trace)
197
+ return res
198
+
199
+
200
+ class AgentLimitError(RuntimeError):
201
+ """Limite atteinte sans réponse finale ; `result` garde la trace pour le diagnostic."""
202
+
203
+ def __init__(self, message: str, result: AgentLoopResult):
204
+ super().__init__(message)
205
+ self.result = result