123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440 |
- import textwrap
- from typing import Optional
- from fastapi import Body, Depends, Path, Query
- from core.base import R2RException
- from core.base.api.models import (
- GenericBooleanResponse,
- GenericMessageResponse,
- WrappedBooleanResponse,
- WrappedGenericMessageResponse,
- WrappedPromptResponse,
- WrappedPromptsResponse,
- )
- from ...abstractions import R2RProviders, R2RServices
- from .base_router import BaseRouterV3
- class PromptsRouter(BaseRouterV3):
- def __init__(
- self,
- providers: R2RProviders,
- services: R2RServices,
- ):
- super().__init__(providers, services)
- def _setup_routes(self):
- @self.router.post(
- "/prompts",
- dependencies=[Depends(self.rate_limit_dependency)],
- summary="Create a new prompt",
- openapi_extra={
- "x-codeSamples": [
- {
- "lang": "Python",
- "source": textwrap.dedent(
- """
- from r2r import R2RClient
- client = R2RClient()
- # when using auth, do client.login(...)
- result = client.prompts.create(
- name="greeting_prompt",
- template="Hello, {name}!",
- input_types={"name": "string"}
- )
- """
- ),
- },
- {
- "lang": "JavaScript",
- "source": textwrap.dedent(
- """
- const { r2rClient } = require("r2r-js");
- const client = new r2rClient();
- function main() {
- const response = await client.prompts.create({
- name: "greeting_prompt",
- template: "Hello, {name}!",
- inputTypes: { name: "string" },
- });
- }
- main();
- """
- ),
- },
- {
- "lang": "cURL",
- "source": textwrap.dedent(
- """
- curl -X POST "https://api.example.com/v3/prompts" \\
- -H "Authorization: Bearer YOUR_API_KEY" \\
- -H "Content-Type: application/json" \\
- -d '{"name": "greeting_prompt", "template": "Hello, {name}!", "input_types": {"name": "string"}}'
- """
- ),
- },
- ]
- },
- )
- @self.base_endpoint
- async def create_prompt(
- name: str = Body(..., description="The name of the prompt"),
- template: str = Body(
- ..., description="The template string for the prompt"
- ),
- input_types: dict[str, str] = Body(
- default={},
- description="A dictionary mapping input names to their types",
- ),
- auth_user=Depends(self.providers.auth.auth_wrapper()),
- ) -> WrappedGenericMessageResponse:
- """
- Create a new prompt with the given configuration.
- This endpoint allows superusers to create a new prompt with a specified name, template, and input types.
- """
- if not auth_user.is_superuser:
- raise R2RException(
- "Only a superuser can create prompts.",
- 403,
- )
- result = await self.services.management.add_prompt(
- name, template, input_types
- )
- return GenericMessageResponse(message=result) # type: ignore
- @self.router.get(
- "/prompts",
- dependencies=[Depends(self.rate_limit_dependency)],
- summary="List all prompts",
- openapi_extra={
- "x-codeSamples": [
- {
- "lang": "Python",
- "source": textwrap.dedent(
- """
- from r2r import R2RClient
- client = R2RClient()
- # when using auth, do client.login(...)
- result = client.prompts.list()
- """
- ),
- },
- {
- "lang": "JavaScript",
- "source": textwrap.dedent(
- """
- const { r2rClient } = require("r2r-js");
- const client = new r2rClient();
- function main() {
- const response = await client.prompts.list();
- }
- main();
- """
- ),
- },
- {
- "lang": "CLI",
- "source": textwrap.dedent(
- """
- r2r prompts list
- """
- ),
- },
- {
- "lang": "cURL",
- "source": textwrap.dedent(
- """
- curl -X GET "https://api.example.com/v3/prompts" \\
- -H "Authorization: Bearer YOUR_API_KEY"
- """
- ),
- },
- ]
- },
- )
- @self.base_endpoint
- async def get_prompts(
- auth_user=Depends(self.providers.auth.auth_wrapper()),
- ) -> WrappedPromptsResponse:
- """
- List all available prompts.
- This endpoint retrieves a list of all prompts in the system. Only superusers can access this endpoint.
- """
- if not auth_user.is_superuser:
- raise R2RException(
- "Only a superuser can list prompts.",
- 403,
- )
- get_prompts_response = (
- await self.services.management.get_all_prompts()
- )
- return ( # type: ignore
- get_prompts_response["results"],
- {
- "total_entries": get_prompts_response["total_entries"],
- },
- )
- @self.router.post(
- "/prompts/{name}",
- dependencies=[Depends(self.rate_limit_dependency)],
- summary="Get a specific prompt",
- openapi_extra={
- "x-codeSamples": [
- {
- "lang": "Python",
- "source": textwrap.dedent(
- """
- from r2r import R2RClient
- client = R2RClient()
- # when using auth, do client.login(...)
- result = client.prompts.get(
- "greeting_prompt",
- inputs={"name": "John"},
- prompt_override="Hi, {name}!"
- )
- """
- ),
- },
- {
- "lang": "JavaScript",
- "source": textwrap.dedent(
- """
- const { r2rClient } = require("r2r-js");
- const client = new r2rClient();
- function main() {
- const response = await client.prompts.retrieve({
- name: "greeting_prompt",
- inputs: { name: "John" },
- promptOverride: "Hi, {name}!",
- });
- }
- main();
- """
- ),
- },
- {
- "lang": "CLI",
- "source": textwrap.dedent(
- """
- r2r prompts retrieve greeting_prompt --inputs '{"name": "John"}' --prompt-override "Hi, {name}!"
- """
- ),
- },
- {
- "lang": "cURL",
- "source": textwrap.dedent(
- """
- curl -X POST "https://api.example.com/v3/prompts/greeting_prompt?inputs=%7B%22name%22%3A%22John%22%7D&prompt_override=Hi%2C%20%7Bname%7D!" \\
- -H "Authorization: Bearer YOUR_API_KEY"
- """
- ),
- },
- ]
- },
- )
- @self.base_endpoint
- async def get_prompt(
- name: str = Path(..., description="Prompt name"),
- inputs: Optional[dict[str, str]] = Body(
- None, description="Prompt inputs"
- ),
- prompt_override: Optional[str] = Query(
- None, description="Prompt override"
- ),
- auth_user=Depends(self.providers.auth.auth_wrapper()),
- ) -> WrappedPromptResponse:
- """
- Get a specific prompt by name, optionally with inputs and override.
- This endpoint retrieves a specific prompt and allows for optional inputs and template override.
- Only superusers can access this endpoint.
- """
- if not auth_user.is_superuser:
- raise R2RException(
- "Only a superuser can retrieve prompts.",
- 403,
- )
- result = await self.services.management.get_prompt(
- name, inputs, prompt_override
- )
- return result # type: ignore
- @self.router.put(
- "/prompts/{name}",
- dependencies=[Depends(self.rate_limit_dependency)],
- summary="Update an existing prompt",
- openapi_extra={
- "x-codeSamples": [
- {
- "lang": "Python",
- "source": textwrap.dedent(
- """
- from r2r import R2RClient
- client = R2RClient()
- # when using auth, do client.login(...)
- result = client.prompts.update(
- "greeting_prompt",
- template="Greetings, {name}!",
- input_types={"name": "string", "age": "integer"}
- )
- """
- ),
- },
- {
- "lang": "JavaScript",
- "source": textwrap.dedent(
- """
- const { r2rClient } = require("r2r-js");
- const client = new r2rClient();
- function main() {
- const response = await client.prompts.update({
- name: "greeting_prompt",
- template: "Greetings, {name}!",
- inputTypes: { name: "string", age: "integer" },
- });
- }
- main();
- """
- ),
- },
- {
- "lang": "cURL",
- "source": textwrap.dedent(
- """
- curl -X PUT "https://api.example.com/v3/prompts/greeting_prompt" \\
- -H "Authorization: Bearer YOUR_API_KEY" \\
- -H "Content-Type: application/json" \\
- -d '{"template": "Greetings, {name}!", "input_types": {"name": "string", "age": "integer"}}'
- """
- ),
- },
- ]
- },
- )
- @self.base_endpoint
- async def update_prompt(
- name: str = Path(..., description="Prompt name"),
- template: Optional[str] = Body(
- None, description="Updated prompt template"
- ),
- input_types: dict[str, str] = Body(
- default={},
- description="A dictionary mapping input names to their types",
- ),
- auth_user=Depends(self.providers.auth.auth_wrapper()),
- ) -> WrappedGenericMessageResponse:
- """
- Update an existing prompt's template and/or input types.
- This endpoint allows superusers to update the template and input types of an existing prompt.
- """
- if not auth_user.is_superuser:
- raise R2RException(
- "Only a superuser can update prompts.",
- 403,
- )
- result = await self.services.management.update_prompt(
- name, template, input_types
- )
- return GenericMessageResponse(message=result) # type: ignore
- @self.router.delete(
- "/prompts/{name}",
- dependencies=[Depends(self.rate_limit_dependency)],
- summary="Delete a prompt",
- openapi_extra={
- "x-codeSamples": [
- {
- "lang": "Python",
- "source": textwrap.dedent(
- """
- from r2r import R2RClient
- client = R2RClient()
- # when using auth, do client.login(...)
- result = client.prompts.delete("greeting_prompt")
- """
- ),
- },
- {
- "lang": "JavaScript",
- "source": textwrap.dedent(
- """
- const { r2rClient } = require("r2r-js");
- const client = new r2rClient();
- function main() {
- const response = await client.prompts.delete({
- name: "greeting_prompt",
- });
- }
- main();
- """
- ),
- },
- {
- "lang": "CLI",
- "source": textwrap.dedent(
- """
- r2r prompts delete greeting_prompt
- """
- ),
- },
- {
- "lang": "cURL",
- "source": textwrap.dedent(
- """
- curl -X DELETE "https://api.example.com/v3/prompts/greeting_prompt" \\
- -H "Authorization: Bearer YOUR_API_KEY"
- """
- ),
- },
- ]
- },
- )
- @self.base_endpoint
- async def delete_prompt(
- name: str = Path(..., description="Prompt name"),
- auth_user=Depends(self.providers.auth.auth_wrapper()),
- ) -> WrappedBooleanResponse:
- """
- Delete a prompt by name.
- This endpoint allows superusers to delete an existing prompt.
- """
- if not auth_user.is_superuser:
- raise R2RException(
- "Only a superuser can delete prompts.",
- 403,
- )
- await self.services.management.delete_prompt(name)
- return GenericBooleanResponse(success=True) # type: ignore
|