### Install Parlant SDK Source: https://github.com/emcie-co/parlant/blob/develop/README.md Install the Parlant SDK using pip. This is the first step to getting started with Parlant. ```bash pip install parlant ``` -------------------------------- ### Complete Parlant SDK Production Setup Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/openrouter.md This example demonstrates a production-ready setup for the Parlant SDK using OpenRouter, including API key, model, embedder model, token limit, tool integration, and guideline-based behavior control. ```bash # Set environment variables export OPENROUTER_API_KEY="your-api-key-here" export OPENROUTER_MODEL="openai/gpt-4o-mini" export OPENROUTER_EMBEDDER_MODEL="openai/text-embedding-3-large" export OPENROUTER_MAX_TOKENS="32768" ``` ```python import parlant.sdk as p from parlant.sdk import NLPServices @p.tool async def get_weather(context: p.ToolContext, city: str) -> p.ToolResult: # Your weather API logic here return p.ToolResult(f"Sunny, 72°F in {city}") async def main(): async with p.Server(nlp_service=NLPServices.openrouter) as server: agent = await server.create_agent( name="Weather Assistant", description="Helps users check weather conditions." ) await agent.create_guideline( condition="User asks about weather", action="Get weather information using the get_weather tool", tools=[get_weather] ) # 🎉 Ready at http://localhost:8800 if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Example Ollama Configuration for Development Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/ollama.md Example environment variable settings for a development setup, balancing speed and accuracy. Adjust API timeout for responsiveness. ```bash # For development (fast, good balance) export OLLAMA_MODEL="gemma3:4b" export OLLAMA_EMBEDDING_MODEL="nomic-embed-text" export OLLAMA_API_TIMEOUT="180" ``` -------------------------------- ### Quick Start: Create a Banking Assistant Agent Source: https://github.com/emcie-co/parlant/blob/develop/llms.txt This example demonstrates how to set up a basic banking assistant agent using Parlant. It includes defining a tool to get account balances and setting up guidelines for handling balance inquiries and unrelated topics. Run this script and access the agent via http://localhost:8800. ```python import parlant.sdk as p import asyncio @p.tool async def get_account_balance(context: p.ToolContext, account_id: str) -> p.ToolResult: # Your business logic here balance = 1234.56 return p.ToolResult(data={"balance": balance, "currency": "USD"}) async def main() -> None: async with p.Server() as server: agent = await server.create_agent( name="Banking Assistant", description="Helpful and professional banking support agent", ) # Add behavioral guidelines await agent.create_guideline( condition="The customer asks about their balance", action="Retrieve and clearly present their account balance", tools=[get_account_balance], ) await agent.create_guideline( condition="The customer asks about topics unrelated to banking", action="Politely decline and redirect to banking topics", ) # Server runs until shutdown - no additional code needed here. # When the process exits, the context manager handles cleanup automatically. if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Create Balanced Guideline Source: https://github.com/emcie-co/parlant/blob/develop/docs/production/agentic-design.md Implement guidelines with a balanced approach, providing specific instructions while allowing for flexibility. This example guides the agent to explain pricing tiers, emphasize value, and recommend based on customer needs. ```python await agent.create_guideline( condition="Customer asks about pricing", action="Explain our pricing tiers clearly, emphasize value, " "and ask about their specific needs to recommend the best fit" ) ``` -------------------------------- ### Cost-Optimized Setup with OpenRouter Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/openrouter.md Balance quality and cost by selecting a cost-effective LLM and a smaller embedding model. This setup prioritizes efficiency. ```bash export OPENROUTER_MODEL="openai/gpt-4o-mini" export OPENROUTER_EMBEDDER_MODEL="openai/text-embedding-3-small" ``` ```python async with p.Server(nlp_service=NLPServices.openrouter) as server: agent = await server.create_agent( name="Cost-Optimized Agent", description="Optimized for cost-effectiveness." ) ``` -------------------------------- ### Example: Create Hotel Glossary Term Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/customization/glossary.md An example demonstrating the creation of a glossary term for a hotel, including its name, description, and multiple synonyms. ```python await agent.create_term( name="Boogie Nights", description="Our luxury beachfront hotel located in Miami", synonyms=["BN Hotel", "The Boogie", "Boogie Hotel"], ) ``` -------------------------------- ### Implement Subscription Plan Variable Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/customization/variables.md Example of creating a tool-enabled variable for 'subscription_plan' and setting a default value for guest customers. ```python @p.tool async def get_subscription_plan(context: p.ToolContext) -> p.ToolResult: # Fetch the customer's subscription plan from your database return p.ToolResult(await get_plan_from_database(context.customer_id)) ``` ```python variable = await agent.create_variable( name="subscription_plan", description="The customer's subscription plan", tool=get_subscription_plan, ) await variable.set_value_for_customer( customer=p.Customer.guest(), value="Free Plan", # Default value for non-registered customers ) ``` -------------------------------- ### Example Ollama Configuration for Higher Accuracy Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/ollama.md Example environment variable settings for a higher accuracy configuration, potentially suitable for cloud environments. Note the increased API timeout. ```bash # higher accuracy cloud export OLLAMA_MODEL="gemma3:4b" export OLLAMA_EMBEDDING_MODEL="nomic-embed-text" export OLLAMA_API_TIMEOUT="600" ``` -------------------------------- ### Parlant Server with Default OpenRouter Configuration Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/openrouter.md Example of initializing a Parlant server with OpenRouter using default LLM and embedding models. ```python import parlant.sdk as p from parlant.sdk import NLPServices async with p.Server(nlp_service=NLPServices.openrouter) as server: agent = await server.create_agent( name="General Assistant", description="A helpful AI assistant." ) ``` -------------------------------- ### Install Parlant Development Version Source: https://github.com/emcie-co/parlant/blob/develop/docs/quickstart/installation.md Install the latest development version of Parlant directly from GitHub. ```bash pip install git+https://github.com/emcie-co/parlant@develop ``` -------------------------------- ### Install parlant-chat-react Widget Source: https://github.com/emcie-co/parlant/blob/develop/docs/production/custom-frontend.md Install the Parlant chat widget using npm or yarn. ```bash npm install parlant-chat-react # or yarn add parlant-chat-react ``` -------------------------------- ### Create Open Guideline Source: https://github.com/emcie-co/parlant/blob/develop/docs/production/agentic-design.md This example demonstrates an overly open guideline that can lead to unpredictable agent behavior. It lacks specific instructions for the agent's action. ```python await agent.create_guideline( condition="Customer asks about pricing", action="Help them understand our pricing" ) ``` -------------------------------- ### Install Parlant Python Client SDK Source: https://github.com/emcie-co/parlant/blob/develop/docs/quickstart/installation.md Install the Parlant client library for Python using pip. This is used for creating custom frontend applications that interact with the Parlant server. ```bash pip install parlant-client ``` -------------------------------- ### Set Ollama Model for High-Performance Cloud Setup Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/ollama.md Environment variables for a high-performance cloud setup with Ollama. Uses a large model and a standard API timeout. ```bash export OLLAMA_MODEL=llama3.1:70b export OLLAMA_API_TIMEOUT=300 ``` -------------------------------- ### Install Parlant with Vertex AI Dependencies Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/vertex.md Install the Parlant library with the optional 'vertex' dependencies to enable support for Vertex AI services, including Claude and Gemini models. ```bash pip install "parlant[vertex]" ``` -------------------------------- ### Create a Basic Guideline Source: https://github.com/emcie-co/parlant/blob/develop/docs/production/agentic-design.md Use `create_guideline` to set boundaries for agent behavior. This example shows a vague condition and action that may lead to undesirable outcomes. ```python agent.create_guideline( condition="Customer is unhappy", action="Make them feel better" ) ``` -------------------------------- ### Tool for Fetching Products Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/customization/tools.md An example tool that simulates fetching products based on a query. It takes a `query` string and returns a `ToolResult` containing the products. Ensure `MY_DB.get_products` is correctly implemented and accessible. ```python import parlant.sdk as p @p.tool async def find_products(context: p.ToolContext, query: str) -> p.ToolResult: """Fetch products based on a natural-language search query.""" # Simulate fetching the balance from a database or API products = await MY_DB.get_products(query=query) return p.ToolResult(balance) ``` -------------------------------- ### Run Parlant Server with Qdrant Agent Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/vector_db/qdrant.md This code snippet demonstrates how to start a Parlant server with the configured Qdrant adapter and create an agent. It then tests the integration by creating a term, which should be stored in Qdrant. ```python async def main(): async with p.Server(configure_container=configure_container) as server: agent = await server.create_agent( name="My Agent", description="Agent using Qdrant for persistent storage", ) # Test: Create a term to verify Qdrant is working term = await agent.create_term( name="Example Term", description="This is stored in Qdrant", ) print(f"Created term: {term.name}") # All vector operations now use Qdrant ``` -------------------------------- ### Install Parlant TypeScript/JavaScript Client SDK Source: https://github.com/emcie-co/parlant/blob/develop/docs/quickstart/installation.md Install the Parlant client library for TypeScript and JavaScript using npm. This is used for creating custom frontend applications that interact with the Parlant server. ```bash npm install parlant-client ``` -------------------------------- ### Run the Parlant Agent Script Source: https://github.com/emcie-co/parlant/blob/develop/docs/quickstart/installation.md Execute the Python script to start your Parlant agent. ```bash python main.py ``` -------------------------------- ### Basic Parlant Server Setup with Vertex AI Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/vertex.md Initialize a Parlant server using the Vertex AI NLP service. This allows you to create agents that leverage Vertex AI models. ```python import parlant.sdk as p from parlant.sdk import NLPServices async with p.Server(nlp_service=NLPServices.vertex) as server: agent = await server.create_agent( name="Healthcare Agent", description="Is empathetic and calming to the patient.", ) ``` -------------------------------- ### High-Performance Setup with OpenRouter Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/openrouter.md Optimize for speed and quality by setting specific models and maximum tokens. This configuration uses GPT-4o mini and a large embedding model, with a high token limit. ```bash export OPENROUTER_MODEL="openai/gpt-4o-mini" export OPENROUTER_EMBEDDER_MODEL="openai/text-embedding-3-large" export OPENROUTER_MAX_TOKENS="128000" ``` ```python async with p.Server(nlp_service=NLPServices.openrouter) as server: agent = await server.create_agent( name="High-Performance Agent", description="Optimized for speed and accuracy." ) ``` -------------------------------- ### Minimal Parlant Server Setup with OpenRouter Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/openrouter.md Initialize a Parlant server using the OpenRouter NLP service and create an AI agent. The server will be available at http://localhost:8800. ```python import parlant.sdk as p from parlant.sdk import NLPServices async with p.Server(nlp_service=NLPServices.openrouter) as server: agent = await server.create_agent( name="AI Assistant", description="A helpful assistant powered by OpenRouter.", ) # 🎉 Ready to use at http://localhost:8800 ``` -------------------------------- ### Create a Guideline for Out-of-Scope Topics Source: https://github.com/emcie-co/parlant/blob/develop/docs/production/agentic-design.md Implement guidelines to handle specific scenarios. This example instructs the agent to politely decline out-of-scope topics and redirect the conversation. ```python await agent.create_guideline( condition="Customer asks about topics outside your designated scope", action="Politely decline to discuss the topic and redirect to what you can help with" ) ``` -------------------------------- ### Create Rigid Guideline Source: https://github.com/emcie-co/parlant/blob/develop/docs/production/agentic-design.md Avoid overly rigid guidelines that feel scripted. This example shows a guideline with an exact response, limiting natural conversation. ```python await agent.create_guideline( condition="Customer asks about pricing", action="Say exactly: 'Our premium plan is $99/month'" ) ``` -------------------------------- ### Start Parlant Server with Custom NLP Service Source: https://github.com/emcie-co/parlant/blob/develop/docs/advanced/custom-llms.md Pass your custom NLP service loader function to the nlp_service parameter when initializing the Parlant server. ```python async with p.Server( nlp_service=load_custom_nlp_service, ) as server: # Your code here ``` -------------------------------- ### Create Customer Groups with Tags Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/entities/customers.md Assign customers to groups using tags for personalized experiences. This example creates a 'VIP' tag and assigns it to a new customer. ```python # Create a new tag to represent VIP customers vip_tag = await server.create_tag(name="VIP") # Register a new customer customer = await server.create_customer(name="Alice", tags=[vip_tag.id]) ``` -------------------------------- ### Combine Multiple Parlant SDK Configurations Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/openrouter.md Configure different aspects of the Parlant SDK by setting multiple environment variables. This example shows how to set the model, max tokens, and embedder model. ```bash # Set all configuration via environment variables export OPENROUTER_MODEL="anthropic/claude-3.5-sonnet" export OPENROUTER_MAX_TOKENS="200000" export OPENROUTER_EMBEDDER_MODEL="openai/text-embedding-3-large" ``` -------------------------------- ### Handle Policy Questions with Escalation Source: https://github.com/emcie-co/parlant/blob/develop/docs/production/agentic-design.md Use guidelines to handle edge cases gracefully. This example shows immediate escalation for policy questions when the agent lacks exact information, ensuring accurate support. ```python await agent.create_guideline( condition="Customer asks about a specific policy and you don't have the exact answer", action="Tell them you want to ensure they get accurate policy information, " "and offer to connect them to human support who can provide the specifics" ) ``` -------------------------------- ### Create Booking Journey Source: https://github.com/emcie-co/parlant/blob/develop/docs/production/agentic-design.md For complex multi-step processes like booking appointments, use Journeys instead of numerous guidelines. This example initiates a booking journey with a title, conditions, and description. ```python booking_journey = await agent.create_journey( title="Book Appointment", conditions=["Customer wants to schedule an appointment"], description="Guide customer through appointment booking process" ) ``` -------------------------------- ### Initialize Parlant Server and Agent Source: https://github.com/emcie-co/parlant/blob/develop/llms.txt Set up the Parlant server and create an agent. This involves using `p.Server()` as an async context manager and calling `server.create_agent()`. ```python async def main() -> None: async with p.Server() as server: agent = await server.create_agent( name="Support Agent", description="Friendly and efficient customer support representative", ) # Domain knowledge await agent.create_term( name="Express Shipping", description="2-day delivery, costs $9.99", ) # Create journey await create_order_journey(agent) # Global guidelines (apply everywhere) await agent.create_guideline( condition="Customer uses profanity or is abusive", action="Calmly ask them to be respectful, or offer to end the conversation", ) await agent.create_guideline( condition="Customer asks to speak to a human", action="Provide the support phone number: 1-800-555-0123", ) # Server runs until shutdown - no additional code needed here. # When the process exits, the context manager handles cleanup automatically. if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Redirect Competitor Questions Source: https://github.com/emcie-co/parlant/blob/develop/docs/production/agentic-design.md Manage competitor-related questions with a guideline that redirects the conversation back to the company's products. This example acknowledges the question, states focus, and prompts for needs to recommend internal options. ```python await agent.create_guideline( condition="Customer asks about competitor products or pricing", action="Acknowledge their question, explain that you focus on our own products, " "and ask specifically what features or capabilities they're looking for " "so you can recommend the best option from our lineup" ) ``` -------------------------------- ### Troubleshooting: Model Not Found Error Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/ollama.md Example error message for a missing Ollama model and the corresponding solution: pulling the model before starting Parlant. ```bash Model gemma3:4b not found. Please pull it first with: ollama pull gemma3:4b **Solution**: Run `ollama pull gemma3:4b-it-qat` before starting Parlant ``` -------------------------------- ### Create a Multi-Step Interaction Journey Source: https://github.com/emcie-co/parlant/blob/develop/llms.txt Define structured, multi-step interaction flows using `agent.create_journey`. This example shows chaining states with transitions, starting from an initial state and moving through chat and tool states to a final end state. ```python journey = await agent.create_journey( title="Order Support", description="Helps customers with order issues", conditions=["The customer has an order-related question"], ) # Chain states with transitions t0 = await journey.initial_state.transition_to(chat_state="Ask for order number") t1 = await t0.target.transition_to(tool_state=lookup_order) t2 = await t1.target.transition_to( chat_state="Present order status", condition="Order was found", ) await t2.target.transition_to(state=p.END_JOURNEY) ``` -------------------------------- ### Install Parlant with Cerebras Extra Source: https://github.com/emcie-co/parlant/blob/develop/docs/quickstart/installation.md Install the 'cerebras' extra package for Parlant to enable the Cerebras NLP service. ```bash pip install parlant[cerebras] ``` -------------------------------- ### Create a New Customer with Parlant SDK Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/entities/customers.md Use this snippet to register a new customer using the Parlant SDK. Ensure the server is initialized. ```python import parlant.sdk as p async with p.Server() as server: # Register a new customer customer = await server.create_customer(name="Alice") ``` -------------------------------- ### Install Parlant Chat React Package Source: https://github.com/emcie-co/parlant/blob/develop/docs/quickstart/installation.md Install the official Parlant React widget using npm. This command is used in a frontend project built with React. ```bash npm install parlant-chat-react ``` -------------------------------- ### Create and Configure an Agent with Parlant SDK Source: https://github.com/emcie-co/parlant/blob/develop/README.md Asynchronously create an agent, define observations based on specific conditions, and set up guidelines for how the agent should respond. Use `p.MATCH_ALWAYS` for guidelines that should always apply when their dependencies are met. Exclude specific observations to prevent them from influencing the agent's behavior under certain conditions. ```python import parlant.sdk as p async with p.Server(): agent = await server.create_agent( name="Customer Support", description="Handles customer inquiries for an airline", ) # Evaluate and call tools only under the right conditions expert_customer = await agent.create_observation( condition="customer uses financial terminology like DTI or amortization", tools=[research_deep_answer], ) # When the expert observation holds, always respond # with depth. Set the guideline to automatically match # whenever the observation it depends on holds... expert_answers = await agent.create_guideline( matcher=p.MATCH_ALWAYS, action="respond with technical depth", dependencies=[expert_customer], ) beginner_answers = await agent.create_guideline( condition="customer seems new to the topic", action="simplify and use concrete examples", ) # When both match, beginners wins. Neither expert-level # tool-data nor instructions can enter the agent's context. await beginner_answers.exclude(expert_customer) ``` -------------------------------- ### Install Parlant with Snowflake Dependency Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/persistence/snowflake.md Install the Parlant package with the optional Snowflake dependency using pip. This ensures all necessary libraries for Snowflake integration are included. ```bash pip install "parlant[snowflake]" ``` -------------------------------- ### Initialize Async Parlant Client (Python) Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/sessions.md Initialize the asynchronous Parlant client. Change 'localhost' to your server's address. The async client is recommended for production to handle events in real-time without blocking. ```python from parlant.client import AsyncParlantClient # Change localhost to your server's address client = AsyncParlantClient(base_url="http://localhost:8800") ``` -------------------------------- ### Create Guideline for Product Ordering Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/customization/guidelines.md Use this to create a guideline that customizes an agent's initial response when a customer wants to order a laptop, making it more personable. ```python await agent.create_guideline( condition="The customer wants to buy a laptop", action="First, determine whether they prefer Mac or Windows" ) ``` -------------------------------- ### Troubleshooting: Connection Error Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/ollama.md Example error message for failing to connect to the Ollama server and the solution: ensuring the Ollama server is running. ```bash Cannot connect to Ollama server at http://localhost:11434 **Solution**: Ensure Ollama is running with `ollama serve` ``` -------------------------------- ### Create a Basic Parlant Agent Source: https://github.com/emcie-co/parlant/blob/develop/docs/quickstart/installation.md Spin up an initial Parlant agent using Python's asyncio. Ensure the OPENAI_API_KEY environment variable is set. ```python # main.py import asyncio import parlant.sdk as p async def main(): async with p.Server() as server: agent = await server.create_agent( name="Otto Carmen", description="You work at a car dealership", ) asyncio.run(main()) ``` -------------------------------- ### Configuration and Best Practices Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/vertex.md Guidance on configuring Vertex AI services and best practices for model selection and error handling. ```APIDOC ## Configuration and Best Practices ### Model Selection 1. **Claude Sonnet 3.5**: Best balance of performance and cost. 2. **Claude Opus 4**: Maximum capability with fallback. 3. **Gemini 2.5 Flash**: Fast processing with large context. 4. **Gemini 2.5 Pro**: Complex reasoning tasks. ### Configuration ```bash export VERTEX_AI_PROJECT_ID=your-project-id export VERTEX_AI_REGION=us-central1 export VERTEX_AI_MODEL=claude-sonnet-3.5 ``` ### Error Handling Example ```python from parlant.adapters.nlp.vertex_service import VertexAIAuthError try: service = VertexAIService(logger=logger) generator = await service.get_schematic_generator(MySchema) result = await generator.generate(prompt) except VertexAIAuthError as e: logger.error(f"Authentication failed: {e}") # Handle auth setup except Exception as e: logger.error(f"Generation failed: {e}") # Handle other errors ``` ``` -------------------------------- ### Define Tool with Parameter Source Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/customization/tools.md Use ToolParameterOptions to specify the source of a parameter, such as 'customer'. This guides the agent on where to obtain the required value. ```python from typing import Annotated import parlant.sdk as p @p.tool async def transfer_money( context: p.ToolContext, amount: Annotated[float, p.ToolParameterOptions( source="customer", # Only the customer can provide this value - the agent cannot infer it )], recipient: Annotated[str, p.ToolParameterOptions( source="customer", )] ) -> ToolResult: # ... ``` -------------------------------- ### Create Agent and Add Guideline with Python SDK Source: https://github.com/emcie-co/parlant/blob/develop/docs/quickstart/installation.md Use this Python code to create a new agent and define a guideline that triggers a specific action based on a condition. Ensure the parlant.sdk is imported. ```python import asyncio import parlant.sdk as p async def main(): async with p.Server() as server: agent = await server.create_agent( name="Otto Carmen", description="You work at a car dealership", ) ############################## ## Add the following: ## ############################## await agent.create_guideline( # This is when the guideline will be triggered condition="the customer greets you", # This is what the guideline instructs the agent to do action="offer a refreshing drink", ) asyncio.run(main()) ``` -------------------------------- ### Usage Example: Parlant SDK with Snowflake NLP Service Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/snowflake-cortex.md Demonstrates how to use the Parlant SDK to create an agent that leverages Snowflake's NLP services. Includes defining tools, variables, and guidelines for agent behavior. ```python import parlant.sdk as p from parlant.sdk import NLPServices @p.tool async def get_weather(context: p.ToolContext, city: str) -> p.ToolResult: # Your weather API logic here return p.ToolResult(f"Sunny, 72°F in {city}") @p.tool async def get_datetime(context: p.ToolContext) -> p.ToolResult: from datetime import datetime return p.ToolResult(datetime.now()) async def main(): async with p.Server(nlp_service=NLPServices.snowflake) as server: agent = await server.create_agent( name="WeatherBot", description="Helpful weather assistant" ) # Have the agent's context be updated on every response (though # update interval is customizable) using a context variable. await agent.create_variable(name="current-datetime", tool=get_datetime) # Control and guide agent behavior with natural language await agent.create_guideline( condition="User asks about weather", action="Get current weather and provide a friendly response with suggestions", tools=[get_weather] ) # Add other (reliably enforced) behavioral modeling elements # ... # 🎉 Test playground ready at http://localhost:8800 # Integrate the official React widget into your app, # or follow the tutorial to build your own frontend! if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Verify ADC Token Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/vertex.md Command to verify Application Default Credentials (ADC) token for authentication troubleshooting. Useful for confirming authentication setup. ```bash gcloud auth application-default print-access-token ``` -------------------------------- ### NLP-Based Assertion Examples Source: https://github.com/emcie-co/parlant/blob/develop/llms.txt Demonstrates how to use the `response.should()` method for NLP-based assertions. It can be used for single conditions or multiple conditions evaluated in parallel. ```python # Single condition await response.should("be polite and professional") ``` ```python # Multiple conditions (evaluated in parallel) await response.should([ "ask for the reason for the visit", "be polite", "not mention pricing", ]) ``` -------------------------------- ### Troubleshooting: Timeout Error Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/ollama.md Example error message for a request timeout with Ollama and the solution: increasing the API timeout or using a smaller model. ```bash Request timed out after 300s **Solution**: Increase `OLLAMA_API_TIMEOUT` or use a smaller model ``` -------------------------------- ### Parlant CLI Test Execution Commands Source: https://github.com/emcie-co/parlant/blob/develop/llms.txt Provides examples of command-line interface commands for running Parlant tests. Includes options for running all tests, filtering by pattern, parallel execution, and setting custom timeouts. ```bash # Run all tests parlant-test tests.py ``` ```bash # Filter by pattern parlant-test tests.py -k "greeting" ``` ```bash # Run tests in parallel parlant-test tests.py --parallel ``` ```bash # Custom timeout (seconds) parlant-test tests.py --timeout 120 ``` -------------------------------- ### Parlant Test Hooks Source: https://github.com/emcie-co/parlant/blob/develop/llms.txt Defines setup and teardown hooks for test execution. `before_all` and `after_all` run once, while `before_each` and `after_each` run before and after each test, respectively. ```python @suite.before_all async def setup() -> None: # Runs once before all tests suite.context["api_key"] = "test-key" ``` ```python @suite.after_all async def teardown() -> None: # Runs once after all tests pass ``` ```python @suite.before_each async def before_test(test_name: str) -> None: # Runs before each test pass ``` ```python @suite.after_each async def after_test(test_name: str, passed: bool, error: str | None) -> None: # Runs after each test pass ``` -------------------------------- ### Set Ollama Model for Development Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/ollama.md Environment variables for a development setup using Ollama. Sets a specific model and API timeout for faster iteration. ```bash export OLLAMA_MODEL=gemma3:4b export OLLAMA_API_TIMEOUT=180 ``` -------------------------------- ### Initialize Parlant Server with Custom Container Configuration Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/persistence/snowflake.md Starts the Parlant server using a custom container configuration, specifying Snowflake as the NLP service and providing the `configure_container` function. Ensures `shutdown_snowflake` is called in the `finally` block to close resources. ```python async def main() -> None: try: async with p.Server( nlp_service=p.NLPServices.snowflake, configure_container=configure_container, ) as server: ... finally: await shutdown_snowflake() ``` -------------------------------- ### Persist Customers to Local Storage Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/entities/customers.md Configure Parlant to store customer data in a local JSON file for development and testing. This requires no additional setup. ```python import asyncio import parlant.sdk as p async def main(): async with p.Server(customer_store="local") as server: # ... asyncio.run(main()) ``` -------------------------------- ### Example: Using Different Azure OpenAI Models Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/azure.md These bash commands show how to set environment variables to use specific Azure OpenAI models like GPT-3.5 Turbo or GPT-4 Turbo, and how to revert to default models. ```bash # Use GPT-3.5 Turbo (if available in your region) export AZURE_ENDPOINT="https://your-resource.openai.azure.com/" export AZURE_GENERATIVE_MODEL_NAME="gpt-35-turbo" export AZURE_EMBEDDING_MODEL_NAME="text-embedding-ada-002" # Use GPT-4 Turbo (if available in your region) export AZURE_GENERATIVE_MODEL_NAME="gpt-4-turbo" export AZURE_EMBEDDING_MODEL_NAME="text-embedding-3-large" # Use default models (GPT-4o and text-embedding-3-large) export AZURE_ENDPOINT="https://your-resource.openai.azure.com/" # No need to set AZURE_GENERATIVE_MODEL_NAME or AZURE_EMBEDDING_MODEL_NAME ``` -------------------------------- ### Create a New Agent Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/entities/agents.md Use this snippet to create a new agent with a specified name and description. Ensure the parlant.sdk is imported and the server is running. ```python import parlant.sdk as p async with p.Server() as server: hexon = await server.agents.create( name="Hexon", description="Technical support specialist" ) # Continue to model the agent's behavior using guidelines, journeys, etc.... ``` -------------------------------- ### Troubleshooting: Out of Memory Error Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/ollama.md Example error message for running out of memory (CUDA) with Ollama and the solution: using a smaller model or increasing GPU memory. ```bash CUDA out of memory **Solution**: Use a smaller model size or increase GPU memory ``` -------------------------------- ### Retrieve Customer Metadata in a Tool Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/entities/customers.md Example of a Parlant tool that retrieves a customer's location from their metadata. This demonstrates how tools can access customer-specific information. ```python @p.tool async def get_customer_location(context: p.ToolContext) -> p.ToolResult: server = p.ToolContextAccessor(context).server if customer := await server.find_customer(id=context.customer_id): return p.ToolResult(customer.metadata.get("location", "Unknown location")) return p.ToolResult("Customer not found") ``` -------------------------------- ### Initialize Parlant Server with Ollama Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/ollama.md Initialize a Parlant server using the Ollama NLP service. This asynchronous code snippet demonstrates creating an agent with a specified name and description. ```python import parlant.sdk as p from parlant.sdk import NLPServices async with p.Server(nlp_service=NLPServices.ollama) as server: agent = await server.create_agent( name="Healthcare Agent", description="Is empathetic and calming to the patient.", ) ``` -------------------------------- ### Register Customer via Parlant Client SDK Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/entities/customers.md Create and manage customers using the Parlant Client SDK, integrating with your application's authentication and authorization systems. Ensure the client is configured with the correct server address. ```python from parlant.client import ParlantClient # Change localhost to your server's address client = ParlantClient("http://localhost:8800") client.customers.create( name="Alice", metadata={ "external_id": "12345", "location": "USA", "hobby": "reading", }, tags=[TAG_ID] # Optional: specify tag IDs to assign to the customer ) ``` -------------------------------- ### Configure Parlant Server with Cerebras NLP Service Source: https://github.com/emcie-co/parlant/blob/develop/docs/quickstart/installation.md Instantiate the Parlant server with a specific NLP service, such as Cerebras. This may require installing additional packages. ```python async with p.Server(nlp_service=p.NLPServices.cerebras) as server: ... ``` -------------------------------- ### Azure CLI Login for Local Development Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/azure.md Use Azure CLI for local development authentication. Ensure Azure CLI is installed and log in to your Azure account. ```bash # Install Azure CLI if not already installed # https://docs.microsoft.com/en-us/cli/azure/install-azure-cli # Login to Azure az login # Set your endpoint export AZURE_ENDPOINT="https://your-resource.openai.azure.com/" ``` -------------------------------- ### Create a Glossary Term Source: https://github.com/emcie-co/parlant/blob/develop/README.md Maps colloquial terms and synonyms to precise business definitions for the agent to understand customer language. ```python await agent.create_term( name="Ocean View", description="Room category with direct view of the Atlantic", synonyms=["sea view", "rooms with a view to the Atlantic"], ) ``` -------------------------------- ### Create and Test Persistent Term Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/vector_db/qdrant.md Create a term and test its persistence by restarting the server. Ensure Qdrant is configured for persistent storage. ```python term = await agent.create_term( name="Test Term", description="This should be stored in Qdrant", ) # Then chat with agent about "test term" - it should understand via vector search # Test persistence: close the server and run again # The term should still be available after restart ``` -------------------------------- ### Create Guidelines in Python Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/customization/relationships.md Use `agent.create_guideline` to define conditions and actions for agent behavior. Requires an initialized agent object. ```python offer_pepsi_instead_of_coke = await agent.create_guideline( condition="The customer wants a coke", action="Tell them we only have Pepsi", ) ``` ```python handoff_if_upset = await agent.create_guideline( condition="The customer is becoming upset", action="Apologize and tell them you will transfer them to a manager", tools=[handoff_to_human_manager], ) ``` -------------------------------- ### Use Claude for Text Generation Source: https://github.com/emcie-co/parlant/blob/develop/docs/adapters/nlp/openrouter.md Set the OPENROUTER_MODEL environment variable to use Claude for text generation. This example initializes a server with the OpenRouter NLP service. ```bash export OPENROUTER_MODEL="anthropic/claude-3.5-sonnet" ``` ```python async with p.Server(nlp_service=NLPServices.openrouter) as server: agent = await server.create_agent( name="Claude Assistant", description="Powered by Claude." ) ``` -------------------------------- ### Persist Sessions to MongoDB Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/sessions.md Configure Parlant to use MongoDB for session persistence in production environments. Specify the connection string to your MongoDB database when starting the server. ```python import asyncio import parlant.sdk as p async def main(): async with p.Server(session_store="mongodb://path.to.your.host:27017") as server: # ... asyncio.run(main()) ``` -------------------------------- ### Valid Conversational Journey (Mermaid) Source: https://github.com/emcie-co/parlant/blob/develop/docs/concepts/customization/journeys.md This Mermaid diagram depicts a valid conversation journey, guiding a customer through a process with distinct conversational steps and decision points. ```mermaid stateDiagram-v2 direction LR state "Ask for order number" as A state "Get order details" as B state "Process refund" as C state "Transfer to human" as D [*] --> A A --> B B --> C: Eligible for refund B --> D: Not eligible for refund C --> [*] D --> [*] style B fill:#ffeecc,stroke:#333,stroke-width:1px ```