Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8abf0e316 | ||
|
|
39a184e5d0 | ||
|
|
9d166e35ba | ||
|
|
4a5966401c | ||
|
|
d92dfba2bf | ||
|
|
8538d6b2b8 | ||
|
|
23f763ba72 | ||
|
|
a9e4ab1bdb | ||
|
|
d9a045a5e4 | ||
|
|
393be9be5a | ||
|
|
a7b016a3d3 | ||
|
|
85e66406dc | ||
|
|
db9422740c | ||
|
|
90fbad5b64 | ||
|
|
b40226826f | ||
|
|
b89f0db71a |
34
CHANGELOG.md
34
CHANGELOG.md
@@ -1,8 +1,38 @@
|
||||
# (2024-11-19) Version 1.4.0
|
||||
|
||||
- (**Improvement**) Dependency updates. This version is based on [mxlink](https://crates.io/crates/mxlink)@1.4.0 (which is based on the newly released [matrix-sdk](https://crates.io/crates/matrix-sdk)@[0.8.0](https://github.com/matrix-org/matrix-rust-sdk/releases/tag/matrix-sdk-0.8.0)). Once you run this version at least once and your matrix-sdk datastore gets upgraded to the new schema, **you will not be able to downgrade to older baibot versions** (based on the older matrix-sdk), unless you start with an empty datastore.
|
||||
|
||||
- (**Bugfix**) Add missing typing notices sending functionality while generating images ([9d166e35ba](https://github.com/etkecc/baibot/commit/9d166e35ba6fc0daaf69318870e92436f3302056))
|
||||
|
||||
|
||||
# (2024-11-12) Version 1.3.2
|
||||
|
||||
Dependency updates.
|
||||
|
||||
|
||||
# (2024-10-03) Version 1.3.1
|
||||
|
||||
- (**Improvement**) Improves fallback user mentions support for old clients (like Element iOS) which use the bot's display name (not its full Matrix User ID). ([d9a045a5e4](https://github.com/etkecc/baibot/commit/d9a045a5e41d2b99694f92ec9e90f47529546d89))
|
||||
|
||||
|
||||
# (2024-10-03) Version 1.3.0
|
||||
|
||||
**TLDR**: you can now use OpenAI's [o1](https://platform.openai.com/docs/models/o1) models, benefit from [prompt caching](https://platform.openai.com/docs/guides/prompt-caching) and mention the bot again from old clients lacking proper [user mentions support](https://spec.matrix.org/latest/client-server-api/#user-and-room-mentions) (like Element iOS).
|
||||
|
||||
- (**Feature**) Introduces a new `baibot_conversation_start_time_utc` [prompt variable](./docs/configuration/text-generation.md#️-prompt-override) which is not a moving target (like the `baibot_now_utc` variable) and allows [prompt caching](https://platform.openai.com/docs/guides/prompt-caching) to work. All default/sample configs have been adjusted to make use of this new variable, but users need to adjust your existing dynamically-created agents to start using it. ([85e66406dc](https://github.com/etkecc/baibot/commit/85e66406dc6f430741c7819f420e2df4ae6e8d3b))
|
||||
|
||||
- (**Improvement**) Allows for the `max_response_tokens` configuration value for the [OpenAI provider](./docs/providers.md#openai) to be set to `null` to allow [o1](https://platform.openai.com/docs/models/o1) models (which do not support `max_response_tokens`) to be used. See the new o1 sample config [here](./docs/sample-provider-configs/openai-o1.yml). ([db9422740c](https://github.com/etkecc/baibot/commit/db9422740ceca32956d9628b6326b8be206344e2))
|
||||
|
||||
- (**Improvement**) Switches the sample configs for the [OpenAI provider](./docs/providers.md#openai) to point to the `gpt-4o` model, which since 2024-10-02 is the same as the `gpt-4o-2024-08-06` model. We previously explicitly pointed the bot to the `gpt-4o-2024-08-06` model, because it was much better (longer context window). Now that `gpt-4o` points to the same powerful model, we don't need to pin its version anymore. Existing users may wish to adjust their configuration to match. ([90fbad5b64](https://github.com/etkecc/baibot/commit/90fbad5b643cd06c23179f055a309ec6a7cba161))
|
||||
|
||||
- (**Bugfix**) Restores fallback user mentions support (via regular text, not via the [user mentions spec](https://spec.matrix.org/latest/client-server-api/#user-and-room-mentions)) to allow certain old clients (like Element iOS) to be able to mention the bot again. Support for this was intentionally removed recently (in [v1.2.0](#2024-10-01-version-120)), but it turned out to be too early to do this. ([b40226826f](https://github.com/etkecc/baibot/commit/b40226826fe914d0d5d265230ebc5bac8058b6f7))
|
||||
|
||||
|
||||
# (2024-10-01) Version 1.2.0
|
||||
|
||||
- (**Feature**) Adds support for [on-demand involvement](./docs/usage.md#on-demand-involvement) of the bot (via mention) in arbitrary threads and reply chains ([9908512968](https://github.com/etkecc/baibot/commit/990851296828168c2106eb3f4668833e9e5a7463)) - fixes [issue #15](https://github.com/etkecc/baibot/issues/15)
|
||||
- (**Feature**) Adds support for [on-demand involvement](./docs/features.md#on-demand-involvement) of the bot (via mention) in arbitrary threads and reply chains ([9908512968](https://github.com/etkecc/baibot/commit/990851296828168c2106eb3f4668833e9e5a7463)) - fixes [issue #15](https://github.com/etkecc/baibot/issues/15)
|
||||
|
||||
- (**Feature**) Simplifies [Transcribe-only mode](./docs/features.md#transcribe-only-mode) reply format (removing `> 🦻` prefixing) to allow easier forwarding, etc. ([e6aa956423](https://github.com/etkecc/baibot/commit/e6aa95642376ee7d87932d0e66dcfedf261b188b)) - fixes [issue #14](https://github.com/etkecc/baibot/issues/14)
|
||||
- (**Improvement**) Simplifies [Transcribe-only mode](./docs/features.md#transcribe-only-mode) reply format (removing `> 🦻` prefixing) to allow easier forwarding, etc. ([e6aa956423](https://github.com/etkecc/baibot/commit/e6aa95642376ee7d87932d0e66dcfedf261b188b)) - fixes [issue #14](https://github.com/etkecc/baibot/issues/14)
|
||||
|
||||
- (**Bugfix**) Fixes speech-to-text replies rendering incorrectly in certain clients, due to them confusing our old reply format with [fallback for rich replies](https://spec.matrix.org/v1.11/client-server-api/#fallbacks-for-rich-replies) ([e6aa956423](https://github.com/etkecc/baibot/commit/e6aa95642376ee7d87932d0e66dcfedf261b188b)) - fixes [issue #17](https://github.com/etkecc/baibot/issues/17)
|
||||
|
||||
|
||||
672
Cargo.lock
generated
672
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
14
Cargo.toml
14
Cargo.toml
@@ -7,7 +7,7 @@ license = "AGPL-3.0-or-later"
|
||||
readme = "README.md"
|
||||
keywords = ["matrix", "chat", "bot", "AI", "LLM"]
|
||||
include = ["/etc/assets/baibot-torso-768.png", "/src", "/README.md", "/CHANGELOG.md", "/LICENSE"]
|
||||
version = "1.2.0"
|
||||
version = "1.4.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
@@ -17,22 +17,22 @@ path = "src/lib.rs"
|
||||
[dependencies]
|
||||
anthropic-rs = "0.1.*"
|
||||
anyhow = "1.0.*"
|
||||
async-openai = "0.24.*"
|
||||
async-openai = "0.26.*"
|
||||
base64 = "0.22.*"
|
||||
chrono = { version = "0.4.*", default-features = false, features = ["std", "now"] }
|
||||
# We'd rather not depend on this, but we cannot use the ruma-events EventContent macro without it.
|
||||
matrix-sdk = { version = "0.7.1", default-features = false }
|
||||
matrix-sdk = { version = "0.8.0", default-features = false }
|
||||
mxidwc = "1.0.*"
|
||||
mxlink = ">=1.3.0"
|
||||
mxlink = ">=1.4.0"
|
||||
etke_openai_api_rust = "0.1.*"
|
||||
quick_cache = "0.6.*"
|
||||
regex = "1.11.*"
|
||||
serde = { version = "1.0.*", features = ["derive"], default-features = false }
|
||||
serde_json = "1.0.*"
|
||||
serde_yaml = "0.9.*"
|
||||
tempfile = "3.13.*"
|
||||
tiktoken-rs = { version = "0.5.*", features = ["async-openai"] }
|
||||
tokio = { version = "1.40.*", features = ["rt", "rt-multi-thread", "macros"] }
|
||||
tempfile = "3.14.*"
|
||||
tiktoken-rs = { version = "0.6.*", features = ["async-openai"] }
|
||||
tokio = { version = "1.41.*", features = ["rt", "rt-multi-thread", "macros"] }
|
||||
tracing = "0.1.*"
|
||||
tracing-subscriber = { version = "0.3.*", features = ["env-filter"] }
|
||||
url = "2.5.*"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
# #
|
||||
#######################################
|
||||
|
||||
FROM docker.io/rust:1.81.0-slim-bookworm AS build
|
||||
FROM docker.io/rust:1.82.0-slim-bookworm AS build
|
||||
|
||||
RUN apt-get update && apt-get install -y build-essential pkg-config libssl-dev libsqlite3-dev
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
# #
|
||||
#######################################
|
||||
|
||||
FROM docker.io/rust:1.81.0-slim-bookworm AS build
|
||||
FROM docker.io/rust:1.82.0-slim-bookworm AS build
|
||||
|
||||
RUN apt-get update && apt-get install -y build-essential pkg-config libssl-dev libsqlite3-dev
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ Users:
|
||||
|
||||
- ✅ can **invite the bot to rooms**
|
||||
- ✅ can **use all the bot's [features](./features.md)** ([💬 Text Generation](./features.md#-text-generation), [🦻 Speech-to-Text](./features.md#-speech-to-text), etc.) by sending room messages
|
||||
- ✅ can **mention the bot** in threads and reply chains to provoke it to respond to non-user messages (see [📖 Usage / 💬 Text Generation / On-demand involvement](./usage.md#on-demand-involvement))
|
||||
- ✅ can **mention the bot** in threads and reply chains to provoke it to respond to non-user messages (see [🌟 Features / 💬 Text Generation / On-demand involvement](./features.md#on-demand-involvement))
|
||||
- ✅ can **change the bot's configuration in a room** (e.g. `!bai config room ...` commands)
|
||||
- ❌ cannot **change the bot's global configuration** (e.g. `!bai config global ...` commands)
|
||||
- ❌ cannot **create new [🤖 Agents](./agents.md)** (neither in rooms, nor globally). See [💼 Room-local agent managers](#-room-local-agent-managers) for controlling which users can create agents.
|
||||
|
||||
@@ -77,11 +77,14 @@ Prompts may contain the following **placeholder variables** which will be replac
|
||||
|---------------------------|-------------|---------|
|
||||
| `{{ baibot_name }}` | Name of the bot as configured in the `user.name` field in the [Static configuration](./README.md#static-configuration) | `Baibot` |
|
||||
| `{{ baibot_model_id }}` | Text-Generation model ID as configured in the [🤖 agent](../agents.md)'s configuration | `gpt-4o` |
|
||||
| `{{ baibot_now_utc }}` | Current date and time in UTC | `2024-09-20 (Friday), 14:26:42 UTC` |
|
||||
| `{{ baibot_now_utc }}` | Current date and time in UTC (⚠️ usage may break prompt caching - see below) | `2024-09-20 (Friday), 14:26:42 UTC` |
|
||||
| `{{ baibot_conversation_start_time_utc }}` | The date and time in UTC that the conversation started | `2024-09-20 (Friday), 14:26:42 UTC` |
|
||||
|
||||
💡 `{{ baibot_now_utc }}` changes as time goes on, which prevents [prompt caching](https://platform.openai.com/docs/guides/prompt-caching) from working. It's better to use `{{ baibot_conversation_start_time_utc }}` in prompts, as its value doesn't change yet still orients the bot to the current date/time.
|
||||
|
||||
Here's a prompt that combines some of the above variables:
|
||||
|
||||
> You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
> You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
|
||||
|
||||
### 🌡️ Temperature Override
|
||||
|
||||
@@ -28,7 +28,7 @@ Text Generation is the bot's ability to **respond to users' text messages with t
|
||||
|
||||
In multi-user (group) rooms, to avoid disturbing the normal conversation between people, the bot is auto-configured to only respond to messages starting with the command prefix (`!bai`) or direct mentions via the [💬 Text Generation / 🗟 Prefix Requirement Type](./configuration/text-generation.md#-prefix-requirement-type) setting.
|
||||
|
||||
Normally, the bot only responds to allowed [👥 Users](./access.md#-users). In certain cases, it's useful for an allowed user to provoke the bot to respond even in foreign threads or reply chains. You can learn more about this feature in the [📖 Usage / 💬 Text Generation / On-demand involvement](./usage.md#on-demand-involvement) section.
|
||||
Normally, the bot only responds to allowed [👥 Users](./access.md#-users). In certain cases, it's useful for an allowed user to provoke the bot to respond even in foreign threads or reply chains. You can learn more about this feature in the [On-demand involvement](./features.md#on-demand-involvement) section below.
|
||||
|
||||
A few other features (like [🗣️ Text-to-Speech](#️-text-to-speech) and [🦻 Speech-to-Text](#-speech-to-text)) combine well with Text Generation, so you **don't necessarily need to communicate with the bot via text** (with [Seamless voice interaction](#seamless-voice-interaction), you can communicate only with voice).
|
||||
|
||||
@@ -38,6 +38,22 @@ You may also wish to see:
|
||||
- [📖 Usage / 💬 Text Generation](./usage.md#-text-generation) section for more details on how to use the bot for Text Generation in a room
|
||||
|
||||
|
||||
#### On-demand involvement
|
||||
|
||||
In the following 2 cases, it's useful to involve the bot in conversations on-demand:
|
||||
|
||||
1. In multi-user rooms (with the [🗟 Prefix Requirement](./configuration/text-generation.md#-prefix-requirement-type) setting set to "required")
|
||||
2. In rooms with foreign users (users that are not authorized bot [👥 users](./access.md#-users))
|
||||
|
||||
In these instances, an allowed [👥 user](./access.md#-users) can also provoke the bot to respond to **any** thread or reply chain by [mentioning](https://spec.matrix.org/latest/client-server-api/#user-and-room-mentions) the bot (e.g. `@baibot Hello!`). The following screenshots demonstrate this behavior:
|
||||
|
||||
- [🖼️ On-demand involvement in the room](./screenshots/text-generation-prefix-requirement.webp)
|
||||
- [🖼️ On-demand involvement in a thread](./screenshots/text-generation-on-demand-thread-involvement.webp) (the Alice user in this example is not an allowed user, yet her messages are still considered as part of the conversation context)
|
||||
- [🖼️ On-demand involvement in a reply chain](./screenshots/text-generation-on-demand-reply-involvement.webp) (the Alice user in this example is not an allowed user, yet her messages are still considered as part of the conversation context)
|
||||
|
||||
💡 **NOTE**: Normally, the bot **only considers messages from allowed [👥 Users](./access.md#-users)** and ignores all other messages when responding. However, **when the bot is explicitly invoked (via mention)** in a thread or reply chain, **it will consider all messages** in the thread and reply chain (even those from foreign users) as part of the conversation context.
|
||||
|
||||
|
||||
### 🗣️ Text-to-Speech
|
||||
|
||||
Text-to-Speech is the bot's ability to **turn text messages into voice messages**.
|
||||
|
||||
@@ -125,7 +125,10 @@ For services which are not fully compatible with the OpenAI API, consider using
|
||||
- create a room-local agent: `!bai agent create-room-local openai my-openai-agent`
|
||||
- create a global agent: `!bai agent create-global openai my-openai-agent`
|
||||
|
||||
💡 When creating an agent, the bot will show you an up-to-date sample configuration for this provider which looks [like this](./sample-provider-configs/openai.yml).
|
||||
💡 When creating an agent, the bot will show you an up-to-date sample configuration for this provider which:
|
||||
|
||||
- in the general case looks [like this](./sample-provider-configs/openai.yml)
|
||||
- for the [o1](https://platform.openai.com/docs/models/o1) models needs to look [like this](./sample-provider-configs/openai-o1.yml)
|
||||
|
||||
|
||||
### OpenAI Compatible
|
||||
|
||||
@@ -2,7 +2,7 @@ base_url: https://api.anthropic.com/v1
|
||||
api_key: YOUR_API_KEY_HERE
|
||||
text_generation:
|
||||
model_id: claude-3-5-sonnet-20240620
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
temperature: 1.0
|
||||
max_response_tokens: 8192
|
||||
max_context_tokens: 204800
|
||||
|
||||
@@ -2,7 +2,7 @@ base_url: https://api.groq.com/openai/v1
|
||||
api_key: YOUR_API_KEY_HERE
|
||||
text_generation:
|
||||
model_id: llama3-70b-8192
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
temperature: 1.0
|
||||
max_response_tokens: 4096
|
||||
max_context_tokens: 131072
|
||||
|
||||
@@ -2,7 +2,7 @@ base_url: http://my-localai-self-hosted-service:8080/v1
|
||||
api_key: YOUR_API_KEY_HERE
|
||||
text_generation:
|
||||
model_id: gpt-4
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
temperature: 1.0
|
||||
max_response_tokens: 4096
|
||||
max_context_tokens: 128000
|
||||
|
||||
@@ -2,7 +2,7 @@ base_url: https://api.mistral.ai/v1
|
||||
api_key: YOUR_API_KEY_HERE
|
||||
text_generation:
|
||||
model_id: mistral-large-latest
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
temperature: 1.0
|
||||
max_response_tokens: 4096
|
||||
max_context_tokens: 128000
|
||||
|
||||
@@ -2,7 +2,7 @@ base_url: http://my-ollama-self-hosted-service:11434/v1
|
||||
api_key: YOUR_API_KEY_HERE
|
||||
text_generation:
|
||||
model_id: gemma2:2b
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
temperature: 1.0
|
||||
max_response_tokens: 4096
|
||||
max_context_tokens: 128000
|
||||
|
||||
@@ -2,7 +2,7 @@ base_url: ''
|
||||
api_key: YOUR_API_KEY_HERE
|
||||
text_generation:
|
||||
model_id: some-model
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
temperature: 1.0
|
||||
max_response_tokens: 4096
|
||||
max_context_tokens: 128000
|
||||
|
||||
24
docs/sample-provider-configs/openai-o1.yml
Normal file
24
docs/sample-provider-configs/openai-o1.yml
Normal file
@@ -0,0 +1,24 @@
|
||||
base_url: https://api.openai.com/v1
|
||||
api_key: YOUR_API_KEY_HERE
|
||||
text_generation:
|
||||
model_id: o1-mini
|
||||
# o1 models do not support a system prompt
|
||||
prompt: null
|
||||
temperature: 1.0
|
||||
# o1 models do not support max_response_tokens.
|
||||
# They use `max_completion_tokens` as an alternative,
|
||||
# but we don't support it yet (see https://github.com/64bit/async-openai/issues/272).
|
||||
max_response_tokens: null
|
||||
max_context_tokens: 128000
|
||||
speech_to_text:
|
||||
model_id: whisper-1
|
||||
text_to_speech:
|
||||
model_id: tts-1-hd
|
||||
voice: onyx
|
||||
speed: 1.0
|
||||
response_format: opus
|
||||
image_generation:
|
||||
model_id: dall-e-3
|
||||
style: vivid
|
||||
size: 1024x1024
|
||||
quality: standard
|
||||
@@ -1,8 +1,8 @@
|
||||
base_url: https://api.openai.com/v1
|
||||
api_key: YOUR_API_KEY_HERE
|
||||
text_generation:
|
||||
model_id: gpt-4o-2024-08-06
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
model_id: gpt-4o
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
temperature: 1.0
|
||||
max_response_tokens: 16384
|
||||
max_context_tokens: 128000
|
||||
|
||||
@@ -2,7 +2,7 @@ base_url: https://openrouter.ai/api/v1
|
||||
api_key: YOUR_API_KEY_HERE
|
||||
text_generation:
|
||||
model_id: mattshumer/reflection-70b:free
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
temperature: 1.0
|
||||
max_response_tokens: 2048
|
||||
max_context_tokens: 8192
|
||||
|
||||
@@ -2,7 +2,7 @@ base_url: https://api.together.xyz/v1
|
||||
api_key: YOUR_API_KEY_HERE
|
||||
text_generation:
|
||||
model_id: meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
temperature: 1.0
|
||||
max_response_tokens: 2048
|
||||
max_context_tokens: 8192
|
||||
|
||||
@@ -15,7 +15,7 @@ See screenshots of:
|
||||
|
||||
- 🖼️ [the default Text Generation flow](./screenshots/text-generation.webp) in 1:1 rooms
|
||||
- 🖼️ [the Text Generation flow in multi-user rooms](./screenshots/text-generation-prefix-requirement.webp) (where the [🗟 Prefix Requirement](./configuration/text-generation.md#-prefix-requirement-type) setting is auto-configured to "required")
|
||||
- [on-demand involvement](#on-demand-involvement)
|
||||
- the [on-demand involvement](./features.md#on-demand-involvement) feature
|
||||
|
||||
Whether the bot responds depends on:
|
||||
|
||||
@@ -25,27 +25,12 @@ Whether the bot responds depends on:
|
||||
|
||||
- (🎨 agent capabilities) whether the configured `text-generation` (or `catch-all`) handler agent actually supports text-generation. The provider may lack support for this feature or it may be disabled in the [🤖 agents](./agents.md) configuration
|
||||
|
||||
- (the [🗟 Prefix Requirement](./configuration/text-generation.md#-prefix-requirement-type) setting) whether a prefix (e.g. `!bai`) or user mention (e.g. `@baibot`) is required for messages sent to the room. For multi-user rooms, this setting defaults to "required". See [on-demand involvement](#on-demand-involvement) for details.
|
||||
- (the [🗟 Prefix Requirement](./configuration/text-generation.md#-prefix-requirement-type) setting) whether a prefix (e.g. `!bai`) or user mention (e.g. `@baibot`) is required for messages sent to the room. For multi-user rooms, this setting defaults to "required". See [🌟 Features / 💬 Text Generation / On-demand involvement](./features.md#on-demand-involvement) for details.
|
||||
|
||||
Room messages start a threaded conversation where you can continue back-and-forth communication with the bot.
|
||||
Room messages start a threaded conversation where you can continue back-and-forth communication with the bot. Using [on-demand involvement](./features.md#on-demand-involvement), you can can also mention the bot to provoke it to get involved in any conversation thread or reply chain.
|
||||
|
||||
Unless you've enabled the [♻️ Context Management](./features.md#️-context-management) feature, all messages will be sent to the agent's API each time. If the context management feature is enabled, older messages may be dropped.
|
||||
|
||||
#### On-demand involvement
|
||||
|
||||
In the following 2 cases, it's useful to involve the bot in conversations on-demand:
|
||||
|
||||
1. For multi-user rooms (with the [🗟 Prefix Requirement](./configuration/text-generation.md#-prefix-requirement-type) setting set to "required")
|
||||
2. In rooms with foreign users (users that are not authorized bot [👥 users](./access.md#-users))
|
||||
|
||||
In these instances, an allowed [👥 user](./access.md#-users) can also provoke the bot to respond to **any** thread or reply chain by [mentioning](https://spec.matrix.org/latest/client-server-api/#user-and-room-mentions) the bot (e.g. `@baibot Hello!`). The following screenshots demonstrate this behavior:
|
||||
|
||||
- [🖼️ On-demand involvement in the room](./screenshots/text-generation-prefix-requirement.webp)
|
||||
- [🖼️ On-demand involvement in a thread](./screenshots/text-generation-on-demand-thread-involvement.webp) (the Alice user in this example is not an allowed user, yet her messages are still considered as part of the conversation context)
|
||||
- [🖼️ On-demand involvement in a reply chain](./screenshots/text-generation-on-demand-reply-involvement.webp) (the Alice user in this example is not an allowed user, yet her messages are still considered as part of the conversation context)
|
||||
|
||||
💡 **NOTE**: Normally, the bot **only considers messages from allowed [👥 Users](./access.md#-users)** and ignores all other messages when responding. However, **when the bot is explicitly invoked (via mention)** in a thread or reply chain, **it will consider all messages** in the thread and reply chain (even those from foreign users) as part of the conversation context.
|
||||
|
||||
|
||||
### 🗣️ Text-to-Speech
|
||||
|
||||
|
||||
@@ -72,8 +72,8 @@ agents:
|
||||
# base_url: https://api.openai.com/v1
|
||||
# api_key: ""
|
||||
# text_generation:
|
||||
# model_id: gpt-4o-2024-08-06
|
||||
# prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
# model_id: gpt-4o
|
||||
# prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
# temperature: 1.0
|
||||
# max_response_tokens: 16384
|
||||
# max_context_tokens: 128000
|
||||
@@ -97,7 +97,7 @@ agents:
|
||||
# api_key: null
|
||||
# text_generation:
|
||||
# model_id: gpt-4
|
||||
# prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
# prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
# temperature: 1.0
|
||||
# max_response_tokens: 16384
|
||||
# max_context_tokens: 128000
|
||||
@@ -122,7 +122,7 @@ agents:
|
||||
# api_key: null
|
||||
# text_generation:
|
||||
# model_id: "gemma2:2b"
|
||||
# prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
# prompt: "You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
# temperature: 1.0
|
||||
# max_response_tokens: 4096
|
||||
# max_context_tokens: 128000
|
||||
|
||||
@@ -13,7 +13,7 @@ services:
|
||||
- /etc/passwd:/etc/passwd:ro
|
||||
|
||||
synapse:
|
||||
image: ghcr.io/element-hq/synapse:v1.116.0
|
||||
image: ghcr.io/element-hq/synapse:v1.118.0
|
||||
user: "${UID}:${GID}"
|
||||
restart: unless-stopped
|
||||
entrypoint: python
|
||||
@@ -26,7 +26,7 @@ services:
|
||||
- ./synapse/media-store:/media-store
|
||||
|
||||
element-web:
|
||||
image: docker.io/vectorim/element-web:v1.11.79
|
||||
image: docker.io/vectorim/element-web:v1.11.84
|
||||
user: "${UID}:${GID}"
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
services:
|
||||
ollama:
|
||||
image: docker.io/ollama/ollama:0.3.11
|
||||
image: docker.io/ollama/ollama:0.4.1
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${SERVICE_OLLAMA_BIND_PORT_HTTP}:11434"
|
||||
|
||||
@@ -21,5 +21,5 @@ pub use provider::{AgentProvider, AgentProviderInfo, ControllerTrait};
|
||||
pub use purpose::AgentPurpose;
|
||||
|
||||
pub(super) fn default_prompt() -> &'static str {
|
||||
"You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time now is: {{ baibot_now_utc }}."
|
||||
"You are a brief, but helpful bot called {{ baibot_name }} powered by the {{ baibot_model_id }} model. The date/time of this conversation's start is: {{ baibot_conversation_start_time_utc }}."
|
||||
}
|
||||
|
||||
@@ -72,6 +72,7 @@ impl ControllerTrait for Controller {
|
||||
let messages = vec![LLMMessage {
|
||||
author: LLMAuthor::User,
|
||||
message_text: "Hello!".to_string(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
}];
|
||||
|
||||
let conversation = LLMConversation { messages };
|
||||
@@ -108,6 +109,7 @@ impl ControllerTrait for Controller {
|
||||
Some(LLMMessage {
|
||||
author: LLMAuthor::Prompt,
|
||||
message_text: prompt_text,
|
||||
timestamp: chrono::Utc::now(),
|
||||
})
|
||||
};
|
||||
|
||||
@@ -129,7 +131,7 @@ impl ControllerTrait for Controller {
|
||||
&text_generation_config.model_id,
|
||||
&prompt_message,
|
||||
conversation_messages,
|
||||
text_generation_config.max_response_tokens,
|
||||
Some(text_generation_config.max_response_tokens),
|
||||
text_generation_config.max_context_tokens,
|
||||
);
|
||||
|
||||
|
||||
@@ -7,17 +7,33 @@ pub struct TextGenerationPromptVariables {
|
||||
|
||||
impl Default for TextGenerationPromptVariables {
|
||||
fn default() -> Self {
|
||||
Self::new("unnamed", "unknown-model", Utc::now())
|
||||
let now = Utc::now();
|
||||
Self::new("unnamed", "unknown-model", now, Some(now))
|
||||
}
|
||||
}
|
||||
|
||||
impl TextGenerationPromptVariables {
|
||||
pub fn new(bot_name: &str, model_id: &str, utc_time: DateTime<Utc>) -> Self {
|
||||
pub fn new(
|
||||
bot_name: &str,
|
||||
model_id: &str,
|
||||
now_time: DateTime<Utc>,
|
||||
conversation_start_time: Option<DateTime<Utc>>,
|
||||
) -> Self {
|
||||
let mut map = HashMap::new();
|
||||
|
||||
map.insert("baibot_name".to_string(), bot_name.to_string());
|
||||
map.insert("baibot_model_id".to_string(), model_id.to_string());
|
||||
map.insert("baibot_now_utc".to_string(), format_utc_time(utc_time));
|
||||
map.insert("baibot_now_utc".to_string(), format_utc_time(now_time));
|
||||
|
||||
let baibot_conversation_start_time_utc = match conversation_start_time {
|
||||
Some(conversation_start_time) => format_utc_time(conversation_start_time),
|
||||
None => "unknown".to_string(),
|
||||
};
|
||||
|
||||
map.insert(
|
||||
"baibot_conversation_start_time_utc".to_string(),
|
||||
baibot_conversation_start_time_utc,
|
||||
);
|
||||
|
||||
Self { map }
|
||||
}
|
||||
@@ -52,7 +68,18 @@ mod tests {
|
||||
.with_nanosecond(250000000)
|
||||
.unwrap();
|
||||
|
||||
let variables = TextGenerationPromptVariables::new("baibot", "gpt-4o", now_utc);
|
||||
let conversation_start_time_utc = Utc
|
||||
.with_ymd_and_hms(2024, 9, 19, 18, 34, 15)
|
||||
.unwrap()
|
||||
.with_nanosecond(250000000)
|
||||
.unwrap();
|
||||
|
||||
let variables = TextGenerationPromptVariables::new(
|
||||
"baibot",
|
||||
"gpt-4o",
|
||||
now_utc,
|
||||
Some(conversation_start_time_utc),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
variables.map.get("baibot_name"),
|
||||
@@ -66,9 +93,13 @@ mod tests {
|
||||
variables.map.get("baibot_now_utc"),
|
||||
Some(&format_utc_time(now_utc))
|
||||
);
|
||||
assert_eq!(
|
||||
variables.map.get("baibot_conversation_start_time_utc"),
|
||||
Some(&format_utc_time(conversation_start_time_utc))
|
||||
);
|
||||
|
||||
let prompt = "Hello, I'm {{ baibot_name }} using {{ baibot_model_id }}. The date/time now is {{ baibot_now_utc }}.";
|
||||
let expected = "Hello, I'm baibot using gpt-4o. The date/time now is 2024-09-20 (Friday), 18:34:15 UTC.";
|
||||
let prompt = "Hello, I'm {{ baibot_name }} using {{ baibot_model_id }}. The date/time now is {{ baibot_now_utc }} and this conversation started at {{ baibot_conversation_start_time_utc }}.";
|
||||
let expected = "Hello, I'm baibot using gpt-4o. The date/time now is 2024-09-20 (Friday), 18:34:15 UTC and this conversation started at 2024-09-19 (Thursday), 18:34:15 UTC.";
|
||||
|
||||
assert_eq!(variables.format(prompt), expected);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ pub fn default_config() -> Config {
|
||||
if let Some(ref mut config) = config.text_generation.as_mut() {
|
||||
config.model_id = "llama3-70b-8192".to_owned();
|
||||
config.max_context_tokens = 131_072;
|
||||
config.max_response_tokens = 4096;
|
||||
config.max_response_tokens = Some(4096);
|
||||
}
|
||||
|
||||
if let Some(ref mut config) = config.speech_to_text.as_mut() {
|
||||
|
||||
@@ -13,7 +13,7 @@ pub fn default_config() -> Config {
|
||||
if let Some(ref mut config) = config.text_generation.as_mut() {
|
||||
config.model_id = "gpt-4".to_owned();
|
||||
config.max_context_tokens = 128_000;
|
||||
config.max_response_tokens = 4096;
|
||||
config.max_response_tokens = Some(4096);
|
||||
}
|
||||
|
||||
if let Some(ref mut config) = config.text_to_speech.as_mut() {
|
||||
|
||||
@@ -17,7 +17,7 @@ pub fn default_config() -> Config {
|
||||
if let Some(ref mut config) = config.text_generation.as_mut() {
|
||||
config.model_id = "gemma2:2b".to_owned();
|
||||
config.max_context_tokens = 128_000;
|
||||
config.max_response_tokens = 4096;
|
||||
config.max_response_tokens = Some(4096);
|
||||
}
|
||||
|
||||
config
|
||||
|
||||
@@ -56,7 +56,7 @@ pub struct TextGenerationConfig {
|
||||
pub temperature: f32,
|
||||
|
||||
#[serde(default)]
|
||||
pub max_response_tokens: u32,
|
||||
pub max_response_tokens: Option<u32>,
|
||||
|
||||
#[serde(default)]
|
||||
pub max_context_tokens: u32,
|
||||
@@ -68,14 +68,14 @@ impl Default for TextGenerationConfig {
|
||||
model_id: default_text_model_id(),
|
||||
prompt: Some(default_prompt().to_owned()),
|
||||
temperature: super::super::default_temperature(),
|
||||
max_response_tokens: 16_384,
|
||||
max_response_tokens: Some(16_384),
|
||||
max_context_tokens: 128_000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_text_model_id() -> String {
|
||||
"gpt-4o-2024-08-06".to_owned()
|
||||
"gpt-4o".to_owned()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
|
||||
@@ -63,6 +63,7 @@ impl ControllerTrait for Controller {
|
||||
let messages = vec![LLMMessage {
|
||||
author: LLMAuthor::User,
|
||||
message_text: "Hello!".to_string(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
}];
|
||||
|
||||
let conversation = LLMConversation { messages };
|
||||
@@ -99,6 +100,7 @@ impl ControllerTrait for Controller {
|
||||
Some(LLMMessage {
|
||||
author: LLMAuthor::Prompt,
|
||||
message_text: prompt_text,
|
||||
timestamp: chrono::Utc::now(),
|
||||
})
|
||||
};
|
||||
|
||||
@@ -131,12 +133,18 @@ impl ControllerTrait for Controller {
|
||||
.temperature_override
|
||||
.unwrap_or(text_generation_config.temperature);
|
||||
|
||||
let request = CreateChatCompletionRequestArgs::default()
|
||||
.max_tokens(text_generation_config.max_response_tokens)
|
||||
let mut request_builder = CreateChatCompletionRequestArgs::default();
|
||||
|
||||
request_builder
|
||||
.model(&text_generation_config.model_id)
|
||||
.temperature(temperature)
|
||||
.messages(openai_conversation_messages)
|
||||
.build()?;
|
||||
.messages(openai_conversation_messages);
|
||||
|
||||
if let Some(max_response_tokens) = text_generation_config.max_response_tokens {
|
||||
request_builder.max_tokens(max_response_tokens);
|
||||
}
|
||||
|
||||
let request = request_builder.build()?;
|
||||
|
||||
if let Ok(request_as_json) = serde_json::to_string(&request) {
|
||||
tracing::trace!(
|
||||
|
||||
@@ -66,7 +66,7 @@ pub struct TextGenerationConfig {
|
||||
pub temperature: f32,
|
||||
|
||||
#[serde(default)]
|
||||
pub max_response_tokens: u32,
|
||||
pub max_response_tokens: Option<u32>,
|
||||
|
||||
#[serde(default)]
|
||||
pub max_context_tokens: u32,
|
||||
@@ -78,7 +78,7 @@ impl Default for TextGenerationConfig {
|
||||
model_id: default_text_model_id(),
|
||||
prompt: Some(default_prompt().to_owned()),
|
||||
temperature: super::super::default_temperature(),
|
||||
max_response_tokens: 4096,
|
||||
max_response_tokens: Some(4096),
|
||||
max_context_tokens: 128_000,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ impl ControllerTrait for Controller {
|
||||
let messages = vec![LLMMessage {
|
||||
author: LLMAuthor::User,
|
||||
message_text: "Hello!".to_string(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
}];
|
||||
|
||||
let conversation = LLMConversation { messages };
|
||||
@@ -97,6 +98,7 @@ impl ControllerTrait for Controller {
|
||||
Some(LLMMessage {
|
||||
author: LLMAuthor::Prompt,
|
||||
message_text: prompt_text,
|
||||
timestamp: chrono::Utc::now(),
|
||||
})
|
||||
};
|
||||
|
||||
@@ -131,12 +133,15 @@ impl ControllerTrait for Controller {
|
||||
|
||||
let max_tokens = text_generation_config
|
||||
.max_response_tokens
|
||||
.try_into()
|
||||
.expect("Failed converting max_response_tokens from u32 to i32");
|
||||
.map(|max_response_tokens| {
|
||||
max_response_tokens
|
||||
.try_into()
|
||||
.expect("Failed converting max_response_tokens from u32 to i32")
|
||||
});
|
||||
|
||||
let request = ChatBody {
|
||||
model: text_generation_config.model_id.clone(),
|
||||
max_tokens: Some(max_tokens),
|
||||
max_tokens,
|
||||
temperature: Some(temperature),
|
||||
top_p: None,
|
||||
n: Some(1),
|
||||
|
||||
@@ -56,7 +56,7 @@ pub fn default_config() -> Config {
|
||||
|
||||
if let Some(text_generation) = &mut config.text_generation {
|
||||
text_generation.model_id = "some-model".to_string();
|
||||
text_generation.max_response_tokens = 4096;
|
||||
text_generation.max_response_tokens = Some(4096);
|
||||
text_generation.max_context_tokens = 128_000;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ pub fn default_config() -> Config {
|
||||
if let Some(ref mut config) = config.text_generation.as_mut() {
|
||||
config.model_id = "mattshumer/reflection-70b:free".to_owned();
|
||||
config.max_context_tokens = 8192;
|
||||
config.max_response_tokens = 2048;
|
||||
config.max_response_tokens = Some(2048);
|
||||
}
|
||||
|
||||
config
|
||||
|
||||
@@ -14,7 +14,7 @@ pub fn default_config() -> Config {
|
||||
if let Some(ref mut config) = config.text_generation.as_mut() {
|
||||
config.model_id = "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo".to_owned();
|
||||
config.max_context_tokens = 8192;
|
||||
config.max_response_tokens = 2048;
|
||||
config.max_response_tokens = Some(2048);
|
||||
}
|
||||
|
||||
config
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
use std::{future::Future, pin::Pin};
|
||||
|
||||
use mxlink::matrix_sdk::media::{MediaFormat, MediaRequest};
|
||||
use mxlink::matrix_sdk::media::{MediaFormat, MediaRequestParameters};
|
||||
use mxlink::matrix_sdk::ruma::{
|
||||
events::room::MediaSource, MilliSecondsSinceUnixEpoch, OwnedUserId,
|
||||
};
|
||||
@@ -172,6 +172,24 @@ impl Bot {
|
||||
self.matrix_link().user_id()
|
||||
}
|
||||
|
||||
pub(crate) async fn user_display_name_in_room(&self, room: &Room) -> Option<String> {
|
||||
let bot_display_name = self
|
||||
.room_display_name_fetcher()
|
||||
.own_display_name_in_room(room)
|
||||
.await;
|
||||
|
||||
match bot_display_name {
|
||||
Ok(value) => value,
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
?err,
|
||||
"Failed to fetch bot display name. Proceeding without it"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn reacting(&self) -> super::reacting::Reacting {
|
||||
super::reacting::Reacting::new(self.clone())
|
||||
}
|
||||
@@ -269,7 +287,7 @@ impl Bot {
|
||||
let desired_display_name = self.inner.config.user.name.clone();
|
||||
|
||||
let profile = account
|
||||
.get_profile()
|
||||
.fetch_user_profile()
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed fetching profile: {:?}", e))?;
|
||||
|
||||
@@ -292,7 +310,7 @@ impl Bot {
|
||||
|
||||
let should_update_avatar = match &profile.avatar_url {
|
||||
Some(avatar_url) => {
|
||||
let request = MediaRequest {
|
||||
let request = MediaRequestParameters {
|
||||
source: MediaSource::Plain(avatar_url.to_owned()),
|
||||
format: MediaFormat::File,
|
||||
};
|
||||
|
||||
@@ -239,8 +239,11 @@ impl Messaging {
|
||||
}
|
||||
};
|
||||
|
||||
let bot_display_name = self.bot.user_display_name_in_room(&room).await;
|
||||
|
||||
let interaction_context = determine_interaction_context_for_room_event(
|
||||
self.bot.user_id(),
|
||||
&bot_display_name,
|
||||
&room,
|
||||
&event,
|
||||
&payload,
|
||||
@@ -279,7 +282,8 @@ impl Messaging {
|
||||
self.bot.admin_pattern_regexes().clone(),
|
||||
trigger_event_info,
|
||||
interaction_context.thread_info.clone(),
|
||||
);
|
||||
)
|
||||
.with_bot_display_name(bot_display_name);
|
||||
|
||||
let controller_type = crate::controller::determine_controller(
|
||||
self.bot.command_prefix(),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use mxlink::matrix_sdk::{
|
||||
ruma::{
|
||||
events::{
|
||||
room::message::Relation, AnyMessageLikeEvent, AnySyncTimelineEvent, AnyTimelineEvent,
|
||||
MessageLikeEvent,
|
||||
room::message::Relation, AnySyncMessageLikeEvent, AnySyncTimelineEvent,
|
||||
SyncMessageLikeEvent,
|
||||
},
|
||||
OwnedEventId, OwnedUserId,
|
||||
},
|
||||
@@ -139,7 +139,7 @@ impl Reacting {
|
||||
}
|
||||
};
|
||||
|
||||
let reacted_to_event_any_timeline_event = match reacted_to_event.event.deserialize() {
|
||||
let reacted_to_event_any_timeline_event = match reacted_to_event.raw().deserialize() {
|
||||
Ok(value) => value,
|
||||
Err(err) => {
|
||||
tracing::error!(
|
||||
@@ -154,7 +154,7 @@ impl Reacting {
|
||||
let reacted_to_event_sender_id: OwnedUserId =
|
||||
reacted_to_event_any_timeline_event.sender().to_owned();
|
||||
|
||||
let AnyTimelineEvent::MessageLike(reacted_to_event_message_like) =
|
||||
let AnySyncTimelineEvent::MessageLike(reacted_to_event_message_like) =
|
||||
reacted_to_event_any_timeline_event
|
||||
else {
|
||||
tracing::debug!(
|
||||
@@ -164,7 +164,7 @@ impl Reacting {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let AnyMessageLikeEvent::RoomMessage(reacted_to_event_room_message) =
|
||||
let AnySyncMessageLikeEvent::RoomMessage(reacted_to_event_room_message) =
|
||||
reacted_to_event_message_like
|
||||
else {
|
||||
tracing::debug!(
|
||||
@@ -174,7 +174,7 @@ impl Reacting {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let MessageLikeEvent::Original(reacted_to_event_room_message_original) =
|
||||
let SyncMessageLikeEvent::Original(reacted_to_event_room_message_original) =
|
||||
reacted_to_event_room_message
|
||||
else {
|
||||
tracing::debug!(?reacted_to_event_id, "Ignoring redacted reacted-to event",);
|
||||
|
||||
@@ -383,24 +383,10 @@ async fn handle_stage_text_generation(
|
||||
_ => vec![],
|
||||
};
|
||||
|
||||
let bot_display_name = bot
|
||||
.room_display_name_fetcher()
|
||||
.own_display_name_in_room(message_context.room())
|
||||
.await;
|
||||
|
||||
let bot_display_name = match bot_display_name {
|
||||
Ok(value) => value,
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
?err,
|
||||
"Failed to fetch bot display name. Proceeding without it"
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let bot_user_prefixes_to_strip =
|
||||
create_list_of_bot_user_prefixes_to_strip(bot.user_id(), &bot_display_name);
|
||||
let bot_user_prefixes_to_strip = create_list_of_bot_user_prefixes_to_strip(
|
||||
bot.user_id(),
|
||||
message_context.bot_display_name(),
|
||||
);
|
||||
|
||||
let allowed_users = match controller_type {
|
||||
// Regular chat completion only operates on messages from allowed users.
|
||||
@@ -492,6 +478,7 @@ async fn handle_stage_text_generation(
|
||||
.text_generation_model_id()
|
||||
.unwrap_or("unknown-model".to_owned()),
|
||||
chrono::Utc::now(),
|
||||
conversation.start_time(),
|
||||
);
|
||||
|
||||
let params = TextGenerationParams {
|
||||
@@ -588,7 +575,7 @@ async fn handle_stage_speech_to_text_actual_transcribing(
|
||||
) -> anyhow::Result<OwnedEventId> {
|
||||
let src = &audio_content.source;
|
||||
|
||||
let media_request = mxlink::matrix_sdk::media::MediaRequest {
|
||||
let media_request = mxlink::matrix_sdk::media::MediaRequestParameters {
|
||||
source: src.to_owned(),
|
||||
format: mxlink::matrix_sdk::media::MediaFormat::File,
|
||||
};
|
||||
|
||||
@@ -34,6 +34,8 @@ pub async fn handle_image(
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let _typing_notice_guard = bot.start_typing_notice(message_context.room()).await;
|
||||
|
||||
let params = MatrixMessageProcessingParams::new(
|
||||
bot.user_id().to_owned(),
|
||||
Some(message_context.combined_admin_and_user_regexes()),
|
||||
|
||||
@@ -46,6 +46,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_build_prompt() {
|
||||
let timestamp = chrono::Utc::now();
|
||||
|
||||
let test_cases = vec![
|
||||
// Simple case
|
||||
TestCase {
|
||||
@@ -59,6 +61,7 @@ mod tests {
|
||||
messages: vec![Message {
|
||||
author: Author::User,
|
||||
message_text: "Must be blue".to_owned(),
|
||||
timestamp,
|
||||
}],
|
||||
expected_prompt: "Generate a picture of a dog\nOther criteria:\n- Must be blue",
|
||||
},
|
||||
@@ -68,14 +71,17 @@ mod tests {
|
||||
messages: vec![Message {
|
||||
author: Author::User,
|
||||
message_text: "Must be blue".to_owned(),
|
||||
timestamp,
|
||||
},
|
||||
Message {
|
||||
author: Author::Assistant,
|
||||
message_text: "Whatever".to_owned(),
|
||||
timestamp,
|
||||
},
|
||||
Message {
|
||||
author: Author::User,
|
||||
message_text: "Must be 3-legged.\nMust be flying.".to_owned(),
|
||||
timestamp,
|
||||
}],
|
||||
expected_prompt: "Generate a picture of an elephant\nOther criteria:\n- Must be blue\n- Must be 3-legged.. Must be flying.",
|
||||
},
|
||||
@@ -85,18 +91,22 @@ mod tests {
|
||||
messages: vec![Message {
|
||||
author: Author::User,
|
||||
message_text: "Must be blue".to_owned(),
|
||||
timestamp,
|
||||
},
|
||||
Message {
|
||||
author: Author::Assistant,
|
||||
message_text: "Whatever".to_owned(),
|
||||
timestamp,
|
||||
},
|
||||
Message {
|
||||
author: Author::User,
|
||||
message_text: "Again".to_owned(),
|
||||
timestamp,
|
||||
},
|
||||
Message {
|
||||
author: Author::User,
|
||||
message_text: "again".to_owned(),
|
||||
timestamp,
|
||||
}],
|
||||
expected_prompt: "Generate a picture of a grizzly bear\nOther criteria:\n- Must be blue",
|
||||
},
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Author {
|
||||
Prompt,
|
||||
@@ -9,6 +11,7 @@ pub enum Author {
|
||||
pub struct Message {
|
||||
pub author: Author,
|
||||
pub message_text: String,
|
||||
pub timestamp: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -52,39 +55,59 @@ impl Conversation {
|
||||
messages: new_messages,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_time(&self) -> Option<DateTime<Utc>> {
|
||||
self.messages.first().map(|message| message.timestamp)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::{TimeZone, Utc};
|
||||
|
||||
#[test]
|
||||
fn combine_consecutive_messages() {
|
||||
let timestamp_1 = Utc.with_ymd_and_hms(2024, 9, 20, 18, 34, 15).unwrap();
|
||||
|
||||
let timestamp_2 = Utc.with_ymd_and_hms(2024, 9, 21, 18, 34, 15).unwrap();
|
||||
|
||||
let timestamp_3 = Utc.with_ymd_and_hms(2024, 9, 22, 18, 34, 15).unwrap();
|
||||
|
||||
let conversation = Conversation {
|
||||
messages: vec![
|
||||
// User's turn
|
||||
Message {
|
||||
author: Author::User,
|
||||
message_text: "Hello".to_string(),
|
||||
timestamp: timestamp_1,
|
||||
},
|
||||
Message {
|
||||
author: Author::User,
|
||||
message_text: "How are you?".to_string(),
|
||||
timestamp: timestamp_2,
|
||||
},
|
||||
Message {
|
||||
author: Author::User,
|
||||
message_text: "I'm OK, btw.".to_string(),
|
||||
timestamp: timestamp_3,
|
||||
},
|
||||
// Assistant's turn
|
||||
Message {
|
||||
author: Author::Assistant,
|
||||
message_text: "Hi there!".to_string(),
|
||||
timestamp: timestamp_2,
|
||||
},
|
||||
Message {
|
||||
author: Author::Assistant,
|
||||
message_text: "I'm doing well, thank you.".to_string(),
|
||||
timestamp: timestamp_3,
|
||||
},
|
||||
// User's turn
|
||||
Message {
|
||||
author: Author::User,
|
||||
message_text: "That's great!".to_string(),
|
||||
timestamp: timestamp_3,
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -97,12 +120,17 @@ mod tests {
|
||||
conversation.messages[0].message_text,
|
||||
"Hello\nHow are you?\nI'm OK, btw."
|
||||
);
|
||||
assert_eq!(conversation.messages[0].timestamp, timestamp_1);
|
||||
|
||||
assert_eq!(conversation.messages[1].author, Author::Assistant);
|
||||
assert_eq!(
|
||||
conversation.messages[1].message_text,
|
||||
"Hi there!\nI'm doing well, thank you."
|
||||
);
|
||||
assert_eq!(conversation.messages[1].timestamp, timestamp_2);
|
||||
|
||||
assert_eq!(conversation.messages[2].author, Author::User);
|
||||
assert_eq!(conversation.messages[2].message_text, "That's great!");
|
||||
assert_eq!(conversation.messages[2].timestamp, timestamp_3);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ fn test_messages_by_the_bot_are_identified_correctly() {
|
||||
message_type: super::super::matrix::MatrixMessageType::Text,
|
||||
message_text: "Hello!".to_owned(),
|
||||
mentioned_users: vec![],
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
|
||||
let llm_message = convert_matrix_message_to_llm_message(&matrix_message, &bot_user_id).unwrap();
|
||||
@@ -39,6 +40,7 @@ fn test_notice_messages_by_bot_with_speech_to_text_prefix_are_cleaned_up_and_con
|
||||
message_type: super::super::matrix::MatrixMessageType::Notice,
|
||||
message_text,
|
||||
mentioned_users: vec![],
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
|
||||
let llm_message = convert_matrix_message_to_llm_message(&matrix_message, &bot_user_id).unwrap();
|
||||
@@ -62,6 +64,7 @@ fn test_notice_error_messages_by_bot_are_ignored() {
|
||||
message_type: super::super::matrix::MatrixMessageType::Notice,
|
||||
message_text,
|
||||
mentioned_users: vec![],
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
|
||||
let llm_message = convert_matrix_message_to_llm_message(&matrix_message, &bot_user_id);
|
||||
@@ -86,6 +89,7 @@ fn test_other_notice_messages_by_the_bot_are_ignored() {
|
||||
message_type: super::super::matrix::MatrixMessageType::Notice,
|
||||
message_text: message_text.to_owned(),
|
||||
mentioned_users: vec![],
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
|
||||
let llm_message = convert_matrix_message_to_llm_message(&matrix_message, &bot_user_id);
|
||||
|
||||
@@ -16,7 +16,7 @@ pub fn shorten_messages_list_to_context_size(
|
||||
model: &str,
|
||||
prompt_message: &Option<Message>,
|
||||
mut messages: Vec<Message>,
|
||||
max_response_tokens: u32,
|
||||
max_response_tokens: Option<u32>,
|
||||
max_context_tokens: u32,
|
||||
) -> Vec<Message> {
|
||||
// Loading the tokenization data is an expensive process, so
|
||||
@@ -26,7 +26,8 @@ pub fn shorten_messages_list_to_context_size(
|
||||
// We want to retain the prompt in all cases, so we always count it first.
|
||||
// We also always reserve enough tokens for the maximum response we expect.
|
||||
let mut current_context_length: u32 = if let Some(prompt_message) = prompt_message {
|
||||
calculate_token_size_for_message(&bpe, model, prompt_message) + max_response_tokens
|
||||
calculate_token_size_for_message(&bpe, model, prompt_message)
|
||||
+ max_response_tokens.unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
@@ -85,6 +86,7 @@ pub mod test {
|
||||
let message = super::Message {
|
||||
author: super::Author::User,
|
||||
message_text: "Hello there!".to_owned(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
|
||||
let tokens = super::calculate_token_size_for_message(&bpe, model, &message);
|
||||
@@ -98,11 +100,12 @@ pub mod test {
|
||||
|
||||
let bpe = super::get_bpe_for_model(model);
|
||||
|
||||
let max_response_tokens: u32 = 5;
|
||||
let max_response_tokens: Option<u32> = Some(5);
|
||||
|
||||
let prompt = super::Message {
|
||||
author: super::Author::Prompt,
|
||||
message_text: "You are a bot!".to_owned(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
let prompt_length = 10;
|
||||
|
||||
@@ -116,6 +119,7 @@ pub mod test {
|
||||
let first = super::Message {
|
||||
author: super::Author::User,
|
||||
message_text: "Hello there!".to_owned(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
let first_length = 8;
|
||||
|
||||
@@ -129,6 +133,7 @@ pub mod test {
|
||||
let second = super::Message {
|
||||
author: super::Author::Assistant,
|
||||
message_text: "Hello!".to_owned(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
let second_length = 7;
|
||||
|
||||
@@ -143,6 +148,7 @@ pub mod test {
|
||||
author: super::Author::User,
|
||||
message_text: "This is the 3rd message in this conversation. It shall be preserved."
|
||||
.to_owned(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
let third_length = 21;
|
||||
|
||||
@@ -156,6 +162,7 @@ pub mod test {
|
||||
let forth = super::Message {
|
||||
author: super::Author::Assistant,
|
||||
message_text: "This is yet another message that shall be preserved.".to_owned(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
let forth_length = 15;
|
||||
|
||||
@@ -173,7 +180,7 @@ pub mod test {
|
||||
&Some(prompt),
|
||||
conversation_messages,
|
||||
max_response_tokens,
|
||||
prompt_length + max_response_tokens + forth_length + third_length,
|
||||
prompt_length + max_response_tokens.unwrap_or(0) + forth_length + third_length,
|
||||
);
|
||||
|
||||
assert_eq!(2, new_conversation_messages.len());
|
||||
@@ -195,11 +202,12 @@ pub mod test {
|
||||
|
||||
let bpe = super::get_bpe_for_model(model);
|
||||
|
||||
let max_response_tokens: u32 = 5;
|
||||
let max_response_tokens: Option<u32> = Some(5);
|
||||
|
||||
let prompt = super::Message {
|
||||
author: super::Author::User,
|
||||
message_text: "あなたはボットです。".to_owned(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
let prompt_length = 14;
|
||||
|
||||
@@ -213,6 +221,7 @@ pub mod test {
|
||||
let first = super::Message {
|
||||
author: super::Author::User,
|
||||
message_text: "こんにちは!".to_owned(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
let first_length = 7;
|
||||
|
||||
@@ -226,6 +235,7 @@ pub mod test {
|
||||
let second = super::Message {
|
||||
author: super::Author::Assistant,
|
||||
message_text: "こんにちは。今日は元気ですか。".to_owned(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
let second_length = 15;
|
||||
|
||||
@@ -239,6 +249,7 @@ pub mod test {
|
||||
let third = super::Message {
|
||||
author: super::Author::User,
|
||||
message_text: "これは第3のメッセージなので、保存されます。".to_owned(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
let third_length = 22;
|
||||
|
||||
@@ -252,6 +263,7 @@ pub mod test {
|
||||
let forth = super::Message {
|
||||
author: super::Author::Assistant,
|
||||
message_text: "これはもう一つの保存されますメッセージです。".to_owned(),
|
||||
timestamp: chrono::Utc::now(),
|
||||
};
|
||||
let forth_length = 21;
|
||||
|
||||
@@ -269,7 +281,7 @@ pub mod test {
|
||||
&Some(prompt),
|
||||
conversation_messages,
|
||||
max_response_tokens,
|
||||
prompt_length + max_response_tokens + forth_length + third_length,
|
||||
prompt_length + max_response_tokens.unwrap_or(0) + forth_length + third_length,
|
||||
);
|
||||
|
||||
assert_eq!(2, new_conversation_messages.len());
|
||||
|
||||
@@ -17,19 +17,30 @@ pub fn convert_matrix_message_to_llm_message(
|
||||
|
||||
fn convert_bot_message(matrix_message: &MatrixMessage) -> Option<Message> {
|
||||
match matrix_message.message_type {
|
||||
MatrixMessageType::Text => convert_bot_text_message(&matrix_message.message_text),
|
||||
MatrixMessageType::Notice => convert_bot_notice_message(&matrix_message.message_text),
|
||||
MatrixMessageType::Text => {
|
||||
convert_bot_text_message(&matrix_message.message_text, &matrix_message.timestamp)
|
||||
}
|
||||
MatrixMessageType::Notice => {
|
||||
convert_bot_notice_message(&matrix_message.message_text, &matrix_message.timestamp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_bot_text_message(text: &str) -> Option<Message> {
|
||||
fn convert_bot_text_message(
|
||||
text: &str,
|
||||
timestamp: &chrono::DateTime<chrono::Utc>,
|
||||
) -> Option<Message> {
|
||||
Some(Message {
|
||||
author: Author::Assistant,
|
||||
message_text: text.to_owned(),
|
||||
timestamp: timestamp.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
fn convert_bot_notice_message(text: &str) -> Option<Message> {
|
||||
fn convert_bot_notice_message(
|
||||
text: &str,
|
||||
timestamp: &chrono::DateTime<chrono::Utc>,
|
||||
) -> Option<Message> {
|
||||
// Notice messages sent by the bot are usually transcriptions of previous messages sent by the user.
|
||||
// Such transcriptions are prefixed with an emoji and blockquoted.
|
||||
// If we find a notice that doesn't match this pattern, we skip it.
|
||||
@@ -42,6 +53,7 @@ fn convert_bot_notice_message(text: &str) -> Option<Message> {
|
||||
return Some(Message {
|
||||
author: Author::User,
|
||||
message_text: text.to_owned(),
|
||||
timestamp: timestamp.to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -52,5 +64,6 @@ fn convert_user_message(matrix_message: &MatrixMessage) -> Option<Message> {
|
||||
Some(Message {
|
||||
author: Author::User,
|
||||
message_text: matrix_message.message_text.clone(),
|
||||
timestamp: matrix_message.timestamp.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use regex::Regex;
|
||||
|
||||
use mxlink::matrix_sdk::ruma::OwnedUserId;
|
||||
@@ -8,6 +9,7 @@ pub struct MatrixMessage {
|
||||
pub message_type: MatrixMessageType,
|
||||
pub message_text: String,
|
||||
pub mentioned_users: Vec<OwnedUserId>,
|
||||
pub timestamp: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
||||
@@ -22,7 +22,7 @@ impl RoomEventFetcher {
|
||||
room: &Room,
|
||||
) -> mxlink::matrix_sdk::Result<TimelineEvent> {
|
||||
let Some(lru_cache) = &self.lru_cache else {
|
||||
return room.event(event_id).await;
|
||||
return room.event(event_id, None).await;
|
||||
};
|
||||
|
||||
let guard = lru_cache.get_value_or_guard_async(event_id).await;
|
||||
@@ -33,7 +33,7 @@ impl RoomEventFetcher {
|
||||
return Ok(config);
|
||||
}
|
||||
Err(guard) => {
|
||||
let event = room.event(event_id).await?;
|
||||
let event = room.event(event_id, None).await?;
|
||||
|
||||
let _ = guard.insert(event.clone());
|
||||
|
||||
|
||||
@@ -9,9 +9,11 @@ use mxlink::matrix_sdk::{
|
||||
ruma::events::{
|
||||
relation::Thread,
|
||||
room::message::{
|
||||
MessageType, OriginalSyncRoomMessageEvent, Relation, RoomMessageEventContent,
|
||||
sanitize::remove_plain_reply_fallback, MessageType, OriginalSyncRoomMessageEvent,
|
||||
Relation, RoomMessageEventContent,
|
||||
},
|
||||
AnyMessageLikeEvent, AnyMessageLikeEventContent, AnyTimelineEvent, MessageLikeEvent,
|
||||
AnyMessageLikeEventContent, AnySyncMessageLikeEvent, AnySyncTimelineEvent,
|
||||
SyncMessageLikeEvent,
|
||||
},
|
||||
Room,
|
||||
};
|
||||
@@ -75,10 +77,10 @@ async fn get_matrix_messages_in_reply_chain_native(
|
||||
event_fetcher: &Arc<RoomEventFetcher>,
|
||||
room: &Room,
|
||||
event_id: OwnedEventId,
|
||||
) -> Result<Vec<AnyMessageLikeEvent>, mxlink::matrix_sdk::Error> {
|
||||
) -> Result<Vec<AnySyncMessageLikeEvent>, mxlink::matrix_sdk::Error> {
|
||||
let mut next_event_id = Some(event_id.clone());
|
||||
|
||||
let mut messages: Vec<AnyMessageLikeEvent> = Vec::new();
|
||||
let mut messages: Vec<AnySyncMessageLikeEvent> = Vec::new();
|
||||
let mut handled_event_ids: Vec<OwnedEventId> = Vec::new();
|
||||
|
||||
while let Some(next_event_id_in_loop) = next_event_id {
|
||||
@@ -97,9 +99,9 @@ async fn get_matrix_messages_in_reply_chain_native(
|
||||
|
||||
handled_event_ids.push(next_event_id_in_loop.clone());
|
||||
|
||||
let event_deserialized = event.event.deserialize()?;
|
||||
let event_deserialized = event.raw().deserialize()?;
|
||||
|
||||
let AnyTimelineEvent::MessageLike(message_like_event) = event_deserialized else {
|
||||
let AnySyncTimelineEvent::MessageLike(message_like_event) = event_deserialized else {
|
||||
tracing::warn!(
|
||||
"Not proceeding past non-MessageLike event: {:?}",
|
||||
event_deserialized
|
||||
@@ -108,9 +110,9 @@ async fn get_matrix_messages_in_reply_chain_native(
|
||||
};
|
||||
|
||||
next_event_id = match message_like_event.clone() {
|
||||
AnyMessageLikeEvent::RoomEncrypted(_) => None,
|
||||
AnyMessageLikeEvent::RoomMessage(room_message) => {
|
||||
if let MessageLikeEvent::Original(room_message_original) = room_message {
|
||||
AnySyncMessageLikeEvent::RoomEncrypted(_) => None,
|
||||
AnySyncMessageLikeEvent::RoomMessage(room_message) => {
|
||||
if let SyncMessageLikeEvent::Original(room_message_original) = room_message {
|
||||
match room_message_original.content.relates_to {
|
||||
Some(Relation::Reply { in_reply_to }) => Some(in_reply_to.event_id.clone()),
|
||||
_ => None,
|
||||
@@ -206,7 +208,7 @@ fn is_message_from_allowed_sender(
|
||||
}
|
||||
|
||||
pub fn convert_matrix_native_event_to_matrix_message(
|
||||
matrix_native_event: &AnyMessageLikeEvent,
|
||||
matrix_native_event: &AnySyncMessageLikeEvent,
|
||||
) -> Option<MatrixMessage> {
|
||||
let Some(content) = matrix_native_event.original_content() else {
|
||||
// Redacted message
|
||||
@@ -229,11 +231,18 @@ pub fn convert_matrix_native_event_to_matrix_message(
|
||||
let text = if is_reply {
|
||||
// For regular replies, we need to strip the fallback-for-rich replies part.
|
||||
// See: https://spec.matrix.org/v1.11/client-server-api/#fallbacks-for-rich-replies
|
||||
strip_rich_reply_fallback_text(&text)
|
||||
remove_plain_reply_fallback(&text).to_owned()
|
||||
} else {
|
||||
text
|
||||
};
|
||||
|
||||
let timestamp = chrono::DateTime::<chrono::Utc>::from(
|
||||
matrix_native_event
|
||||
.origin_server_ts()
|
||||
.to_system_time()
|
||||
.unwrap_or_else(std::time::SystemTime::now),
|
||||
);
|
||||
|
||||
let mentioned_users = room_message
|
||||
.mentions
|
||||
.map(|m| m.user_ids.iter().map(|u| u.to_owned()).collect())
|
||||
@@ -248,6 +257,7 @@ pub fn convert_matrix_native_event_to_matrix_message(
|
||||
},
|
||||
message_text: text,
|
||||
mentioned_users,
|
||||
timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -268,13 +278,14 @@ pub fn convert_matrix_native_event_to_matrix_message(
|
||||
#[tracing::instrument(name = "determine_interaction_context_for_room_event", skip_all, fields(room_id = room.room_id().as_str(), event_id = current_event.event_id.as_str()))]
|
||||
pub async fn determine_interaction_context_for_room_event(
|
||||
bot_user_id: &OwnedUserId,
|
||||
bot_display_name: &Option<String>,
|
||||
room: &Room,
|
||||
current_event: &OriginalSyncRoomMessageEvent,
|
||||
current_event_payload: &MessagePayload,
|
||||
event_fetcher: &Arc<RoomEventFetcher>,
|
||||
) -> anyhow::Result<Option<InteractionContext>> {
|
||||
let current_event_is_mentioning_bot =
|
||||
is_event_mentioning_bot(¤t_event.content, bot_user_id);
|
||||
is_event_mentioning_bot(¤t_event.content, bot_user_id, bot_display_name);
|
||||
|
||||
let Some(relation) = ¤t_event.content.relates_to else {
|
||||
// This is a top-level message. We consider it the start of the thread.
|
||||
@@ -296,6 +307,7 @@ pub async fn determine_interaction_context_for_room_event(
|
||||
Relation::Thread(thread) => {
|
||||
determine_interaction_context_for_room_event_related_to_thread(
|
||||
bot_user_id,
|
||||
bot_display_name,
|
||||
room,
|
||||
current_event,
|
||||
event_fetcher,
|
||||
@@ -320,6 +332,7 @@ pub async fn determine_interaction_context_for_room_event(
|
||||
|
||||
async fn determine_interaction_context_for_room_event_related_to_thread(
|
||||
bot_user_id: &OwnedUserId,
|
||||
bot_display_name: &Option<String>,
|
||||
room: &Room,
|
||||
current_event: &OriginalSyncRoomMessageEvent,
|
||||
event_fetcher: &Arc<RoomEventFetcher>,
|
||||
@@ -380,6 +393,7 @@ async fn determine_interaction_context_for_room_event_related_to_thread(
|
||||
thread_start_timeline_event,
|
||||
thread_info.clone(),
|
||||
bot_user_id,
|
||||
bot_display_name,
|
||||
)?;
|
||||
|
||||
let Some(detailed_message_payload) = thread_start_detailed_message_payload else {
|
||||
@@ -422,45 +436,33 @@ async fn determine_interaction_context_for_room_event_related_to_reply(
|
||||
fn is_event_mentioning_bot(
|
||||
event_content: &RoomMessageEventContent,
|
||||
bot_user_id: &OwnedUserId,
|
||||
bot_display_name: &Option<String>,
|
||||
) -> bool {
|
||||
// As a fallback, we used to do string matching (`event_content.body().contains(bot_user_id.as_str())`) here as well.
|
||||
// However, this is unreliable. In 2024+, clients that do not have proper mentions support should get fixed,
|
||||
// instead of us having to deal with the possibility of false positives.
|
||||
//
|
||||
let Some(mentions) = &event_content.mentions else {
|
||||
return false;
|
||||
};
|
||||
|
||||
mentions
|
||||
.user_ids
|
||||
.iter()
|
||||
.any(|user_id| user_id == bot_user_id)
|
||||
}
|
||||
|
||||
/// Strips the rich reply fallback text from the given text.
|
||||
/// See: https://spec.matrix.org/v1.11/client-server-api/#fallbacks-for-rich-replies
|
||||
///
|
||||
/// Example:
|
||||
/// ```rust,ignore
|
||||
/// let text = "> <@admin:example.com> What's the difference between Matrix and XMPP?\n\nAnswer me";
|
||||
/// let stripped_text = strip_rich_reply_fallback_text(text);
|
||||
/// assert_eq!(stripped_text, "Answer me");
|
||||
/// ```
|
||||
fn strip_rich_reply_fallback_text(text: &str) -> String {
|
||||
let lines = text.lines();
|
||||
let mut stripped_lines = Vec::new();
|
||||
let mut encountered_non_prefix = false;
|
||||
|
||||
for line in lines {
|
||||
if !encountered_non_prefix && line.starts_with("> ") {
|
||||
continue;
|
||||
} else {
|
||||
encountered_non_prefix = true;
|
||||
stripped_lines.push(line);
|
||||
if let Some(mentions) = &event_content.mentions {
|
||||
mentions
|
||||
.user_ids
|
||||
.iter()
|
||||
.any(|user_id| user_id == bot_user_id)
|
||||
} else {
|
||||
// For compatibility with clients that do not support the new Mentions specification
|
||||
// (see https://spec.matrix.org/latest/client-server-api/#user-and-room-mentions),
|
||||
// we also do string matching here.
|
||||
//
|
||||
// As of 2024-10-03, at least Element iOS does not support the new Mentions specification
|
||||
// and is still quite widespread.
|
||||
//
|
||||
// We may consider dropping this string-matching behavior altogether in the future,
|
||||
// so improving this compatibility block is not a high priority.
|
||||
if event_content.body().contains(bot_user_id.as_str()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
stripped_lines.join("\n").trim().to_owned()
|
||||
if let Some(bot_display_name) = bot_display_name {
|
||||
return event_content.body().contains(bot_display_name);
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn timeline_event_to_detailed_message_payload(
|
||||
@@ -468,8 +470,9 @@ fn timeline_event_to_detailed_message_payload(
|
||||
timeline_event: TimelineEvent,
|
||||
thread_info: ThreadInfo,
|
||||
bot_user_id: &OwnedUserId,
|
||||
bot_display_name: &Option<String>,
|
||||
) -> anyhow::Result<Option<DetailedMessagePayload>> {
|
||||
let timeline_event_deserialized = match timeline_event.event.deserialize() {
|
||||
let timeline_event_deserialized = match timeline_event.raw().deserialize() {
|
||||
Ok(value) => value,
|
||||
Err(err) => {
|
||||
return Err(anyhow::format_err!(
|
||||
@@ -480,7 +483,7 @@ fn timeline_event_to_detailed_message_payload(
|
||||
}
|
||||
};
|
||||
|
||||
let AnyTimelineEvent::MessageLike(thread_start_message_like_event) =
|
||||
let AnySyncTimelineEvent::MessageLike(thread_start_message_like_event) =
|
||||
timeline_event_deserialized
|
||||
else {
|
||||
tracing::trace!(
|
||||
@@ -491,7 +494,7 @@ fn timeline_event_to_detailed_message_payload(
|
||||
};
|
||||
|
||||
let (is_mentioning_bot, message_payload) = match thread_start_message_like_event {
|
||||
AnyMessageLikeEvent::RoomEncrypted(room_message) => {
|
||||
AnySyncMessageLikeEvent::RoomEncrypted(room_message) => {
|
||||
tracing::warn!(
|
||||
"Could not inspect event {} because it failed to decrypt: {:?}",
|
||||
timeline_event_id.clone(),
|
||||
@@ -506,8 +509,8 @@ fn timeline_event_to_detailed_message_payload(
|
||||
MessagePayload::Encrypted(thread_info.clone()),
|
||||
)
|
||||
}
|
||||
AnyMessageLikeEvent::RoomMessage(room_message) => {
|
||||
if let MessageLikeEvent::Original(room_message_original) = room_message {
|
||||
AnySyncMessageLikeEvent::RoomMessage(room_message) => {
|
||||
if let SyncMessageLikeEvent::Original(room_message_original) = room_message {
|
||||
let room_message_payload: Result<MessagePayload, String> =
|
||||
room_message_original.content.msgtype.clone().try_into();
|
||||
|
||||
@@ -519,8 +522,11 @@ fn timeline_event_to_detailed_message_payload(
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let is_mentioning_bot =
|
||||
is_event_mentioning_bot(&room_message_original.content, bot_user_id);
|
||||
let is_mentioning_bot = is_event_mentioning_bot(
|
||||
&room_message_original.content,
|
||||
bot_user_id,
|
||||
bot_display_name,
|
||||
);
|
||||
|
||||
(is_mentioning_bot, room_message_payload)
|
||||
} else {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use chrono::{TimeZone, Utc};
|
||||
|
||||
use mxlink::matrix_sdk::ruma::OwnedUserId;
|
||||
|
||||
use crate::conversation::matrix::{
|
||||
@@ -11,11 +13,14 @@ fn is_message_from_allowed_sender() {
|
||||
let allowed_user_id = OwnedUserId::try_from("@user.someone:example.com").unwrap();
|
||||
let unallowed_user_id = OwnedUserId::try_from("@another:example.com").unwrap();
|
||||
|
||||
let timestamp = Utc.with_ymd_and_hms(2024, 9, 20, 18, 34, 15).unwrap();
|
||||
|
||||
let bot_message = MatrixMessage {
|
||||
sender_id: bot_user_id.to_owned(),
|
||||
message_type: MatrixMessageType::Text,
|
||||
message_text: "Hello!".to_owned(),
|
||||
mentioned_users: vec![],
|
||||
timestamp,
|
||||
};
|
||||
|
||||
let allowed_user_message = MatrixMessage {
|
||||
@@ -23,6 +28,7 @@ fn is_message_from_allowed_sender() {
|
||||
message_type: MatrixMessageType::Text,
|
||||
message_text: "Hello!".to_owned(),
|
||||
mentioned_users: vec![],
|
||||
timestamp,
|
||||
};
|
||||
|
||||
let unallowed_user_message = MatrixMessage {
|
||||
@@ -30,6 +36,7 @@ fn is_message_from_allowed_sender() {
|
||||
message_type: MatrixMessageType::Text,
|
||||
message_text: "Hello!".to_owned(),
|
||||
mentioned_users: vec![],
|
||||
timestamp,
|
||||
};
|
||||
|
||||
let parsed_regex = match mxidwc::parse_pattern("@user.*:example.com") {
|
||||
@@ -77,11 +84,14 @@ async fn process_matrix_messages() {
|
||||
let allowed_user_id = OwnedUserId::try_from("@user.someone:example.com").unwrap();
|
||||
let unallowed_user_id = OwnedUserId::try_from("@another:example.com").unwrap();
|
||||
|
||||
let timestamp = Utc.with_ymd_and_hms(2024, 9, 20, 18, 34, 15).unwrap();
|
||||
|
||||
let allowed_user_message = MatrixMessage {
|
||||
sender_id: allowed_user_id.to_owned(),
|
||||
message_type: MatrixMessageType::Text,
|
||||
message_text: "Hello from the user!".to_owned(),
|
||||
mentioned_users: vec![],
|
||||
timestamp,
|
||||
};
|
||||
|
||||
let allowed_user_message_with_prefix = MatrixMessage {
|
||||
@@ -89,6 +99,7 @@ async fn process_matrix_messages() {
|
||||
message_type: MatrixMessageType::Text,
|
||||
message_text: "!bai Hello from the user!".to_owned(),
|
||||
mentioned_users: vec![],
|
||||
timestamp,
|
||||
};
|
||||
|
||||
let allowed_user_message_with_prefix_no_space = MatrixMessage {
|
||||
@@ -96,6 +107,7 @@ async fn process_matrix_messages() {
|
||||
message_type: MatrixMessageType::Text,
|
||||
message_text: "!baiHello from the user!".to_owned(),
|
||||
mentioned_users: vec![],
|
||||
timestamp,
|
||||
};
|
||||
|
||||
let allowed_user_message_with_prefix_full_width_space = MatrixMessage {
|
||||
@@ -103,6 +115,7 @@ async fn process_matrix_messages() {
|
||||
message_type: MatrixMessageType::Text,
|
||||
message_text: "!bai Hello from the user!".to_owned(),
|
||||
mentioned_users: vec![],
|
||||
timestamp,
|
||||
};
|
||||
|
||||
let bot_message = MatrixMessage {
|
||||
@@ -110,6 +123,7 @@ async fn process_matrix_messages() {
|
||||
message_type: MatrixMessageType::Text,
|
||||
message_text: "Hello from the bot!".to_owned(),
|
||||
mentioned_users: vec![],
|
||||
timestamp,
|
||||
};
|
||||
|
||||
let allowed_user_message_with_bot_mention = MatrixMessage {
|
||||
@@ -117,6 +131,7 @@ async fn process_matrix_messages() {
|
||||
message_type: MatrixMessageType::Text,
|
||||
message_text: "@baibot: Hello from the user!".to_owned(),
|
||||
mentioned_users: vec![bot_user_id.to_owned()],
|
||||
timestamp,
|
||||
};
|
||||
|
||||
// The message text is the same as above - it mentions the bot, but the actually-mentioned user is another user.
|
||||
@@ -125,6 +140,7 @@ async fn process_matrix_messages() {
|
||||
message_type: MatrixMessageType::Text,
|
||||
message_text: allowed_user_message_with_bot_mention.message_text.clone(),
|
||||
mentioned_users: vec![allowed_user_id.to_owned()],
|
||||
timestamp,
|
||||
};
|
||||
|
||||
let unallowed_user_message = MatrixMessage {
|
||||
@@ -132,6 +148,7 @@ async fn process_matrix_messages() {
|
||||
message_type: MatrixMessageType::Text,
|
||||
message_text: "Hello from an unallowed user!".to_owned(),
|
||||
mentioned_users: vec![],
|
||||
timestamp,
|
||||
};
|
||||
|
||||
let parsed_regex = match mxidwc::parse_pattern("@user.*:example.com") {
|
||||
@@ -279,13 +296,6 @@ async fn process_matrix_messages() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_rich_reply_fallback_text() {
|
||||
let text = "> <@admin:example.com> What's the difference between Matrix and XMPP?\n\nAnswer me";
|
||||
let stripped_text = super::strip_rich_reply_fallback_text(text);
|
||||
assert_eq!(stripped_text, "Answer me");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_list_of_bot_user_prefixes_to_strip() {
|
||||
let bot_user_id =
|
||||
|
||||
@@ -15,6 +15,8 @@ pub struct MessageContext {
|
||||
admin_whitelist_regexes: Vec<regex::Regex>,
|
||||
trigger_event_info: TriggerEventInfo,
|
||||
thread_info: ThreadInfo,
|
||||
|
||||
bot_display_name: Option<String>,
|
||||
}
|
||||
|
||||
impl MessageContext {
|
||||
@@ -31,9 +33,20 @@ impl MessageContext {
|
||||
admin_whitelist_regexes,
|
||||
trigger_event_info,
|
||||
thread_info,
|
||||
|
||||
bot_display_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_bot_display_name(mut self, value: Option<String>) -> Self {
|
||||
self.bot_display_name = value;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn bot_display_name(&self) -> &Option<String> {
|
||||
&self.bot_display_name
|
||||
}
|
||||
|
||||
pub fn room(&self) -> &Room {
|
||||
&self.room
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user