Repository navigation
Add the Session API crate #1593
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
bd7863d
39460bf
e76258c
7bd04d9
01eac79
1e79ba6
94e8c2d
96d387d
5637b84
662c238
94c3a3b
925a049
a3d4c13
1cbb509
b344981
673f061
821e405
3e80c94
668a2e7
b8c2b61
cd02a39
ce27505
e810c78
57ecc70
9240097
75a16ce
2c9bc28
279430d
74c9a5b
1163192
c099316
bd572b8
8d23ac7
8fb6d40
50da432
810281d
e288351
22a30ef
527eb25
15cb834
20f290c
bcb88fd
cc01f83
608ed5c
b8dada0
4c38411
9900be5
977a6fb
9627dab
7903b02
cdb6e42
e20fd1c
1a93849
1e1c931
67e30df
0fe9b1a
ec460af
63c8d71
3af5b3c
12011d7
84c198a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| livekit-session: minor | ||
| --- | ||
|
|
||
| Add the `livekit-session` crate, whose `Session` fetches credentials from a token source, connects a room, publishes the platform microphone and plays the agent's audio by default (`SessionOptions::with_platform_audio`), projects the agent's state (`AgentState`) into a `watch` channel, and merges chat and transcripts into one message feed, with a README and an `examples/session` voice and text chat. |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| [package] | ||
| name = "session" | ||
| version = "0.1.0" | ||
| edition.workspace = true | ||
| publish = false | ||
|
|
||
| [dependencies] | ||
| clap = { workspace = true, features = ["derive", "env"] } | ||
| env_logger = { workspace = true } | ||
| futures-util = { workspace = true } | ||
| livekit-session = { workspace = true, features = ["rustls-tls-native-roots"] } | ||
| livekit-token-source = { workspace = true } | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: At present, users must manually depend on // lib.rs
pub use livekit;
pub use livekit_token_source;@1egoman, curious your thoughts here.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is a good point to consider. I am a bit conflicted though, in other places to solve this type of problem (ie, a "peer dependency") I've seen places where standard practice seems to dictate that keeping multiple packages in sync via version to be what people recommend. I've never really liked this pattern though and think it is really easy to cause things to break. I think if we went down this path, then there would be a natural push for people going forward to do Other idea: expose a # Cargo.toml
livekit = { version = "0.10", features = ["session"] } // A user's main.rs
use livekit::session::Session;
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Investigating options here: https://linear.app/livekit/issue/CLT-3705/investigate-feature-flag-option-for-dependency-chain
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We decide to for now leave the import up to the devs, considering re-export or a feature solutions till but we don't want to block this PR. |
||
| tokio = { workspace = true, features = ["full"] } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| # Session | ||
|
|
||
| A conversation with a LiveKit agent, built on `livekit-session`. The microphone is published and | ||
| the agent's audio is played through platform audio, with echo cancellation, so no headphones are | ||
| needed. Lines typed on stdin are sent to the agent as well; the agent's replies, what you say once | ||
| transcribed, and state changes are printed as they arrive. | ||
|
|
||
| Credentials come from a [development token server](https://docs.livekit.io/frontends/build/authentication/development-token-server/), | ||
| which also dispatches the agent: | ||
|
|
||
| ```bash | ||
| LIVEKIT_TOKEN_SERVER_ID=<token server id> LIVEKIT_AGENT_NAME=<agent name> cargo run -p session | ||
| ``` | ||
|
|
||
| Or from a pre-generated token, whose room configuration dispatches the agent: | ||
|
|
||
| ```bash | ||
| LIVEKIT_URL=wss://<project>.livekit.cloud LIVEKIT_TOKEN=<token> cargo run -p session | ||
| ``` | ||
|
|
||
| Every variable also has a flag (`--token-server-id`, `--agent-name`, `--url`, `--token`); see | ||
| `cargo run -p session -- --help`. | ||
|
|
||
| Pass `--text` to leave the audio devices alone and talk by typing only, e.g. on a machine without | ||
| a microphone. The agent then needs to accept text input. | ||
|
|
||
| ```bash | ||
| cargo run -p session -- --text | ||
| ``` | ||
|
|
||
| Close stdin (Ctrl-D) to end the session. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| use std::error::Error; | ||
| use std::time::Duration; | ||
|
|
||
| use clap::Parser; | ||
| use futures_util::StreamExt; | ||
| use livekit_session::{ | ||
| Message, MessageOrigin, Session, SessionEvent, SessionOptions, SessionState, | ||
| }; | ||
|
|
||
| use livekit_token_source::{development_token_server, literal, TokenSourceFetchOptions}; | ||
| use tokio::io::{AsyncBufReadExt, BufReader}; | ||
|
|
||
| /// A conversation with a LiveKit agent over voice and typed text | ||
| #[derive(Parser, Debug)] | ||
| #[command(author, version, about, long_about = None)] | ||
| struct Args { | ||
| /// LiveKit server URL, used together with --token | ||
| #[arg(long, env = "LIVEKIT_URL")] | ||
| url: Option<String>, | ||
|
|
||
| /// Pre-generated token whose room configuration dispatches the agent | ||
| #[arg(long, env = "LIVEKIT_TOKEN", hide_env_values = true)] | ||
| token: Option<String>, | ||
|
|
||
| /// Development token server ID, used when no URL and token are given | ||
| #[arg(long, env = "LIVEKIT_TOKEN_SERVER_ID")] | ||
| token_server_id: Option<String>, | ||
|
|
||
| /// Agent for the development token server to dispatch | ||
| #[arg(long, env = "LIVEKIT_AGENT_NAME")] | ||
| agent_name: Option<String>, | ||
|
|
||
| /// Leave the audio devices alone and talk by typing only | ||
| #[arg(long)] | ||
| text: bool, | ||
| } | ||
|
|
||
| /// Creates session options with credentials from a pre-generated token if one | ||
| /// is given, and from a development token server otherwise. | ||
| fn create_options(args: Args) -> Result<SessionOptions, Box<dyn Error>> { | ||
| if let (Some(url), Some(token)) = (args.url, args.token) { | ||
| return Ok(SessionOptions::new_fixed_source(literal(url, token))); | ||
| } | ||
| let token_server_id = args | ||
| .token_server_id | ||
| .ok_or("pass --token-server-id, or --url and --token (or set the LIVEKIT_* variables)")?; | ||
| let mut fetch_options = TokenSourceFetchOptions::new(); | ||
| if let Some(agent_name) = args.agent_name { | ||
| fetch_options = fetch_options.with_agent_name(agent_name); | ||
| } | ||
| Ok(SessionOptions::new_configurable_source( | ||
| development_token_server(token_server_id), | ||
| fetch_options, | ||
| )) | ||
| } | ||
|
|
||
| /// Prints a message once it is complete. The user's own input is skipped, as | ||
| /// it is already on screen. | ||
| fn print_message(message: &Message) { | ||
| if !message.is_final { | ||
| return; | ||
| } | ||
| let speaker = match message.origin { | ||
| MessageOrigin::AgentTranscript => "agent", | ||
| MessageOrigin::UserTranscript => "you (transcribed)", | ||
| MessageOrigin::UserInput => return, | ||
| _ => message.participant_identity.as_str(), | ||
| }; | ||
| println!("{speaker}: {}", message.text); | ||
| } | ||
|
|
||
| fn print_state(state: &SessionState) { | ||
| println!("[{:?}, agent {:?}]", state.connection, state.agent); | ||
| } | ||
|
|
||
| #[tokio::main] | ||
| async fn main() -> Result<(), Box<dyn Error>> { | ||
| env_logger::init(); | ||
| let args = Args::parse(); | ||
|
|
||
| // By default the session captures the microphone and plays the agent's | ||
| // audio, with echo cancellation between the two. `--text` keeps the | ||
| // conversation to typed lines, e.g. on a machine without audio devices. | ||
| let text = args.text; | ||
| let session_options = create_options(args)? | ||
| .with_agent_connect_timeout(Duration::from_secs(15)) | ||
| .with_platform_audio(!text); | ||
| let session = Session::new(session_options); | ||
| let mut events = session.subscribe(); | ||
| session.start().await?; | ||
|
|
||
| // `changed` reports only later updates, so print where the session starts. | ||
| let mut state = session.state(); | ||
| print_state(&state.borrow_and_update()); | ||
| let mut lines = BufReader::new(tokio::io::stdin()).lines(); | ||
| loop { | ||
| tokio::select! { | ||
| changed = state.changed() => { | ||
| if changed.is_err() { | ||
| break; | ||
| } | ||
| let current = state.borrow_and_update().clone(); | ||
| println!("{:?}", session); | ||
| if !current.connection.is_connected() { | ||
| break; | ||
| } | ||
| } | ||
| Some(event) = events.next() => { | ||
| if let SessionEvent::MessageUpserted(message) = event { | ||
| print_message(&message); | ||
| } | ||
| } | ||
| line = lines.next_line() => match line? { | ||
| Some(line) if line.trim().is_empty() => {} | ||
| Some(line) => { | ||
| if let Err(err) = session.send_text(line.trim()).await { | ||
| eprintln!("failed to send: {err}"); | ||
| } | ||
| } | ||
| None => break, | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| session.end().await; | ||
| Ok(()) | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| [package] | ||
| name = "livekit-session" | ||
| description = "Agent sessions for the LiveKit Rust SDK" | ||
| version = "0.0.0" | ||
| license.workspace = true | ||
| edition.workspace = true | ||
| repository.workspace = true | ||
| readme = "README.md" | ||
|
|
||
| [features] | ||
| default = ["native"] | ||
|
|
||
| # Backend and TLS pass-throughs, forwarded to both the room connection | ||
| # (livekit) and the token fetch (livekit-token-source). | ||
| native = ["livekit/native", "livekit-token-source/native"] | ||
| native-tls = ["livekit/native-tls", "livekit-token-source/native-tls"] | ||
| native-tls-vendored = ["livekit/native-tls-vendored", "livekit-token-source/native-tls-vendored"] | ||
| rustls-tls-native-roots = [ | ||
| "livekit/rustls-tls-native-roots", | ||
| "livekit-token-source/rustls-tls-native-roots", | ||
| ] | ||
| rustls-tls-webpki-roots = [ | ||
| "livekit/rustls-tls-webpki-roots", | ||
| "livekit-token-source/rustls-tls-webpki-roots", | ||
| ] | ||
|
|
||
| # End-to-end tests against a running `livekit-server --dev`. | ||
| __lk-e2e-test = [] | ||
|
|
||
| # How CI checks this crate's features, read by | ||
| # `.github/workflows/feature-combinations-curated.yml` via `cargo metadata`. | ||
| # See the equivalent table in `livekit/Cargo.toml` for the encoding. | ||
| # | ||
| # Curated rather than a powerset: every TLS feature is forwarded to `livekit`, | ||
| # so most powerset entries rebuild `livekit` underneath, and depth 2 would | ||
| # spend 22 checks mostly on two TLS backends at once or `__lk-e2e-test` paired | ||
| # with something unrelated, which nobody can select. The TLS forwards | ||
| # themselves are covered by `livekit`'s own list. | ||
| [package.metadata.feature-combinations] | ||
| mode = "curated" | ||
| check = [ | ||
| ["default"], # a plain `cargo check` | ||
| [], # --no-default-features | ||
| ["native", "rustls-tls-webpki-roots"], | ||
| ["default", "rustls-tls-native-roots"], # defaults *plus* one | ||
| ] | ||
|
|
||
| [dependencies] | ||
| futures-util = { workspace = true, features = ["std"] } | ||
| livekit = { workspace = true } | ||
| livekit-token-source = { workspace = true } | ||
|
MaxHeimbrock marked this conversation as resolved.
Resolved
|
||
| log = { workspace = true } | ||
| thiserror = { workspace = true } | ||
| tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } | ||
| tokio-stream = { workspace = true, features = ["sync"] } | ||
|
|
||
| [dev-dependencies] | ||
| anyhow = { workspace = true } | ||
| async-trait = "0.1" | ||
| livekit-api = { workspace = true } | ||
| livekit-protocol = { workspace = true } | ||
| livekit-token = { workspace = true } | ||
| tokio = { workspace = true, features = ["io-util", "macros", "net", "rt-multi-thread", "sync", "time"] } | ||
Uh oh!
There was an error while loading. Please reload this page.