123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631 |
- import logging
- import textwrap
- from typing import Optional
- from uuid import UUID
- from fastapi import Body, Depends, Path, Query
- from core.base import Message, R2RException
- from core.base.api.models import (
- GenericBooleanResponse,
- WrappedBooleanResponse,
- WrappedConversationMessagesResponse,
- WrappedConversationResponse,
- WrappedConversationsResponse,
- WrappedMessageResponse,
- )
- from ...abstractions import R2RProviders, R2RServices
- from .base_router import BaseRouterV3
- logger = logging.getLogger()
- class ConversationsRouter(BaseRouterV3):
- def __init__(
- self,
- providers: R2RProviders,
- services: R2RServices,
- ):
- super().__init__(providers, services)
- def _setup_routes(self):
- @self.router.post(
- "/conversations",
- summary="Create a new conversation",
- dependencies=[Depends(self.rate_limit_dependency)],
- openapi_extra={
- "x-codeSamples": [
- {
- "lang": "Python",
- "source": textwrap.dedent(
- """
- from r2r import R2RClient
- client = R2RClient()
- # when using auth, do client.login(...)
- result = client.conversations.create()
- """
- ),
- },
- {
- "lang": "JavaScript",
- "source": textwrap.dedent(
- """
- const { r2rClient } = require("r2r-js");
- const client = new r2rClient();
- function main() {
- const response = await client.conversations.create();
- }
- main();
- """
- ),
- },
- {
- "lang": "CLI",
- "source": textwrap.dedent(
- """
- r2r conversations create
- """
- ),
- },
- {
- "lang": "cURL",
- "source": textwrap.dedent(
- """
- curl -X POST "https://api.example.com/v3/conversations" \\
- -H "Authorization: Bearer YOUR_API_KEY"
- """
- ),
- },
- ]
- },
- )
- @self.base_endpoint
- async def create_conversation(
- name: Optional[str] = Body(
- None, description="The name of the conversation", embed=True
- ),
- auth_user=Depends(self.providers.auth.auth_wrapper()),
- ) -> WrappedConversationResponse:
- """
- Create a new conversation.
- This endpoint initializes a new conversation for the authenticated user.
- """
- user_id = auth_user.id
- return await self.services.management.create_conversation(
- user_id=user_id,
- name=name,
- )
- @self.router.get(
- "/conversations",
- summary="List conversations",
- dependencies=[Depends(self.rate_limit_dependency)],
- openapi_extra={
- "x-codeSamples": [
- {
- "lang": "Python",
- "source": textwrap.dedent(
- """
- from r2r import R2RClient
- client = R2RClient()
- # when using auth, do client.login(...)
- result = client.conversations.list(
- offset=0,
- limit=10,
- )
- """
- ),
- },
- {
- "lang": "JavaScript",
- "source": textwrap.dedent(
- """
- const { r2rClient } = require("r2r-js");
- const client = new r2rClient();
- function main() {
- const response = await client.conversations.list();
- }
- main();
- """
- ),
- },
- {
- "lang": "CLI",
- "source": textwrap.dedent(
- """
- r2r conversations list
- """
- ),
- },
- {
- "lang": "cURL",
- "source": textwrap.dedent(
- """
- curl -X GET "https://api.example.com/v3/conversations?offset=0&limit=10" \\
- -H "Authorization: Bearer YOUR_API_KEY"
- """
- ),
- },
- ]
- },
- )
- @self.base_endpoint
- async def list_conversations(
- ids: list[str] = Query(
- [],
- description="A list of conversation IDs to retrieve. If not provided, all conversations will be returned.",
- ),
- offset: int = Query(
- 0,
- ge=0,
- description="Specifies the number of objects to skip. Defaults to 0.",
- ),
- limit: int = Query(
- 100,
- ge=1,
- le=1000,
- description="Specifies a limit on the number of objects to return, ranging between 1 and 100. Defaults to 100.",
- ),
- auth_user=Depends(self.providers.auth.auth_wrapper()),
- ) -> WrappedConversationsResponse:
- """
- List conversations with pagination and sorting options.
- This endpoint returns a paginated list of conversations for the authenticated user.
- """
- requesting_user_id = (
- None if auth_user.is_superuser else [auth_user.id]
- )
- conversation_uuids = [
- UUID(conversation_id) for conversation_id in ids
- ]
- conversations_response = (
- await self.services.management.conversations_overview(
- offset=offset,
- limit=limit,
- conversation_ids=conversation_uuids,
- user_ids=requesting_user_id,
- )
- )
- return conversations_response["results"], { # type: ignore
- "total_entries": conversations_response["total_entries"]
- }
- @self.router.get(
- "/conversations/{id}",
- summary="Get conversation details",
- dependencies=[Depends(self.rate_limit_dependency)],
- openapi_extra={
- "x-codeSamples": [
- {
- "lang": "Python",
- "source": textwrap.dedent(
- """
- from r2r import R2RClient
- client = R2RClient()
- # when using auth, do client.login(...)
- result = client.conversations.get(
- "123e4567-e89b-12d3-a456-426614174000"
- )
- """
- ),
- },
- {
- "lang": "JavaScript",
- "source": textwrap.dedent(
- """
- const { r2rClient } = require("r2r-js");
- const client = new r2rClient();
- function main() {
- const response = await client.conversations.retrieve({
- id: "123e4567-e89b-12d3-a456-426614174000",
- });
- }
- main();
- """
- ),
- },
- {
- "lang": "CLI",
- "source": textwrap.dedent(
- """
- r2r conversations retrieve 123e4567-e89b-12d3-a456-426614174000
- """
- ),
- },
- {
- "lang": "cURL",
- "source": textwrap.dedent(
- """
- curl -X GET "https://api.example.com/v3/conversations/123e4567-e89b-12d3-a456-426614174000" \\
- -H "Authorization: Bearer YOUR_API_KEY"
- """
- ),
- },
- ]
- },
- )
- @self.base_endpoint
- async def get_conversation(
- id: UUID = Path(
- ..., description="The unique identifier of the conversation"
- ),
- auth_user=Depends(self.providers.auth.auth_wrapper()),
- ) -> WrappedConversationMessagesResponse:
- """
- Get details of a specific conversation.
- This endpoint retrieves detailed information about a single conversation identified by its UUID.
- """
- requesting_user_id = (
- None if auth_user.is_superuser else [auth_user.id]
- )
- conversation = await self.services.management.get_conversation(
- conversation_id=id,
- user_ids=requesting_user_id,
- )
- return conversation
- @self.router.post(
- "/conversations/{id}",
- summary="Update conversation",
- dependencies=[Depends(self.rate_limit_dependency)],
- openapi_extra={
- "x-codeSamples": [
- {
- "lang": "Python",
- "source": textwrap.dedent(
- """
- from r2r import R2RClient
- client = R2RClient()
- # when using auth, do client.login(...)
- result = client.conversations.update("123e4567-e89b-12d3-a456-426614174000", "new_name")
- """
- ),
- },
- {
- "lang": "JavaScript",
- "source": textwrap.dedent(
- """
- const { r2rClient } = require("r2r-js");
- const client = new r2rClient();
- function main() {
- const response = await client.conversations.update({
- id: "123e4567-e89b-12d3-a456-426614174000",
- name: "new_name",
- });
- }
- main();
- """
- ),
- },
- {
- "lang": "CLI",
- "source": textwrap.dedent(
- """
- r2r conversations delete 123e4567-e89b-12d3-a456-426614174000
- """
- ),
- },
- {
- "lang": "cURL",
- "source": textwrap.dedent(
- """
- curl -X POST "https://api.example.com/v3/conversations/123e4567-e89b-12d3-a456-426614174000" \
- -H "Authorization: Bearer YOUR_API_KEY" \
- -H "Content-Type: application/json" \
- -d '{"name": "new_name"}'
- """
- ),
- },
- ]
- },
- )
- @self.base_endpoint
- async def update_conversation(
- id: UUID = Path(
- ...,
- description="The unique identifier of the conversation to delete",
- ),
- name: str = Body(
- ...,
- description="The updated name for the conversation",
- embed=True,
- ),
- auth_user=Depends(self.providers.auth.auth_wrapper()),
- ) -> WrappedConversationResponse:
- """
- Update an existing conversation.
- This endpoint updates the name of an existing conversation identified by its UUID.
- """
- return await self.services.management.update_conversation(
- conversation_id=id,
- name=name,
- )
- @self.router.delete(
- "/conversations/{id}",
- summary="Delete conversation",
- dependencies=[Depends(self.rate_limit_dependency)],
- openapi_extra={
- "x-codeSamples": [
- {
- "lang": "Python",
- "source": textwrap.dedent(
- """
- from r2r import R2RClient
- client = R2RClient()
- # when using auth, do client.login(...)
- result = client.conversations.delete("123e4567-e89b-12d3-a456-426614174000")
- """
- ),
- },
- {
- "lang": "JavaScript",
- "source": textwrap.dedent(
- """
- const { r2rClient } = require("r2r-js");
- const client = new r2rClient();
- function main() {
- const response = await client.conversations.delete({
- id: "123e4567-e89b-12d3-a456-426614174000",
- });
- }
- main();
- """
- ),
- },
- {
- "lang": "CLI",
- "source": textwrap.dedent(
- """
- r2r conversations delete 123e4567-e89b-12d3-a456-426614174000
- """
- ),
- },
- {
- "lang": "cURL",
- "source": textwrap.dedent(
- """
- curl -X DELETE "https://api.example.com/v3/conversations/123e4567-e89b-12d3-a456-426614174000" \\
- -H "Authorization: Bearer YOUR_API_KEY"
- """
- ),
- },
- ]
- },
- )
- @self.base_endpoint
- async def delete_conversation(
- id: UUID = Path(
- ...,
- description="The unique identifier of the conversation to delete",
- ),
- auth_user=Depends(self.providers.auth.auth_wrapper()),
- ) -> WrappedBooleanResponse:
- """
- Delete an existing conversation.
- This endpoint deletes a conversation identified by its UUID.
- """
- requesting_user_id = (
- None if auth_user.is_superuser else [auth_user.id]
- )
- await self.services.management.delete_conversation(
- conversation_id=id,
- user_ids=requesting_user_id,
- )
- return GenericBooleanResponse(success=True) # type: ignore
- @self.router.post(
- "/conversations/{id}/messages",
- summary="Add message to conversation",
- dependencies=[Depends(self.rate_limit_dependency)],
- openapi_extra={
- "x-codeSamples": [
- {
- "lang": "Python",
- "source": textwrap.dedent(
- """
- from r2r import R2RClient
- client = R2RClient()
- # when using auth, do client.login(...)
- result = client.conversations.add_message(
- "123e4567-e89b-12d3-a456-426614174000",
- content="Hello, world!",
- role="user",
- parent_id="parent_message_id",
- metadata={"key": "value"}
- )
- """
- ),
- },
- {
- "lang": "JavaScript",
- "source": textwrap.dedent(
- """
- const { r2rClient } = require("r2r-js");
- const client = new r2rClient();
- function main() {
- const response = await client.conversations.addMessage({
- id: "123e4567-e89b-12d3-a456-426614174000",
- content: "Hello, world!",
- role: "user",
- parentId: "parent_message_id",
- });
- }
- main();
- """
- ),
- },
- {
- "lang": "cURL",
- "source": textwrap.dedent(
- """
- curl -X POST "https://api.example.com/v3/conversations/123e4567-e89b-12d3-a456-426614174000/messages" \\
- -H "Authorization: Bearer YOUR_API_KEY" \\
- -H "Content-Type: application/json" \\
- -d '{"content": "Hello, world!", "parent_id": "parent_message_id", "metadata": {"key": "value"}}'
- """
- ),
- },
- ]
- },
- )
- @self.base_endpoint
- async def add_message(
- id: UUID = Path(
- ..., description="The unique identifier of the conversation"
- ),
- content: str = Body(
- ..., description="The content of the message to add"
- ),
- role: str = Body(
- ..., description="The role of the message to add"
- ),
- parent_id: Optional[UUID] = Body(
- None, description="The ID of the parent message, if any"
- ),
- metadata: Optional[dict[str, str]] = Body(
- None, description="Additional metadata for the message"
- ),
- auth_user=Depends(self.providers.auth.auth_wrapper()),
- ) -> WrappedMessageResponse:
- """
- Add a new message to a conversation.
- This endpoint adds a new message to an existing conversation.
- """
- if content == "":
- raise R2RException("Content cannot be empty", status_code=400)
- if role not in ["user", "assistant", "system"]:
- raise R2RException("Invalid role", status_code=400)
- message = Message(role=role, content=content)
- return await self.services.management.add_message(
- conversation_id=id,
- content=message,
- parent_id=parent_id,
- metadata=metadata,
- )
- @self.router.post(
- "/conversations/{id}/messages/{message_id}",
- summary="Update message in conversation",
- dependencies=[Depends(self.rate_limit_dependency)],
- openapi_extra={
- "x-codeSamples": [
- {
- "lang": "Python",
- "source": textwrap.dedent(
- """
- from r2r import R2RClient
- client = R2RClient()
- # when using auth, do client.login(...)
- result = client.conversations.update_message(
- "123e4567-e89b-12d3-a456-426614174000",
- "message_id_to_update",
- content="Updated content"
- )
- """
- ),
- },
- {
- "lang": "JavaScript",
- "source": textwrap.dedent(
- """
- const { r2rClient } = require("r2r-js");
- const client = new r2rClient();
- function main() {
- const response = await client.conversations.updateMessage({
- id: "123e4567-e89b-12d3-a456-426614174000",
- messageId: "message_id_to_update",
- content: "Updated content",
- });
- }
- main();
- """
- ),
- },
- {
- "lang": "cURL",
- "source": textwrap.dedent(
- """
- curl -X POST "https://api.example.com/v3/conversations/123e4567-e89b-12d3-a456-426614174000/messages/message_id_to_update" \\
- -H "Authorization: Bearer YOUR_API_KEY" \\
- -H "Content-Type: application/json" \\
- -d '{"content": "Updated content"}'
- """
- ),
- },
- ]
- },
- )
- @self.base_endpoint
- async def update_message(
- id: UUID = Path(
- ..., description="The unique identifier of the conversation"
- ),
- message_id: UUID = Path(
- ..., description="The ID of the message to update"
- ),
- content: Optional[str] = Body(
- None, description="The new content for the message"
- ),
- metadata: Optional[dict[str, str]] = Body(
- None, description="Additional metadata for the message"
- ),
- auth_user=Depends(self.providers.auth.auth_wrapper()),
- ) -> WrappedMessageResponse:
- """
- Update an existing message in a conversation.
- This endpoint updates the content of an existing message in a conversation.
- """
- return await self.services.management.edit_message(
- message_id=message_id,
- new_content=content,
- additional_metadata=metadata,
- )
|