poe2-agent 0.2.1

AI agent for Path of Exile 2 build analysis
Documentation
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! ReAct-style tool-calling agent for build analysis.
//!
//! Uses OpenAI function calling to query PoB data on demand
//! rather than dumping everything into the system prompt upfront.

use std::sync::Arc;

use futures_core::Stream;

use crate::llm::{
    ChatGptClient, FunctionDefinition, LlmError, Message, ToolDefinition,
};
use crate::pob_parser::{PobParser, PobQuery};

const MAX_TOOL_ROUNDS: usize = 10;

const SYSTEM_PROMPT: &str = "\
You are a Path of Exile 2 build analysis assistant. The user has uploaded \
their Path of Building export.\n\
\n\
You have tools to inspect the build data. Use them to answer the user's \
questions accurately — do NOT guess at numbers.\n\
\n\
Start by calling get_build_stats to get an overview of the build's offense, \
defense, and resources. Then use get_skill_list or get_config if needed \
to answer the user's specific question.\n\
\n\
Use get_empty_slots to quickly scan all equipment slots and see which ones \
are empty and which have items equipped. This is useful for identifying \
obvious upgrade opportunities — empty slots mean free power. Call this \
before diving into individual items with get_item.\n\
\n\
Use get_item to inspect a specific equipment slot when the user asks about \
their gear, an item's mods, or how a particular slot could be upgraded. \
Do not call get_item unless the question is about specific equipment.\n\
\n\
Use get_passive_tree when the user asks about their passive tree, allocated \
nodes, keystones, notables, ascendancy choices, masteries, or jewel sockets. \
It returns all allocated nodes categorized by type.\n\
\n\
Use get_jewel to inspect a jewel socketed in a passive tree socket. First call \
get_passive_tree to get the jewel_sockets list with node IDs, then call \
get_jewel with the node_id to see the jewel's name, base, rarity, and mods.\n\
\n\
Use query_passive_stats to find how much of a specific stat comes from allocated \
passives and what's available nearby on the tree. Provide a stat pattern like \
\"fire damage\" or \"maximum life\". Optionally set radius (default 3) to control \
how far to search from current allocation.\n\
\n\
Use get_unallocated_ascendancy to see which ascendancy nodes the character has \
allocated and which are still available. Returns both primary and secondary \
ascendancy nodes with node names, types, and stats. Use this when recommending \
ascendancy choices or when the user asks what ascendancy nodes to take next.\n\
\n\
Be specific and reference actual numbers from the build data when relevant. \
If the data doesn't contain enough information to answer, say so.\n\
\n\
Path of Exile 2 differences from Path of Exile 1 — do NOT confuse these:\n\
- There are NO utility flasks. Players have 2 flask slots (life/mana style only).\n\
- Charms (3 slots) provide passive bonuses and trigger effects — they replace \
much of what utility flasks did in PoE1.\n\
- Spirit is a resource that reserves for persistent buffs, auras, and minions.\n\
- Gear does NOT have gem sockets. Skill gems are equipped independently in \
dedicated active-gem slots, each with support sockets.\n\
- Rune sockets on gear provide bonus stats (via socketed runes).\n\
- Do NOT reference PoE1-specific unique items, support gems, or league mechanics.\n\
- When recommending items, gems, or tree nodes, verify they exist using the \
available tools rather than relying on memory.";

/// A single turn from a prior conversation. Text only — no tool calls.
#[derive(Debug, Clone)]
pub struct ChatMessage {
    pub role: String,
    pub content: String,
}

/// Events yielded by the agent during a response.
pub enum AgentEvent {
    /// The agent is calling a tool (yields tool name for progress indication).
    ToolCall { name: String },
    /// A token of the final streamed response.
    Token(String),
}

/// Tool-calling build analysis agent.
///
/// Wraps an LLM client and a shared PoB parser. Each call to `respond`
/// runs a ReAct loop: the LLM decides which tools to call, the agent
/// executes them via the parser, and the results are fed back until
/// the LLM produces a final answer.
pub struct ToolAgent {
    llm: ChatGptClient,
    parser: Arc<PobParser>,
}

impl ToolAgent {
    pub fn new(llm: ChatGptClient, parser: Arc<PobParser>) -> Self {
        Self { llm, parser }
    }

    /// Stream a response to a user question about the given build.
    ///
    /// `build_xml` is the raw PoB XML export. The agent loads it into PoB
    /// on each tool call so queries always reflect the full build.
    pub fn respond(
        &self,
        build_xml: &[u8],
        message: &str,
        history: Vec<ChatMessage>,
    ) -> impl Stream<Item = Result<AgentEvent, LlmError>> + Send {
        let llm = self.llm.clone();
        let parser = Arc::clone(&self.parser);
        let build_xml = build_xml.to_vec();
        let message = message.to_owned();

        async_stream::try_stream! {
            let tools = tool_definitions();
            let mut messages = vec![Message::system(SYSTEM_PROMPT)];
            for msg in history {
                match msg.role.as_str() {
                    "user" => messages.push(Message::user(&msg.content)),
                    "assistant" => messages.push(Message::assistant(&msg.content)),
                    _ => {}
                }
            }
            messages.push(Message::user(message));

            // Tool-calling loop: let the LLM call tools until it has
            // enough data, then break to stream the final answer.
            let mut tools_were_called = false;

            for _ in 0..MAX_TOOL_ROUNDS {
                let (assistant_msg, finish_reason) = llm
                    .chat_with_tools(messages.clone(), Some(&tools))
                    .await?;

                let reason = finish_reason.as_deref().unwrap_or("stop");

                if reason != "tool_calls" {
                    if !tools_were_called {
                        // LLM answered directly without tools — yield its text.
                        if let Some(text) = assistant_msg.content {
                            yield AgentEvent::Token(text);
                        }
                        return;
                    }
                    // Tools were used in a prior round; break to stream.
                    break;
                }

                if let Some(ref tool_calls) = assistant_msg.tool_calls {
                    tools_were_called = true;

                    for tc in tool_calls {
                        yield AgentEvent::ToolCall {
                            name: tc.function.name.clone(),
                        };
                    }

                    messages.push(assistant_msg.clone());

                    for tc in tool_calls {
                        let result = execute_tool(&parser, &build_xml, &tc.function.name, &tc.function.arguments).await;
                        let content = match result {
                            Ok(val) => val.to_string(),
                            Err(e) => format!("{{\"error\": \"{e}\"}}"),
                        };
                        messages.push(Message::tool_result(&tc.id, content));
                    }
                }
            }

            // Stream the final answer so tokens arrive progressively.
            let stream = llm.chat_stream(messages);
            tokio::pin!(stream);
            while let Some(token_result) = futures_lite::StreamExt::next(&mut stream).await {
                yield AgentEvent::Token(token_result?);
            }
        }
    }
}

