Sarvam Conv AI SDK
The Sarvam Conversational AI SDK is a Python package that helps developers build and extend conversational agents. It provides core components to manage conversation flow, language preferences, and messaging, making it easier to develop interactive and context-aware AI experiences.Overview
The Sarvam Conv AI SDK enables developers to create tools that can:- Facilitate agentic capabilities like API calling in the middle of a conversation.
- Manage agent-specific variables
- Control and modify the language used during conversations
- Send dynamic messages to both the user and the underlying language model (LLM)
Installation
Install the SDK via pip:Example Usage
Base Classes
The SDK exposes three base classes for tool development:1. SarvamTool
Primary base class for all operational tools invoked during conversation flow.
Example:
2. SarvamOnStartTool
Executed at the beginning of a conversation, typically for initialization. The class must be named OnStart
.
3. SarvamOnEndTool
Executed at the end of a conversation, typically for cleanup or post-processing. The class must be named OnEnd
.
Context Classes and Methods
SarvamToolContext
The context object passed to SarvamTool.run()
methods.
Variable Management
-
get_agent_variable(variable_name: str) -> Any
Retrieve the value of a variable. -
set_agent_variable(variable_name: str, value: Any) -> None
Update a variable’s value.
Language Control
-
get_current_language() -> SarvamToolLanguageName
Returns the current language of the agent. -
change_language(language: SarvamToolLanguageName) -> None
Update the language preference.
Conversation Flow
set_end_conversation() -> None
Explicitly end the conversation.
State Management
-
get_current_state() -> str
Returns the current state of the conversation. -
change_state(state: str) -> None
Transition to a new state. Note: The new state must be one of the next valid states defined in the agent configuration.
Engagement Metadata
get_engagement_metadata() -> EngagementMetadata
Retrieve the engagement metadata containing information about the current interaction.
SarvamOnStartToolContext
The context object passed to SarvamOnStartTool.run()
methods.
Variable Management
-
get_agent_variable(variable_name: str) -> Any
Retrieve the value of a variable. -
set_agent_variable(variable_name: str, value: Any) -> None
Update a variable’s value.
User Information
get_user_identifier() -> str
Get the user identifier.
Initialization Methods
-
set_initial_bot_message(message: str) -> None
Set the first message sent by the agent when the conversation starts. -
set_initial_state_name(state_name: str) -> None
Set the initial state from which the agent should start. -
set_initial_language_name(language: SarvamToolLanguageName) -> None
Define the initial language preference for the user.
Engagement Metadata
get_engagement_metadata() -> EngagementMetadata
Retrieve the engagement metadata containing information about the current interaction.
SarvamOnEndToolContext
The context object passed to SarvamOnEndTool.run()
methods.
Variable Management
-
get_agent_variable(variable_name: str) -> Any
Retrieve the value of a variable. -
set_agent_variable(variable_name: str, value: Any) -> None
Update a variable’s value.
User Information
get_user_identifier() -> str
Get the user identifier.
Engagement Metadata
get_engagement_metadata() -> EngagementMetadata
Retrieve the engagement metadata containing information about the current interaction.
Interaction Reattempt
set_retry_interaction
The user will be reattempted with the same agent. Useful when any business goal has not been met.
Interaction Transcript
get_interaction_transcript() -> SarvamInteractionTranscript
Retrieve the conversation history containing user and agent messages in English and the timestamp when the conversation began and ended. Format:yyyy-mm-dd hh:mm:ss
Return Types
SarvamToolOutput
The return type for SarvamTool.run()
methods. Contains:
message_to_user: Optional[str]
- Message that is sent directly to the usermessage_to_llm: Optional[str]
- Message that is sent to the LLM, which then respondscontext: SarvamToolContext
- The updated context object
message_to_llm
or message_to_user
must be set.
Important: When both message_to_user
and message_to_llm
are set, only the message_to_user
is actually sent to the user, but the message_to_llm
overrides the message_to_user
when adding to the chat thread for the LLM’s context.
EngagementMetadata
The engagement metadata object that can be retrieved from context objects using get_engagement_metadata()
. Contains:
interaction_id: str
- Unique identifier for each conversation between user & agent.attempt_id: Optional[str]
- Unique identifier for each attempt created on the platformcampaign_id: Optional[str]
- Campaign ID for the interactioninteraction_language: SarvamToolLanguageName
- The language used for the interaction (defaults to English)app_id: str
- Application identifier of the agent for the interactionapp_version: int
- Version number of the agentagent_phone_number: Optional[str]
- Phone number associated with the conversational agent application
Supported Languages
The SDK supports multilingual conversations using theSarvamToolLanguageName
enum. Available languages include:
- Bengali
- Gujarati
- Kannada
- Malayalam
- Tamil
- Telugu
- Punjabi
- Odia
- Marathi
- Hindi
- English
Best Practices
- Always implement
run()
: Therun()
method is the entry point for tool execution logic. - Use
Field()
for parameters: Ensures type safety and adds descriptive metadata necessary for LLM to use in the prompt. - Gracefully handle errors: Avoid accessing unset variables or using invalid types.
- Return the appropriate type:
SarvamTool.run()
must returnSarvamToolOutput
, whileSarvamOnStartTool.run()
andSarvamOnEndTool.run()
return their respective context objects. - Write meaningful docstrings: Clearly describe what each tool is intended to do as this directly impacts the performance of tool calling capabilities of the agent.
- Use async operations for I/O: For the best performance, use
async/await
for external API calls to avoid blocking. - Use context methods: Use the provided context methods for variable management, language control, and messaging instead of directly accessing context attributes.
Error Handling
The SDK includes built-in error handling for common scenarios:- Variable not found: Raises ValueError when accessing undefined variables
- Variable not defined: Raises ValueError when setting variables that haven’t been initialized
- Non-serializable values: Raises ValueError when variable values cannot be JSON serialized
- Invalid output: Raises ValueError when
SarvamToolOutput
is created without at least one message
Testing Your Tools
After creating a tool, you can test it locally to ensure it works as expected. Here’s how to test your tools:Testing Steps
- Create the ToolContext: Initialize the appropriate context object with test data
- Instantiate the tool class: Use
tool.model_validate(tool_args)
to create a tool instance - Run the tool: Call the tool’s
run()
method with the context - Observe the returned object: Check if the necessary changes have been made to the context
Example Test: SarvamTool
Example Test: OnStart Tool
ForSarvamOnStartTool
, the testing approach is similar but it returns the context object directly: