### Portia AI Example Files Overview Source: https://docs.portialabs.ai/getting-started-tour This table outlines the example Python files provided in the Portia AI getting started tour. Each entry specifies the filename, its primary focus, and the key features it introduces to the user. ```markdown Example File | Focus | Features Introduced ---|---|--- `1_github_oauth.py` | OAuth API use | OAuth, basic agent commands `2_tools_end_users_llms.py` | Multi-tool agent | End users, multi-step reasoning `3_mcp.py` | Running MCP Tools | MCP format, structured execution `4_browser_use.py` | Web automation | Browser automation, local & remote modes ``` -------------------------------- ### Install SteelThread with uv Source: https://docs.portialabs.ai/steel-thread-quickstart Adds the steel-thread library as a dependency using the uv package manager. ```bash uv add steel-thread ``` -------------------------------- ### Install SteelThread with Poetry Source: https://docs.portialabs.ai/steel-thread-quickstart Adds the steel-thread library as a dependency using the Poetry package manager. ```bash poetry add steel-thread ``` -------------------------------- ### Test Installation from Python (OpenAI) Source: https://docs.portialabs.ai/install Tests the Portia installation by running a query from a Python script using OpenAI as the LLM provider. Requires setting OPENAI_API_KEY in a .env file. ```python from dotenv import load_dotenv from portia import( Portia, default_config, example_tool_registry, ) load_dotenv() # Instantiate Portia with the default config which uses Open AI, and with some example tools. portia = Portia(tools=example_tool_registry) # Run the test query and print the output! plan_run = portia.run('add 1 + 2') print(plan_run.model_dump_json(indent=2)) ``` -------------------------------- ### Install Portia SDK with Extra Dependencies Source: https://docs.portialabs.ai/install Installs the Portia SDK with additional dependencies for specific LLM providers. Use '[all]' for all providers, or specify individual providers like '[amazon]', '[google]', or '[mistral]'. ```bash pip install"portia-sdk-python[all]" # Or only with Amazon Bedrock extra dependencies pip install"portia-sdk-python[amazon]" # Or only with Google GenAI extra dependencies pip install"portia-sdk-python[google]" # Or only with Mistral extra dependencies pip install"portia-sdk-python[mistral]" ``` -------------------------------- ### Create a Dataset with Portia Source: https://docs.portialabs.ai/steel-thread-quickstart Runs a Portia query to process user feedback from a local file and identify recurring themes. Requires a PORTIA_API_KEY environment variable. ```python from portia import Portia path ="./uxr/calorify.txt"# TODO: change to your desired path query =f"Read the user feedback notes in local file{path}, \ and call out recurring themes in their feedback. \ Use lots of ⚠️ emojis when highlighting areas of concern." Portia().run(query=query) ``` -------------------------------- ### Test Installation from Python (Mistral) Source: https://docs.portialabs.ai/install Tests the Portia installation by running a query from a Python script using Mistral AI as the LLM provider. Requires setting MISTRAL_API_KEY in a .env file. ```python import os from dotenv import load_dotenv from portia import( Config, LLMProvider, Portia, example_tool_registry, ) load_dotenv() MISTRAL_API_KEY = os.getenv('MISTRAL_API_KEY') ``` -------------------------------- ### Run Portia CLI with Default (OpenAI) Source: https://docs.portialabs.ai/install Executes a basic prompt using the Portia CLI with OpenAI as the default LLM provider. This is a fundamental test to ensure the installation is working correctly. ```bash portia-cli run "add 1 + 2" ``` -------------------------------- ### Install SteelThread with Pip Source: https://docs.portialabs.ai/steel-thread-quickstart Installs the steel-thread library using the pip package manager. ```bash pip install steel-thread ``` -------------------------------- ### Process a Stream with SteelThread Source: https://docs.portialabs.ai/steel-thread-quickstart Processes a stream of data using SteelThread, leveraging built-in evaluators. Requires a configured stream in the Portia dashboard and a PORTIA_API_KEY. ```python from portia import Config from steelthread.steelthread import SteelThread, StreamConfig from dotenv import load_dotenv load_dotenv(override=True) config = Config.from_default() # Setup SteelThread instance and process stream st = SteelThread() st.process_stream( StreamConfig( # The stream name is the name of the stream we created in the dashboard. stream_name="your-stream-name-here", config=config, ) ) ``` -------------------------------- ### Test Installation from Python (Anthropic) Source: https://docs.portialabs.ai/install Tests the Portia installation by running a query from a Python script using Anthropic as the LLM provider. Requires setting ANTHROPIC_API_KEY in a .env file and configuring the model. ```python import os from dotenv import load_dotenv from portia import( Config, LLMProvider, Portia, example_tool_registry, ) load_dotenv() ANTHROPIC_API_KEY = os.getenv('ANTHROPIC_API_KEY') # Create a default Portia config with LLM provider set to Anthropic and to the Sonnet 3.5 model anthropic_config = Config.from_default( llm_provider=LLMProvider.ANTHROPIC, default_model="anthropic/claude-3-5-sonnet-latest", anthropic_api_key=ANTHROPIC_API_KEY ) # Instantiate a Portia instance. Load it with the config and with the example tools. portia = Portia(config=anthropic_config, tools=example_tool_registry) # Run the test query and print the output! plan_run = portia.run('add 1 + 2') print(plan_run.model_dump_json(indent=2)) ``` -------------------------------- ### Install Portia Python SDK Source: https://docs.portialabs.ai/install Installs the Portia SDK and its core dependencies using pip. For alternative package managers like Poetry or uv, use their respective add commands. ```bash pip install portia-sdk-python ``` -------------------------------- ### Run Example Script Source: https://docs.portialabs.ai/getting-started-tour Command to execute the Python script containing the Portia browser automation example. ```shell uv run 4_browser_use.py ``` -------------------------------- ### Run Test Query with Portia SDK Source: https://docs.portialabs.ai/install Executes a test query using the Portia SDK and prints the JSON output. This snippet demonstrates a basic interaction with the Portia library for running queries and inspecting results. ```python plan_run = portia.run('add 1 + 2') print(plan_run.model_dump_json(indent=2)) ``` -------------------------------- ### Complete Portia Project Setup with Chargebee Source: https://docs.portialabs.ai/portia-tools/local-mcp/chargebee Provides a complete example of equipping a Portia instance with Chargebee MCP tools alongside default tools. It shows the instantiation of Config, DefaultToolRegistry, McpToolRegistry, and the Portia class. ```python from portia import DefaultToolRegistry, McpToolRegistry, Portia, Config config = Config.from_default() tool_registry = DefaultToolRegistry(config)+ McpToolRegistry.from_stdio_connection( server_name="chargebee", command="npx", args=["-y","@chargebee/mcp@latest"], ) portia = Portia(config=config, tools=tool_registry) ``` -------------------------------- ### Run Portia CLI with Anthropic Source: https://docs.portialabs.ai/install Executes a basic prompt using the Portia CLI, specifically targeting the Anthropic LLM provider. This demonstrates how to switch providers via the command line. ```bash portia-cli run --llm-provider="anthropic""add 1 + 2" ``` -------------------------------- ### Configure Portia with Google GenAI Source: https://docs.portialabs.ai/install Sets up Portia with Google GenAI, using the Gemini 2.0 Flash model. Requires GOOGLE_API_KEY to be set in the environment. ```python import os from dotenv import load_dotenv from portia import ( Config, LLMProvider, Portia, example_tool_registry, ) load_dotenv() GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY') # Create a default Portia config with LLM provider set to Google GenAI and model set to Gemini 2.0 Flash google_config = Config.from_default( llm_provider=LLMProvider.GOOGLE, default_model="google/gemini-2.0-flash", google_api_key=GOOGLE_API_KEY ) # Instantiate a Portia instance. Load it with the config and with the example tools. portia = Portia(config=google_config, tools=example_tool_registry) # Run the test query and print the output! plan_run = portia.run('add 1 + 2') print(plan_run.model_dump_json(indent=2)) ``` -------------------------------- ### Configure Google GenAI API Key Source: https://docs.portialabs.ai/install Sets the environment variable for the Google GenAI API key. 'gemini-2.5-pro' and 'gemini-2.5-flash' are used by default. Ensure Google GenAI dependencies are installed. ```bash export GOOGLE_API_KEY='your-api-key-here' ``` -------------------------------- ### End-to-End Example with Clarification Handling Source: https://docs.portialabs.ai/browser-tools A full example demonstrating how to run a task using BrowserTool and handle ActionClarifications, including user guidance and resuming the plan. ```python from dotenv import load_dotenv from portia import( ActionClarification, Config, PlanRunState, Portia, ) from portia.open_source_tools.browser_tool import BrowserTool load_dotenv(override=True) task ="Get the top news headline from the BBC news website (https://www.bbc.co.uk/news)" portia = Portia(Config.from_default(), tools=[BrowserTool()]) plan_run = portia.run(task) while plan_run.state == PlanRunState.NEED_CLARIFICATION: # If clarifications are needed, resolve them before resuming the workflow print("\nPlease resolve the following clarifications to continue") for clarification in plan_run.get_outstanding_clarifications(): # Handling of Action clarifications if isinstance(clarification, ActionClarification): print(f"{clarification.user_guidance} -- Please click on the link below to proceed.") print(clarification.action_url) input("Press Enter to continue...") # Once clarifications are resolved, resume the workflow plan_run = portia.resume(plan_run) ``` -------------------------------- ### Run Portia CLI with Google GenAI Source: https://docs.portialabs.ai/install Executes a basic prompt using the Portia CLI, specifically targeting the Google Generative AI provider. This allows testing integration with Google's AI services. ```bash portia-cli run --llm-provider="google""add 1 + 2" ``` -------------------------------- ### Complete Portia Setup with Shopify Dev Source: https://docs.portialabs.ai/portia-tools/local-mcp/shopify-dev Provides a complete example of equipping a Portia instance with Shopify Dev tools alongside default tools. It shows the instantiation of Config, DefaultToolRegistry, McpToolRegistry, and Portia. ```python from portia import DefaultToolRegistry, McpToolRegistry, Portia, Config config = Config.from_default() tool_registry = DefaultToolRegistry(config) + McpToolRegistry.from_stdio_connection( server_name="shopify-dev", command="npx", args=["@shopify/dev-mcp@latest"], ) portia = Portia(config=config, tools=tool_registry) ``` -------------------------------- ### Configure Portia with Azure OpenAI Source: https://docs.portialabs.ai/install Sets up Portia with Azure OpenAI, using the GPT-4o model. Requires AZURE_OPENAI_API_KEY and AZURE_OPENAI_ENDPOINT to be set in the environment. ```python import os from dotenv import load_dotenv from portia import ( Config, LLMProvider, Portia, example_tool_registry, ) load_dotenv() AZURE_OPENAI_API_KEY = os.getenv('AZURE_OPENAI_API_KEY') AZURE_OPENAI_ENDPOINT = os.getenv('AZURE_OPENAI_ENDPOINT') # Create a default Portia config with LLM provider set to Azure OpenAI and model to GPT 4o azure_config = Config.from_default( llm_provider=LLMProvider.AZURE_OPENAI, default_model="azure-openai/gpt-4o", azure_openai_api_key=AZURE_OPENAI_API_KEY, azure_openai_endpoint=AZURE_OPENAI_ENDPOINT, ) # Instantiate a Portia instance. Load it with the config and with the example tools. portia = Portia(config=azure_config, tools=example_tool_registry) ``` -------------------------------- ### Run Portia CLI with Azure OpenAI Source: https://docs.portialabs.ai/install Executes a basic prompt using the Portia CLI, specifically targeting the Azure OpenAI provider. This is useful for users leveraging Azure's OpenAI offerings. ```bash portia-cli run --llm-provider="azure-openai""add 1 + 2" ``` -------------------------------- ### GitHub OAuth Integration Example - Portia SDK Source: https://docs.portialabs.ai/getting-started-tour An example of using Portia to integrate with third-party APIs via OAuth. This script shows how an agent can perform user-specific actions like starring GitHub repositories or checking Google Calendar availability. ```python # File : 1_github_oauth.py # This is the most straightforward example of using Portia to connect to third-party APIs with OAuth. # It demonstrates how an agent can perform actions on behalf of a user, such as starring a GitHub repository or checking availability on their Google Calendar. # Key concepts: # * OAuth authentication for third-party services. # * Use of `Portia` with multiple tools. # * Simple command execution. ``` -------------------------------- ### Run Portia CLI with Mistral Source: https://docs.portialabs.ai/install Executes a basic prompt using the Portia CLI, specifically targeting the Mistral AI LLM provider. This showcases the flexibility in choosing different AI models. ```bash portia-cli run --llm-provider="mistralai""add 1 + 2" ``` -------------------------------- ### Configure Portia with Mistral AI Source: https://docs.portialabs.ai/install Sets up Portia with Mistral AI, using the latest Mistral Large model. Requires MISTRAL_API_KEY to be set in the environment. ```python import os from dotenv import load_dotenv from portia import ( Config, LLMProvider, Portia, example_tool_registry, ) load_dotenv() MISTRAL_API_KEY = os.getenv('MISTRAL_API_KEY') # Create a default Portia config with LLM provider set to Mistral AI and the latest Mistral Large model mistral_config = Config.from_default( llm_provider=LLMProvider.MISTRALAI, default_model="mistralai/mistral-large-latest", mistralai_api_key=MISTRAL_API_KEY ) # Instantiate a Portia instance. Load it with the config and with the example tools. portia = Portia(config=mistral_config, tools=example_tool_registry) # Run the test query and print the output! plan_run = portia.run('add 1 + 2') print(plan_run.model_dump_json(indent=2)) ``` -------------------------------- ### Plan JSON Example Source: https://docs.portialabs.ai/run-plan An example of a plan definition in JSON format, outlining the steps, tools, and inputs required for execution. ```json { "id":"plan-1dcd74a4-0af5-490a-a7d0-0df4fd983977", "plan_context":{ "query":"Which stock price grew faster, Amazon or Google?", "tool_ids":[ "calculator_tool", "weather_tool", "search_tool" ] }, "steps":[ { "task":"Search for the latest stock price growth data for Amazon.", "inputs":[], "tool_id":"search_tool", "output":"$amazon_stock_growth" }, { "task":"Search for the latest stock price growth data for Google.", "inputs":[], "tool_id":"search_tool", "output":"$google_stock_growth" }, { "task":"Compare the stock price growth of Amazon and Google.", "inputs":[ { "name":"$amazon_stock_growth", "description":"The stock price growth data for Amazon." }, { "name":"$google_stock_growth", "description":"The stock price growth data for Google." } ], "tool_id":"llm_tool", "output":"$stock_growth_comparison" } ] } ``` -------------------------------- ### Run Portia CLI with Amazon Bedrock Source: https://docs.portialabs.ai/install Executes a basic prompt using the Portia CLI, specifically targeting Amazon Bedrock for LLM access. This enables testing with AWS's managed AI services. ```bash portia-cli run --llm-provider="amazon""add 1 + 2" ``` -------------------------------- ### Integrate Perplexity MCP Server with Portia Source: https://docs.portialabs.ai/portia-tools/local-mcp/perplexity Provides a complete example of equipping a Portia instance with tools from the Perplexity MCP server, alongside default tools. It shows the setup of configuration, tool registries, and the Portia instance. ```python from portia import DefaultToolRegistry, McpToolRegistry, Portia, Config config = Config.from_default() tool_registry = DefaultToolRegistry(config)+ McpToolRegistry.from_stdio_connection( server_name="perplexity-ask", command="npx", args=["-y","server-perplexity-ask"], env={"PERPLEXITY_API_KEY":""}, ) portia = Portia(config=config, tools=tool_registry) ``` -------------------------------- ### Portia Plan Structure Example Source: https://docs.portialabs.ai/generate-plan An example JSON representation of a `Plan` object, illustrating its structure including ID, context, and a sequence of steps with tasks, inputs, tool IDs, and outputs. ```json { "id":"plan-1dcd74a4-0af5-490a-a7d0-0df4fd983977", "plan_context":{ "query":"Which stock price grew faster, Amazon or Google?", "tool_ids":["calculator_tool","weather_tool","search_tool"] }, "steps":[ { "task":"Search for the latest stock price growth data for Amazon.", "inputs":[], "tool_id":"search_tool", "output":"$amazon_stock_growth" }, { "task":"Search for the latest stock price growth data for Google.", "inputs":[], "tool_id":"search_tool", "output":"$google_stock_growth" }, { "task":"Compare the stock price growth of Amazon and Google.", "inputs":[ { "name":"$amazon_stock_growth", "value":null, "description":"The stock price growth data for Amazon." }, { "name":"$google_stock_growth", "value":null, "description":"The stock price growth data for Google." } ], "tool_id":"llm_tool", "output":"$stock_growth_comparison" } ] } ``` -------------------------------- ### Plan Run State JSON Example Source: https://docs.portialabs.ai/manage-end-users An example JSON output representing the state of a completed Portia plan run. It includes details like plan ID, status, step outputs, and the final personalized output. ```json { "id":"prun-d9991518-92d7-447f-bf28-4f7b9b8110ce", "plan_id":"plan-4f497c60-c33e-40ea-95b4-cd2054559fff", "current_step_index":1, "clarifications":[], "state":"COMPLETE", "end_user_id":"DemoUser123", "step_outputs":{ "$svalbard_temperature":{ "value":"The current weather in Svalbard is light snow with a temperature of -11.53°C." }, "$personalized_greeting":{ "value":"Hello Nicholas of Patara, I hope you are keeping warm. With the current weather in Svalbard showing light snow and a temperature of -11.53°C, make sure to bundle up and stay cozy!" } }, "final_output":{ "value":"Hello Nicholas of Patara, I hope you are keeping warm. With the current weather in Svalbard showing light snow and a temperature of -11.53°C, make sure to bundle up and stay cozy!" } } ``` -------------------------------- ### Instantiating Portia Runner Source: https://docs.portialabs.ai/getting-started-tour Demonstrates how to instantiate a Portia runner, loading default configuration from the environment and including Portia cloud tools along with CLI execution hooks for user interaction during execution. ```python # Instantiate a Portia runner. # Load it with the default config from the environment, and with Portia cloud tools. ``` -------------------------------- ### Check Python Version Source: https://docs.portialabs.ai/install Command to verify the installed Python version. Portia requires Python 3.11 or higher. ```bash python3 --version ``` -------------------------------- ### Python Example: Running Portia Tools Source: https://docs.portialabs.ai/run-portia-tools This snippet demonstrates the core functionality of the Portia library. It shows how to initialize Portia with default configurations and tools, generate an execution plan from a natural language query, and then execute that plan. It also includes logic to handle various clarification types (InputClarification, MultipleChoiceClarification, ActionClarification) that might arise during plan execution, allowing for user interaction or external actions. ```python from dotenv import load_dotenv from portia import ( ActionClarification, InputClarification, MultipleChoiceClarification, PlanRunState, Portia, PortiaToolRegistry, default_config, ) load_dotenv() # Instantiate a Portia instance. Load it with the default config and with Portia cloud tools above portia = Portia(tools=PortiaToolRegistry(default_config())) # Generate the plan from the user query and print it plan = portia.plan('Find the github repository of PortiaAI and give it a star for me') print(f"{plan.model_dump_json(indent=2)}") # Run the plan plan_run = portia.run_plan(plan) while plan_run.state == PlanRunState.NEED_CLARIFICATION: # If clarifications are needed, resolve them before resuming the plan run for clarification in plan_run.get_outstanding_clarifications(): # Usual handling of Input and Multiple Choice clarifications if isinstance(clarification, (InputClarification, MultipleChoiceClarification)): print(f"{clarification.user_guidance}") user_input = input("Please enter a value:\n" + (("\n".join(clarification.options)+"\n") if "options" in clarification else "")) plan_run = portia.resolve_clarification(clarification, user_input, plan_run) # Handling of Action clarifications if isinstance(clarification, ActionClarification): print(f"{clarification.user_guidance} -- Please click on the link below to proceed.") print(clarification.action_url) plan_run = portia.wait_for_ready(plan_run) # Once clarifications are resolved, resume the plan run plan_run = portia.resume(plan_run) ``` -------------------------------- ### Configure Mistral API Key Source: https://docs.portialabs.ai/install Sets the environment variable for the Mistral API key. 'mistral-large-latest' is the default model. Ensure Mistral dependencies are installed. ```bash export MISTRAL_API_KEY='your-api-key-here' ``` -------------------------------- ### Configure Amazon Bedrock Credentials Source: https://docs.portialabs.ai/install Sets the environment variables for AWS access key ID, secret access key, and default region for Amazon Bedrock. Ensure Amazon dependencies are installed. ```bash export AWS_ACCESS_KEY_ID ='your-access-key-id' export AWS_SECRET_ACCESS_KEY ='your-secret-access-key' export AWS_DEFAULT_REGION ='your-default-region' ``` -------------------------------- ### Value Confirmation Clarification Example Source: https://docs.portialabs.ai/understand-clarifications An example of a Value Confirmation clarification, used to get user confirmation or denial for a particular value, useful for 'human in the loop' tasks. The `argument` attribute indicates the value being confirmed. ```json { "uuid":"clar-425c8ce9-8fc9-43af-b99e-64903043c5df", "plan_run_id":"prun-89c6bd4f-29d2-4aad-bf59-8ba3229fd258", "category": “Value Confirmation”, "step":2, "user_guidance":"This will email all contacts in your database. Are you sure you want to proceed?", "resolved":true, "argument":"$email_all_contacts" } ``` -------------------------------- ### Configure OpenAI API Key Source: https://docs.portialabs.ai/install Sets the environment variable for the OpenAI API key. 'gpt-4.1' is the default model. ```bash export OPENAI_API_KEY='your-api-key-here' ``` -------------------------------- ### Run Python Script with uv - Portia SDK Source: https://docs.portialabs.ai/getting-started-tour Demonstrates how to run a Python script using the 'uv' command. This process includes obtaining the correct Python version, creating a virtual environment, installing dependencies, and executing the script. ```bash uv run .py ``` -------------------------------- ### Configure Anthropic API Key Source: https://docs.portialabs.ai/install Sets the environment variable for the Anthropic API key. 'sonnet-3.7' and 'sonnet-3.5' are used by default. ```bash export ANTHROPIC_API_KEY='your-api-key-here' ``` -------------------------------- ### Initialize Portia with Registry Source: https://docs.portialabs.ai/getting-started-tour Initializes the Portia agent with a configured tool registry and execution hooks, enabling it to run tasks. ```python portia = Portia( config=my_config, tools=registry, execution_hooks=CLIExecutionHooks(), ) ``` -------------------------------- ### Fetch Server with UVX Source: https://docs.portialabs.ai/getting-started-tour Configures an MCPToolRegistry to run a server using UVX, which downloads and executes Python packages. This allows Portia to interact with the server. ```python from portia import McpToolRegistry registry = McpToolRegistry.from_stdio_connection( server_name="fetch", command="uvx", args=["mcp-server-fetch"], ) ``` -------------------------------- ### Configure Azure OpenAI API Key and Endpoint Source: https://docs.portialabs.ai/install Sets the environment variables for Azure OpenAI API key and endpoint. 'gpt-4.1' is the default model. ```bash export AZURE_OPENAI_API_KEY='your-api-key-here' export AZURE_OPENAI_ENDPOINT='your-api-key-here' ``` -------------------------------- ### Portia SDK Reference - Portia Class and Plan Method Source: https://docs.portialabs.ai/generate-plan API documentation for the `Portia` class and its `plan` method. The `Portia` instance is the main entrypoint for interacting with Portia's libraries. The `plan` method generates a plan from a given query and can accept optional `tools` and `example_plans` parameters. ```APIDOC Portia: __init__(tools: list = None, config: dict = None) Initializes the Portia client with a list of tools and configuration. - tools: A list of available tools for plan generation. - config: Configuration settings for the Portia client. plan(query: str, tools: list = None, example_plans: list = None) -> Plan Generates a plan based on the provided query. - query: The user's request or query. - tools: Optional list of tools to use for plan generation. - example_plans: Optional list of `Plan` objects to use as examples for guiding the plan generation. - Returns: A `Plan` object representing the generated plan. ``` -------------------------------- ### Configure Portia with Amazon Bedrock Source: https://docs.portialabs.ai/install Sets up Portia with Amazon Bedrock, using an Anthropic Claude Sonnet model. Supports configuration via AWS access keys or a credentials profile. ```python import os from dotenv import load_dotenv from portia import ( Config, LLMProvider, Portia, example_tool_registry, ) load_dotenv() AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_DEFAULT_REGION = os.getenv('AWS_DEFAULT_REGION') # Create a default Portia config ussing aws access keys with LLM provider set to AMAZON and model set to anthropic within Bedrock (make sure you enable the model in your Bedrock model access settings). amazon_config = Config.from_default( llm_provider=LLMProvider.AMAZON, default_model="amazon/eu.anthropic.claude-sonnet-4-20250514-v1:0", aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, aws_default_region=AWS_DEFAULT_REGION, ) # Config using the aws_credentials_profile_name, if you're using ~/.aws/credentials (generated by `aws configure`). AWS_CREDENTIALS_PROFILE_NAME = os.getenv('AWS_CREDENTIALS_PROFILE_NAME')||"default" amazon_config2 = Config.from_default( llm_provider=LLMProvider.AMAZON, default_model="amazon/eu.anthropic.claude-sonnet-4-20250514-v1:0", aws_credentials_profile_name=AWS_CREDENTIALS_PROFILE_NAME, ) portia = Portia(config=amazon_config, tools=example_tool_registry) # Run the test query and print the output! plan_run = portia.run('add 1 + 2') print(plan_run.model_dump_json(indent=2)) ``` -------------------------------- ### Plan and Run a Task with Portia Source: https://docs.portialabs.ai/getting-started-tour Shows how to first plan a task using portia.plan() and then execute the generated plan using portia.run_plan(). The 'end_user' parameter identifies the user for credential lookup. ```python # Assuming task2 is defined elsewhere # task2 = ... # Assuming portia is initialized as above plan = portia.plan(task2) print(plan.pretty_print()) plan_run = portia.run_plan(plan, end_user="its me, mario") ``` -------------------------------- ### Equip Portia with Qdrant and Default Tools Source: https://docs.portialabs.ai/portia-tools/local-mcp/qdrant Provides a complete example of equipping a Portia instance with both the default tools and the Qdrant MCP server tools. It shows how to configure Portia and combine tool registries. ```python from portia import DefaultToolRegistry, McpToolRegistry, Portia, Config config = Config.from_default() tool_registry = DefaultToolRegistry(config)+ McpToolRegistry.from_stdio_connection( server_name="qdrant", command="uvx", args=[ "mcp-server-qdrant", ], env={ "QDRANT_LOCAL_PATH":"", "COLLECTION_NAME":"", "EMBEDDING_MODEL":"", }, ) portia = Portia(config=config, tools=tool_registry) ``` -------------------------------- ### Instantiate Portia and Run Plan from User Query Source: https://docs.portialabs.ai/run-plan This snippet demonstrates how to instantiate the Portia agent with example tools and then directly execute a plan based on a user's query. It shows the process of generating and running a plan in a single step using the `run` method. ```python from dotenv import load_dotenv from portia import( Portia, example_tool_registry, ) load_dotenv() # Instantiate a Portia instance. Load it with the default config and the example tools. portia = Portia(tools=example_tool_registry) # Generate the plan from the user query and run it plan_run = portia.run('Which stock price grew faster in 2024, Amazon or Google?') # Serialise into JSON and print the output print(plan_run.model_dump_json(indent=2)) ``` -------------------------------- ### Install and Quickstart SteelThread Source: https://docs.portialabs.ai/evals-steel-thread SteelThread requires access to agent activity in Portia cloud. You need a PORTIAAPIKEY to begin. Generate a new API key from the 'Manage API keys' tab in app.portialabs.ai. ```en You will need a PORTIAAPIKEY to get started. Head over to (app.portialabs.ai ↗) and navigate to the Manage API keys tab from the left hand nav. There you can generate a new API key. ``` -------------------------------- ### Initialize Portia with Tools and Run Plan with Additional User Data Source: https://docs.portialabs.ai/manage-end-users Demonstrates initializing the Portia client with a tool registry, loading environment variables, and running a plan with an `EndUser` object that includes additional data like weather preferences. ```python from dotenv import load_dotenv from portia import( Portia, default_config, example_tool_registry, ) from portia.end_user import EndUser load_dotenv() portia = Portia(tools=example_tool_registry) plan_run = portia.run( "Get the temperature in Svalbard and write me a personalized greeting with the result.", end_user=EndUser(external_id="my_user_id_123", name="Nicholas of Patara", additional_data={"weather_preferences":"I prefer my weather in the form of a Haiku"}) ) ``` -------------------------------- ### Initialize Portia Agent with CLIExecutionHooks Source: https://docs.portialabs.ai/getting-started-tour Initializes the Portia agent with cloud storage, default tools, and CLI execution hooks to allow user input during agent execution. The `portia.run` method executes a task and returns a `PlanRun` object containing outputs. ```python from portia_ai import Portia, Config, StorageClass from portia_ai.tools import PortiaToolRegistry from portia_ai.hooks import CLIExecutionHooks my_config = Config.from_default(storage_class=StorageClass.CLOUD) portia = Portia( config=my_config, tools=PortiaToolRegistry(my_config), execution_hooks=CLIExecutionHooks(), ) # Example task (assuming task0 is defined elsewhere) # plan_run = portia.run(task0) ``` -------------------------------- ### Portia Plan Execution Example Source: https://docs.portialabs.ai/run-portia-tools Illustrates a typical plan execution flow in Portia, including searching for a GitHub repository and starring it. It shows the expected JSON structure for a plan and its corresponding run. ```json { "id":"plan-71fbe578-0c3f-4266-b5d7-933e8bb10ef2", "plan_context":{ "query":"Find the github repository of PortiaAI and give it a star for me", "tool_ids":[ "portia::github::search_repos", "portia::github::star_repo", "portia::slack::send_message", "portia::zendesk::list_groups_for_user", ... ] }, "steps":[ { "task":"Search for the GitHub repository of PortiaAI", "inputs":[], "tool_id":"portia:github::search_repos", "output":"$portiaai_repository" }, { "task":"Star the GitHub repository of PortiaAI", "inputs":[ { "name":"$portiaai_repository", "description":"The GitHub repository of PortiaAI" } ], "tool_id":"portia:github::star_repo", "output":"$star_result" } ] } ``` ```json { "id":"prun-36945fae-1dcc-4b05-9bc4-4b862748e031", "plan_id":"plan-71fbe578-0c3f-4266-b5d7-933e8bb10ef2", "current_step_index":1, "state":"COMPLETE", "outputs":{ "clarifications":[ { "uuid":"clar-f873b9be-10ee-4184-a717-3a7559416499", "category": “Multiple Choice”, "response": “portiaAI/portia-sdk-python", "step":2, "user_guidance":"Please select a repository.", "handled":true, "argument":"$portiaai_repository", "options":"[\"portiaAI/portia-sdk-python\", \"portiaAI/docs\", \"portiaAI/portia-agent-examples\"]", } ], "step_outputs":{ "$portiaai_repository":{ "value":"[\"portiaAI/portia-sdk-python\", \"portiaAI/docs\", \"portiaAI/portia-agent-examples\"]", "summary":null }, "$star_result":{ "value":"Successfully starred the repository 'portiaAI/portia-sdk-python'.", "summary":null } }, "final_output":{ "value":"Successfully starred the repository 'portiaAI/portia-sdk-python'.", "summary":null } } } ``` -------------------------------- ### Get Portia SDK Version Source: https://docs.portialabs.ai/SDK/portia/version Retrieves the current version of the Portia SDK. This function is designed to work whether the SDK is installed as a dependency or run directly from source, reading the version from pyproject.toml when run from source. It returns the version as a string. ```python def get_version() -> str: # Implementation details to read version from pyproject.toml or installed package ``` -------------------------------- ### Google Calendar Get Events by Properties Schema Source: https://docs.portialabs.ai/portia-tools/portia-cloud/google-calendar/calendar-get-events-by-properties Schema for retrieving Google Calendar events based on various properties. Allows filtering by event title, start and end times, description, attendees, and the maximum number of results. ```APIDOC Tool ID: portia:google:gcalendar:get_events_by_properties Tool Description: Gets Google Calendar events by properties, returning the matching event details. You do not need to provide all the properties, only the ones you have provided with. Args Schema: { "description":"Schema for getting a Google Calendar events by properties.", "properties":{ "event_title":{ "anyOf":[ { "type":"string" }, { "type":"null" } ], "default":null, "description":"The title of the event to get", "title":"Event Title" }, "start_time":{ "anyOf":[ { "format":"date-time", "type":"string" }, { "type":"string" } ], "default":"1970-01-01T00:00:00", "description":"The earliest time of the events to get in ISO format without timezone, e.g 2024-09-20T20:00:00", "title":"Start Time" }, "end_time":{ "anyOf":[ { "format":"date-time", "type":"string" }, { "type":"string" } ], "default":"2100-01-01T00:00:00", "description":"The latest time of the events to get in ISO format without timezone, e.g 2024-09-20T20:00:00", "title":"End Time" }, "event_description":{ "anyOf":[ { "type":"string" }, { "type":"null" } ], "default":null, "description":"The description of the events to get", "title":"Event Description" }, "attendees":{ "default":[], "description":"The attendees' of the events to get", "items":{ "type":"string" }, "title":"Attendees", "type":"array" }, "max_results":{ "default":10, "description":"The maximum number of events to return", "title":"Max Results", "type":"integer" } }, "title":"GoogleCalendarGetEventsByPropertiesSchema", "type":"object" } Output Schema: ('list[dict]', 'A list of dictionaries containing information about matching calendar events') ``` -------------------------------- ### Execute MCP Server Fetch Tool Source: https://docs.portialabs.ai/getting-started-tour Illustrates how to execute a local MCP server for fetching web content. This is typically run from the shell. ```bash # Download and run the mcp-server-fetch tool # (Example command, actual command may vary) # python -m servers.fetch --port 8000 ``` -------------------------------- ### Integrate GCP Cloud Run MCP with Portia Source: https://docs.portialabs.ai/portia-tools/local-mcp/gcp-cloud-run Provides a complete example of equipping a Portia instance with tools from the GCP Cloud Run MCP server, alongside default tools. It shows the setup of configuration, merging registries, and initializing the Portia instance. ```python from portia import DefaultToolRegistry, McpToolRegistry, Portia, Config config = Config.from_default() tool_registry = DefaultToolRegistry(config) + McpToolRegistry.from_stdio_connection( server_name="cloud-run-mcp", command="npx", args=["-y","https://github.com/GoogleCloudPlatform/cloud-run-mcp"], ) portia = Portia(config=config, tools=tool_registry) ``` -------------------------------- ### Custom Emoji Evaluator and Tool Stubbing with Portia Source: https://docs.portialabs.ai/steel-thread-quickstart This Python code defines a custom evaluator to count emojis in the output of a plan run and stubs the 'file_reader_tool' to return static content. It then configures a Portia client with the stubbed tool and runs evals using the custom evaluator. ```python from portia import Portia, Config, DefaultToolRegistry from steelthread.steelthread import SteelThread, EvalConfig from steelthread.evals import Evaluator, EvalMetric from steelthread.portia.tools import ToolStubRegistry, ToolStubContext # Define custom evaluator class EmojiEvaluator(Evaluator): def eval_test_case(self, test_case, plan, plan_run, metadata): out = plan_run.outputs.final_output.get_value() or "" count = out.count("⚠️") return EvalMetric.from_test_case( test_case=test_case, name="emoji_score", score=min(count / 2, 1.0), description="Emoji usage", explanation=f"Found {count} ⚠️ emojis in the output.", actual_value=str(count), expectation="2" ) # Define stub behavior def file_reader_stub_response(ctx: ToolStubContext) -> str: """Stub response for file reader tool to return static file content.""" filename = ctx.kwargs.get("filename", "").lower() return f"Feedback from file:{filename} suggests \ ⚠️ 'One does not simply Calorify' \ and ⚠️ 'Calorify is not a diet' \ and ⚠️ 'Calorify is not a weight loss program' \ and ⚠️ 'Calorify is not a fitness program' \ and ⚠️ 'Calorify is not a health program' \ and ⚠️ 'Calorify is not a nutrition program' \ and ⚠️ 'Calorify is not a meal delivery service' \ and ⚠️ 'Calorify is not a meal kit service' " config = Config.from_default() # Add the tool stub definition to your Portia client using a ToolStubRegistry portia = Portia( config, tools=ToolStubRegistry( DefaultToolRegistry(config), stubs={ "file_reader_tool": file_reader_stub_response, }, ), ) # Run evals with stubs SteelThread().run_evals( portia, EvalConfig( eval_dataset_name="your-dataset-name-here", # TODO: replace with your dataset name config=config, iterations=5, evaluators=[EmojiEvaluator(config)] ), ) ``` -------------------------------- ### Configure Slack App for Portia AI Source: https://docs.portialabs.ai/portia-tools/portia-cloud/slack/get-conversation Provides a comprehensive guide on setting up a Slack application for use with Portia AI. This includes creating a Slack app, noting down client ID and secret, configuring the Redirect URL, setting necessary Bot and User Token Scopes, and installing the app to a Slack workplace. ```APIDOC Configure Slack tools with Portia AI: 1. Create a Slack App: - Head over to [**api.slack.com/apps ↗**](https://api.slack.com/apps). - Create an app from scratch and select the Slack workplace. - Note down the client ID and secret from the **Basic Information** page. 2. Configure OAuth & Permissions: - In the **OAuth & Permissions** tab, add the Redirect URL: `https://api.portialabs.ai/api/v0/oauth/slack`. - Save URLs. - Under **Bot Token Scopes**, add: - `channels:history`: View messages in public channels. - `channels:read`: View basic information about public channels. - `chat:write`: Send messages as the Slack app. - `users:read`: View people in a workspace. - Under **User Token Scopes**, add: - `search:read`: Support searching workplace content. 3. Install Slack App: - Scroll up to the **OAuth & Permissions** page. - Hit the **Install to _{your workplace name}_** button. - Open your Slack app and select 'Add apps', then choose your new app. ``` -------------------------------- ### Defining Portia Tasks Source: https://docs.portialabs.ai/getting-started-tour Defines two example tasks for Portia: a simple task to star a GitHub repository and a more complex task involving calendar checks and meeting scheduling. ```python # A relatively simple task: task0 ="Star the github repo for portiaAI/portia-sdk-python" # A more complex task: task1 =""" Check my availability in Google Calendar for tomorrow between 10am and 12pm. If I have any free times between 10am and 12pm, please schedule a 30-minute meeting with bob (bob@portialabs.ai) with title 'Encode Hackathon', and description 'hack it'. If I don't have any free times, please output the next time after 12pm when I am free. """ ```