aboutsummaryrefslogtreecommitdiffstats
path: root/src/agent.rs
blob: 2d84566027efd7df50b34b671ef8491c47036bc4 (plain) (blame)
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
use std::sync::atomic::AtomicBool;

use serde_json::{json, Value};

use crate::config::Config;
use crate::provider::{self, Error, Outcome, Sink};

/// Frozen for the life of the process. Anything session-varying added here
/// invalidates the provider's prompt cache, so keep it boring.
pub fn system_message() -> Value {
    json!({
        "role": "system",
        "content": "You are agent686, a coding agent working in a Unix terminal. \
                    You edit files and run commands. Be terse and do not explain \
                    what you are about to do before doing it."
    })
}

/// Appends the user message, runs one provider round trip, and appends the
/// assistant message to the history whether or not it asked for tools.
pub fn run_turn(
    cfg: &Config,
    history: &mut Vec<Value>,
    prompt: &str,
    cancel: &AtomicBool,
    sink: &mut dyn Sink,
) -> Result<Outcome, Error> {
    history.push(json!({ "role": "user", "content": prompt }));

    let outcome = provider::chat(cfg, history, cancel, sink)?;

    let mut message = serde_json::Map::new();
    message.insert("role".into(), json!("assistant"));
    message.insert(
        "content".into(),
        if outcome.content.is_empty() {
            Value::Null
        } else {
            json!(outcome.content)
        },
    );
    if !outcome.tool_calls.is_empty() {
        let calls: Vec<Value> = outcome
            .tool_calls
            .iter()
            .map(|call| {
                json!({
                    "id": call.id,
                    "type": "function",
                    "function": {
                        "name": call.name,
                        // Byte-for-byte what the model sent.
                        "arguments": call.arguments,
                    }
                })
            })
            .collect();
        message.insert("tool_calls".into(), Value::Array(calls));
    }
    history.push(Value::Object(message));

    Ok(outcome)
}

pub fn new_history() -> Vec<Value> {
    vec![system_message()]
}