BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / agents / chat_run.rs

chat_run.rs

chat_run.rs 3.4 KiB Download Raw
1use agents::{
2 ChatMessage, ChatReply, McpEndpoint, RunEvent, RunOutcome, RunStatus, RunUpdate, ToolSpec,
3 next_turn,
4};
5use tokio::sync::{mpsc, oneshot};
6
7use mcp::{ListedTool, ToolSession};
8
9const SYSTEM: &str = "You help with one Teams message. Use the tools to read what you need and to propose a reply or a reaction. You never send anything yourself.";
10const ROUNDS: usize = 8;
11
12pub async fn run_chat(
13 profile: agents::AgentProfile,
14 prompt: String,
15 endpoint: Option<McpEndpoint>,
16 events: mpsc::UnboundedSender<RunUpdate>,
17 mut stop: oneshot::Receiver<()>,
18) -> RunOutcome {
19 let session = match endpoint {
20 Some(endpoint) => {
21 match ToolSession::connect(&mcp::McpEndpoint {
22 url: endpoint.url,
23 token: endpoint.token,
24 })
25 .await
26 {
27 Ok(session) => Some(session),
28 Err(error) => {
29 let _ = events.send(RunUpdate::Event(RunEvent::Step(format!(
30 "MCP tools unavailable: {error}"
31 ))));
32 None
33 }
34 }
35 }
36 None => None,
37 };
38 let specs = match &session {
39 Some(session) => session
40 .tools()
41 .await
42 .unwrap_or_default()
43 .into_iter()
44 .map(spec)
45 .collect(),
46 None => Vec::new(),
47 };
48 let mut messages = vec![ChatMessage::user(prompt)];
49 let mut stop_armed = true;
50 for _ in 0..ROUNDS {
51 let turn = tokio::select! {
52 biased;
53 result = &mut stop, if stop_armed => {
54 if result.is_ok() {
55 return RunOutcome { status: RunStatus::Stopped, exit_code: None };
56 }
57 stop_armed = false;
58 continue;
59 }
60 turn = next_turn(&profile, SYSTEM, &messages, &specs) => turn,
61 };
62 match turn {
63 Err(message) => return failed(message),
64 Ok(ChatReply::Text(text)) => {
65 let _ = events.send(RunUpdate::Event(RunEvent::Text(text.clone())));
66 return RunOutcome {
67 status: RunStatus::Completed { final_text: text },
68 exit_code: None,
69 };
70 }
71 Ok(ChatReply::Tools { text, calls }) => {
72 messages.push(ChatMessage::assistant(text, calls.clone()));
73 for call in calls {
74 let _ = events.send(RunUpdate::Event(RunEvent::Step(call.name.clone())));
75 let result = match &session {
76 Some(session) => session
77 .call(&call.name, &call.arguments)
78 .await
79 .unwrap_or_else(|error| error),
80 None => "tools are not available".to_owned(),
81 };
82 messages.push(ChatMessage::tool(call.id, result));
83 }
84 }
85 }
86 }
87 failed("stopped after too many tool calls".to_owned())
88}
89
90fn spec(tool: ListedTool) -> ToolSpec {
91 ToolSpec {
92 name: tool.name,
93 description: tool.description,
94 parameters: tool.parameters,
95 }
96}
97
98fn failed(message: String) -> RunOutcome {
99 RunOutcome {
100 status: RunStatus::Failed {
101 message,
102 stderr_tail: Vec::new(),
103 },
104 exit_code: None,
105 }
106}