/// Build the tool definitions for the agent.
fn tool_definitions() -> Vec<ToolDefinition> {
    vec![
        ToolDefinition {
            tool_type: "function".to_owned(),
            function: FunctionDefinition {
                name: "get_build_stats".to_owned(),
                description: "Get extended build statistics including offense, defense, \
                    resources, speed, and charges. Returns ~40 fields grouped by category."
                    .to_owned(),
                parameters: serde_json::json!({
                    "type": "object",
                    "properties": {},
                    "required": [],
                    "additionalProperties": false
                }),
            },
        },
        ToolDefinition {
            tool_type: "function".to_owned(),
            function: FunctionDefinition {
                name: "get_skill_list".to_owned(),
                description: "Get the list of skills with their DPS values, trigger info, \
                    and gem links (socket groups with gems, levels, and quality)."
                    .to_owned(),
                parameters: serde_json::json!({
                    "type": "object",
                    "properties": {},
                    "required": [],
                    "additionalProperties": false
                }),
            },
        },
        ToolDefinition {
            tool_type: "function".to_owned(),
            function: FunctionDefinition {
                name: "get_config".to_owned(),
                description: "Get the build's configuration flags (enemy settings, \
                    charge generation, conditions, etc.)."
                    .to_owned(),
                parameters: serde_json::json!({
                    "type": "object",
                    "properties": {},
                    "required": [],
                    "additionalProperties": false
                }),
            },
        },
        ToolDefinition {
            tool_type: "function".to_owned(),
            function: FunctionDefinition {
                name: "get_item".to_owned(),
                description: "Retrieve the item equipped in a specific gear slot, including \
                    its name, base type, rarity, and all mod lines (implicit, explicit, \
                    enchant, rune)."
                    .to_owned(),
                parameters: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "slot": {
                            "type": "string",
                            "enum": [
                                "Weapon 1", "Weapon 2", "Helmet", "Body Armour",
                                "Gloves", "Boots", "Amulet", "Ring 1", "Ring 2", "Ring 3",
                                "Belt", "Charm 1", "Charm 2", "Charm 3",
                                "Flask 1", "Flask 2"
                            ],
                            "description": "The equipment slot to inspect"
                        }
                    },
                    "required": ["slot"],
                    "additionalProperties": false
                }),
            },
        },
        ToolDefinition {
            tool_type: "function".to_owned(),
            function: FunctionDefinition {
                name: "get_empty_slots".to_owned(),
                description: "Scan all equipment slots and return which are empty and which \
                    have items equipped. Returns item name and rarity for filled slots. \
                    Useful for quickly identifying missing gear without calling get_item \
                    for every slot."
                    .to_owned(),
                parameters: serde_json::json!({
                    "type": "object",
                    "properties": {},
                    "required": [],
                    "additionalProperties": false
                }),
            },
        },
        ToolDefinition {
            tool_type: "function".to_owned(),
            function: FunctionDefinition {
                name: "get_jewel".to_owned(),
                description: "Retrieve a jewel socketed in a passive tree socket, including \
                    its name, base type, rarity, and all mod lines. Use socket node IDs \
                    from get_passive_tree's jewel_sockets array."
                    .to_owned(),
                parameters: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "node_id": {
                            "type": "integer",
                            "description": "The passive tree socket node ID (from get_passive_tree jewel_sockets)"
                        }
                    },
                    "required": ["node_id"],
                    "additionalProperties": false
                }),
            },
        },
        ToolDefinition {
            tool_type: "function".to_owned(),
            function: FunctionDefinition {
                name: "get_passive_tree".to_owned(),
                description: "Get the allocated passive tree nodes, grouped by type: \
                    keystones, notables, ascendancy nodes, masteries, and jewel sockets. \
                    Also returns class, ascendancy, and total allocated node count."
                    .to_owned(),
                parameters: serde_json::json!({
                    "type": "object",
                    "properties": {},
                    "required": [],
                    "additionalProperties": false
                }),
            },
        },
        ToolDefinition {
            tool_type: "function".to_owned(),
            function: FunctionDefinition {
                name: "query_passive_stats".to_owned(),
                description: "Query how much of a specific stat comes from allocated passive \
                    tree nodes, and how much more is available on nearby unallocated nodes. \
                    Uses case-insensitive pattern matching on stat descriptions."
                    .to_owned(),
                parameters: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "stat": {
                            "type": "string",
                            "description": "Stat pattern to search for (e.g. \"fire damage\", \"maximum life\", \"critical strike\")"
                        },
                        "radius": {
                            "type": "integer",
                            "description": "How many hops from allocated nodes to search for nearby stats (default: 3)"
                        }
                    },
                    "required": ["stat"],
                    "additionalProperties": false
                }),
            },
        },
        ToolDefinition {
            tool_type: "function".to_owned(),
            function: FunctionDefinition {
                name: "get_unallocated_ascendancy".to_owned(),
                description: "Get the character's ascendancy nodes — both allocated and \
                    available — for primary and secondary ascendancies. Returns node names, \
                    types, stats, and points spent. Use this to recommend which ascendancy \
                    nodes to take next."
                    .to_owned(),
                parameters: serde_json::json!({
                    "type": "object",
                    "properties": {},
                    "required": [],
                    "additionalProperties": false
                }),
            },
        },
    ]
}

/// Execute a single tool call via the PoB parser.
async fn execute_tool(
    parser: &PobParser,
    build_xml: &[u8],
    tool_name: &str,
    tool_args: &str,
) -> Result<serde_json::Value, String> {
    let query = match tool_name {
        "get_build_stats" => PobQuery::BuildStats,
        "get_skill_list" => PobQuery::SkillList,
        "get_config" => PobQuery::Config,
        "get_item" => {
            let args: serde_json::Value =
                serde_json::from_str(tool_args).map_err(|e| format!("invalid arguments: {e}"))?;
            let slot = args["slot"]
                .as_str()
                .ok_or("missing required parameter: slot")?
                .to_owned();
            PobQuery::Item(slot)
        }
        "get_empty_slots" => PobQuery::EmptySlots,
        "get_jewel" => {
            let args: serde_json::Value =
                serde_json::from_str(tool_args).map_err(|e| format!("invalid arguments: {e}"))?;
            let node_id = args["node_id"]
                .as_i64()
                .ok_or("missing required parameter: node_id")?;
            PobQuery::Jewel(node_id)
        }
        "get_passive_tree" => PobQuery::PassiveTree,
        "query_passive_stats" => {
            let args: serde_json::Value =
                serde_json::from_str(tool_args).map_err(|e| format!("invalid arguments: {e}"))?;
            let stat = args["stat"]
                .as_str()
                .ok_or("missing required parameter: stat")?
                .to_owned();
            let radius = args["radius"].as_u64().unwrap_or(3) as u32;
            PobQuery::PassiveStats { stat, radius }
        }
        "get_unallocated_ascendancy" => PobQuery::UnallocatedAscendancy,
        other => return Err(format!("unknown tool: {other}")),
    };

    parser
        .query(build_xml, query)
        .await
        .map_err(|e| e.to_string())
}