### Portia AI Setup and Configuration Links Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/index.mdx Provides links to essential setup and configuration guides for Portia AI, including installation, account setup, and configuration management. ```APIDOC Setup Guides: 1. Install and setup - Description: Get Portia AI set up and run your first query. - Link: /install 2. Set up a Portia account - Description: Sign up for a Portia cloud account. - Link: /setup-account 3. Manage your config - Description: Learn how to configure your Portia environment. - Link: /manage-config ``` -------------------------------- ### Install Dependencies Source: https://github.com/portiaai/docs/blob/main/README.md Installs project dependencies using yarn. ```bash yarn install ``` -------------------------------- ### Run Code Example Tests Source: https://github.com/portiaai/docs/blob/main/README.md Executes code example tests using pytest. ```python uv run pytest ``` -------------------------------- ### Start Development Server Source: https://github.com/portiaai/docs/blob/main/README.md Starts the Docusaurus development server. ```bash yarn start ``` -------------------------------- ### Install Portia Python SDK Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Installs the Portia Python SDK and its core dependencies using pip. This command is the basic installation for the SDK. ```bash pip install portia-sdk-python ``` -------------------------------- ### Install SteelThread Source: https://github.com/portiaai/docs/blob/main/docs/product/Evals and SteelThread/Quickstart.md Install the SteelThread library using your preferred package manager: pip, poetry, or uv. ```bash pip install steel-thread ``` ```bash poetry add steel-thread ``` ```bash uv add steel-thread ``` -------------------------------- ### Portia CLI Output Example Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md An example of the JSON output returned by the Portia CLI after executing a plan. Key fields to check are 'state' and 'final_output'. ```json { "id": "prun-13a97e70-2ca6-41c9-bc49-b7f84f6d3982", "plan_id": "plan-96693022-598e-458c-8d2f-44ba51d4f0b5", "current_step_index": 0, "clarifications": [], "state": "COMPLETE", "step_outputs": { "$result": { "value": 3.0 } }, "final_output": { "value": 3.0 } } ``` -------------------------------- ### Install Portia SDK with Extra Dependencies Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Installs the Portia Python 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]" pip install "portia-sdk-python[amazon]" pip install "portia-sdk-python[google]" pip install "portia-sdk-python[mistral]" ``` -------------------------------- ### Start Development Server on Custom Port Source: https://github.com/portiaai/docs/blob/main/README.md Starts the Docusaurus development server on a specified port. ```bash PORT=3002 yarn start ``` -------------------------------- ### Test Portia with OpenAI Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Instantiates Portia with default configuration for OpenAI and runs a simple arithmetic query. Requires OPENAI_API_KEY in .env. ```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)) ``` -------------------------------- ### Run Example Script Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/A tour of our SDK.md This command executes a Python script using the 'uv' runner. It handles Python version management, virtual environment creation, dependency installation, and script execution. ```bash uv run .py ``` -------------------------------- ### Conditional Code Execution in Tests Source: https://github.com/portiaai/docs/blob/main/README.md Demonstrates how to manage code dependencies and execution flow within the testing framework. ```python ```python # Example of depending on another code snippet ```python ```python depends_on=example1 print('This code depends on example1') ``` ```python # Example of invisible setup code ```python ```python # Example of specifying test containers ```python ```python test_containers=redis # Code that requires redis ``` ```python # Example of skipping a test ```python ```python skip=true skip_reason="Not expecting users to run this" print('This test will be skipped') ``` ``` -------------------------------- ### Run Portia CLI with OpenAI Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Executes a simple math prompt using the Portia CLI with the OpenAI LLM provider. This is the default provider. ```bash portia-cli run "add 1 + 2" ``` -------------------------------- ### Run Portia CLI with Google GenAI Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Executes a simple math prompt using the Portia CLI, specifically targeting the Google GenAI LLM provider. ```bash portia-cli run --llm-provider="google" "add 1 + 2" ``` -------------------------------- ### Portia AI Example Overview Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/A tour of our SDK.md This table summarizes the different example files available for Portia AI, detailing their focus and the features they introduce. It serves as a quick reference for users to select examples relevant to their needs, ranging from OAuth API usage to multi-tool agent capabilities and web automation. ```APIDOC Summary Table: | 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 | ``` -------------------------------- ### Test Portia with Google GenAI Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Instantiates Portia with Google GenAI configuration (Gemini 2.0 Flash) and runs a simple arithmetic query. Requires GOOGLE_API_KEY in .env. ```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://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Sets the environment variable for the Google GenAI API key. Ensure Google GenAI dependencies are installed before setting this. ```bash export GOOGLE_API_KEY='your-api-key-here' ``` -------------------------------- ### Run Portia CLI with Azure OpenAI Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Executes a simple math prompt using the Portia CLI, specifically targeting the Azure OpenAI LLM provider. ```bash portia-cli run --llm-provider="azure-openai" "add 1 + 2" ``` -------------------------------- ### Run Portia CLI with Amazon Bedrock Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Executes a simple math prompt using the Portia CLI, specifically targeting the Amazon Bedrock LLM provider. ```bash portia-cli run --llm-provider="amazon" "add 1 + 2" ``` -------------------------------- ### Test Portia with Mistral AI Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Instantiates Portia with Mistral AI configuration (Mistral Large) and runs a simple arithmetic query. Requires MISTRAL_API_KEY in .env. ```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)) ``` -------------------------------- ### Run Portia CLI with Anthropic Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Executes a simple math prompt using the Portia CLI, specifically targeting the Anthropic LLM provider. ```bash portia-cli run --llm-provider="anthropic" "add 1 + 2" ``` -------------------------------- ### Initialize Monday.com MCP Server Connection Source: https://github.com/portiaai/docs/blob/main/docs/portia-tools/local-mcp/monday.com.mdx Establishes a connection to the monday.com MCP server using environment API credentials. This is the basic setup required to start interacting with monday.com data. ```python McpToolRegistry.from_stdio_connection( server_name="monday.com", command="npx", args=[ "@mondaydotcomorg/monday-api-mcp", "-t", "", ], ) ``` -------------------------------- ### Run Portia CLI with Mistral AI Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Executes a simple math prompt using the Portia CLI, specifically targeting the Mistral AI LLM provider. ```bash portia-cli run --llm-provider="mistralai" "add 1 + 2" ``` -------------------------------- ### Building a Plan with Structured LLM Tool Source: https://github.com/portiaai/docs/blob/main/docs/product/Plan and run workflows/Inputs and Outputs.md Illustrates how to build an execution plan using PlanBuilder. This example chains two steps: getting weather information and then summarizing it using the LLM tool with a structured output. ```python from portia import PlanBuilder # Assuming 'weather_tool.id' and 'structured_llm_tool.id' are available plan = PlanBuilder( "get the weather in london and summarize the weather" ).step( "get the weather in london", tool_id=weather_tool.id ).step( "summarize the weather", tool_id=structured_llm_tool.id ).build() ``` -------------------------------- ### Generated Plan Example Source: https://github.com/portiaai/docs/blob/main/docs/product/Plan and run workflows/Run a plan.md An example of a generated plan for comparing stock price growth, including tasks, inputs, and tool IDs. ```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" } ] } ``` -------------------------------- ### Install and Run mcp-server-fetch Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/A tour of our SDK.md Demonstrates how to download and run the 'mcp-server-fetch' tool using uvx. This is a command-line instruction and should not be executed directly in this context. ```bash # Don't actually run this: uvx mcp-server-fetch ``` -------------------------------- ### Instantiate and Configure Portia Runner Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/A tour of our SDK.md Demonstrates how to instantiate the Portia runner by loading default configuration from the environment, including Portia cloud tools, and integrating CLIExecutionHooks for user interaction. ```python # Instantiate a Portia runner. # Load it with the default config from the environment, and with Portia cloud tools. # Use the CLIExecutionHooks to allow the user to provide input to the agents via the CLI when needed my_config = Config.from_default(storage_class=StorageClass.CLOUD) portia = Portia( config=my_config, tools=PortiaToolRegistry(my_config), execution_hooks=CLIExecutionHooks(), ) ``` -------------------------------- ### Configure Mistral API Key Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Sets the environment variable for the Mistral API key. Ensure Mistral dependencies are installed before setting this. ```bash export MISTRAL_API_KEY='your-api-key-here' ``` -------------------------------- ### Environment Variable Setup Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Instructions for setting up environment variables for AWS and Azure OpenAI API keys and endpoints in a local .env file. ```env AWS_ACCESS_KEY_ID=YOUR_AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY=YOUR_AWS_SECRET_ACCESS_KEY AWS_DEFAULT_REGION=YOUR_AWS_DEFAULT_REGION AWS_CREDENTIALS_PROFILE_NAME=YOUR_AWS_PROFILE_NAME AZURE_OPENAI_API_KEY=YOUR_AZURE_OPENAI_API_KEY AZURE_OPENAI_ENDPOINT=YOUR_AZURE_OPENAI_ENDPOINT ``` -------------------------------- ### Portia Configuration Example Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/Manage config options.md Demonstrates loading default Portia configuration, setting storage class to DISK, specifying a storage directory, setting the default log level to DEBUG, and configuring a Redis cache URL. This example shows how to initialize a Portia instance with custom settings. ```python from dotenv import load_dotenv from portia import ( Config, LogLevel, Portia, StorageClass, ) from portia.open_source_tools.registry import example_tool_registry load_dotenv() # Load the default config with specified storage, logging and caching options my_config = Config.from_default( storage_class=StorageClass.DISK, storage_dir='demo_runs', # Amend this based on where you'd like your plans and plan runs saved! default_log_level=LogLevel.DEBUG, llm_redis_cache_url="redis://localhost:6379" ) # Instantiate a Portia instance. Load it with the default config and with some example tools portia = Portia(config=my_config, tools=example_tool_registry) # Execute the plan run from the user query output = portia.run('Which stock price grew faster in 2024, Amazon or Google?') ``` -------------------------------- ### Google Calendar Get Events By Properties Tool Source: https://github.com/portiaai/docs/blob/main/docs/portia-tools/portia-cloud/google-calendar/calendar-get-events-by-properties.mdx Retrieves Google Calendar events based on specified properties. Supports filtering by event title, start and end times, description, and attendees. Allows setting a 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') ``` -------------------------------- ### Define Example Tasks for Portia Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/A tour of our SDK.md Defines two example tasks: 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. " ``` -------------------------------- ### Install Slack App Source: https://github.com/portiaai/docs/blob/main/docs/_lib/_tool-intro-slack.mdx Steps to create a Slack application, obtain credentials, and configure necessary permissions and redirect URLs for integration with Portia AI. ```markdown 1. Head over to **api.slack.com/apps** ↗** 2. Create an app from scratch and select the Slack workplace you would like to use it in. 3. Note down the client ID and secret on the **Basic Information** page. We will need this in a couple of steps from now! 4. In the **OAuth & Permissions** tab further down in the left hand nav, add as **Redirect URL** the following URL `https://api.portialabs.ai/api/v0/oauth/slack` (don't forget to hit that **Save URLs** button!). 5. Under **Bot Token Scopes**, be sure to add the scopes - `channels:history` -- View messages and other content in public channels that your Slack app has been added to. - `channels:read` -- View basic information about public channels in a workspace. - `chat:write` -- Send messages as *@\{your slack app name\}*. - `users:read` -- View people in a workspace. 6. Under **User Token Scopes**, be sure to add the scope `search:read` to support searching workplace content. 7. Now scroll up to the top of the **OAuth & Permissions** page and hit the **Install to *\{your workplace name\}*** button. 8. Once that is done, open your Slack app and hit 'Add apps` and be sure to select your new app. ``` -------------------------------- ### Configure OpenAI API Key Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Sets the environment variable for the OpenAI API key. This is required to authenticate with OpenAI services. ```bash export OPENAI_API_KEY='your-api-key-here' ``` -------------------------------- ### Configure Anthropic API Key Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Sets the environment variable for the Anthropic API key. This is required to authenticate with Anthropic services. ```bash export ANTHROPIC_API_KEY='your-api-key-here' ``` -------------------------------- ### Portia Plan Execution Example Source: https://github.com/portiaai/docs/blob/main/docs/product/Handle auth and clarifications/Run Portia tools with authentication.md Shows a generated plan for searching and starring a GitHub repository, followed by the final state of the plan run, including clarification outputs and step results. ```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 } } } ``` -------------------------------- ### Complete Portia Project Setup with Monday.com Integration Source: https://github.com/portiaai/docs/blob/main/docs/portia-tools/local-mcp/monday.com.mdx Demonstrates how to equip a Portia instance with tools from both the default registry and the monday.com MCP server. This allows for combined functionality and seamless data management. ```python from portia import DefaultToolRegistry, McpToolRegistry, Portia, Config config = Config.from_default() tool_registry = DefaultToolRegistry(config) + McpToolRegistry.from_stdio_connection( server_name="monday.com", command="npx", args=[ "@mondaydotcomorg/monday-api-mcp", "-t", "", ], ) portia = Portia(config=config, tools=tool_registry) ``` -------------------------------- ### Test Portia with Anthropic Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Instantiates Portia with Anthropic configuration (Claude 3.5 Sonnet) and runs a simple arithmetic query. Requires ANTHROPIC_API_KEY in .env. ```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)) ``` -------------------------------- ### Get Default System Context Source: https://github.com/portiaai/docs/blob/main/docs/SDK/portia/planning_agents/context.md Returns a list of strings representing the default system context for the PlanningAgent. This context is typically used to guide the agent's behavior and responses. ```python def default_query_system_context() -> list[str]: # Function implementation details... ``` -------------------------------- ### Setup Portia for Cloud Storage and Run Plans Source: https://github.com/portiaai/docs/blob/main/docs/product/Plan and run workflows/Run a plan.md Demonstrates how to configure Portia for cloud storage, create a plan, and run it either directly from the object or by loading it from cloud storage using its UUID. It includes loading environment variables for API keys and handling potential exceptions during plan storage. ```python from portia.plan import PlanBuilder, PlanUUID from portia import Portia from uuid import UUID portia = Portia() plan = PlanBuilder("test").build() plan_id = PlanUUID(uuid=UUID("f8003b53-9b62-44e2-ac67-887146c07949")) plan.id = plan_id try: if not portia.storage.get_plan(plan_id): portia.storage.save_plan(plan) except Exception as e: pass ``` ```python from dotenv import load_dotenv from portia import ( Portia, default_config, Config, StorageClass, PlanUUID ) # Load the Portia API key load_dotenv() # Set up the Portia instance to use cloud storage config = Config.from_default(storage_class=StorageClass.CLOUD) portia = Portia(config=config) # This will create a plan that is stored in Portia Cloud plan = portia.plan('Which stock price grew faster in 2024, Amazon or Google?') # We can then either run the plan directly from the object... run = portia.run_plan(plan=plan) # Or we can use the ID so that the plan is loaded from storage run = portia.run_plan(plan=PlanUUID.from_string("plan-f8003b53-9b62-44e2-ac67-887146c07949")) ``` -------------------------------- ### Portia E2E Web Scraping Example Source: https://github.com/portiaai/docs/blob/main/docs/product/Extend and run tools/Browser based tools.md This Python script demonstrates a full end-to-end example of using Portia to scrape a website. It initializes Portia with a BrowserTool, defines a task to get a news headline, runs the task, and handles any necessary clarifications, such as user authentication, before 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) ``` -------------------------------- ### Create Dataset with Portia Query Source: https://github.com/portiaai/docs/blob/main/docs/product/Evals and SteelThread/Quickstart.md Create a dataset by running a Portia query that reads user feedback from a local file and identifies recurring themes and areas of concern. ```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) ``` -------------------------------- ### Instantiate Portia with Example Tools Source: https://github.com/portiaai/docs/blob/main/docs/product/Extend and run tools/Integrating tools.md Instantiates a Portia instance with a list of example tools, including CalculatorTool, SearchTool, and WeatherTool. This allows the agent to utilize these functionalities for answering queries. ```python from portia import ( default_config, Portia, ) from portia.open_source_tools.calculator_tool import CalculatorTool from portia.open_source_tools.search_tool import SearchTool from portia.open_source_tools.weather import WeatherTool # Instantiate a Portia instance. Load it with the default config and with the example tools. portia = Portia(tools=[CalculatorTool(), SearchTool(), WeatherTool()]) ``` -------------------------------- ### Browser for URL Tool - Introduction Source: https://github.com/portiaai/docs/blob/main/docs/portia-tools/open-source/browser-for-url.mdx Markdown content for introducing the Browser for URL tool, likely including a reference to a common introduction component. ```mdx import Intro from '@site/docs/_lib/_tool-intro-open-source.mdx'; # Browser for URL Tool ``` -------------------------------- ### Complete Supabase Integration Example Source: https://github.com/portiaai/docs/blob/main/docs/portia-tools/local-mcp/supabase.mdx Provides a comprehensive example of equipping a Portia instance with Supabase tools alongside default tools. It demonstrates how to combine multiple tool registries for extended functionality. ```python from portia import DefaultToolRegistry, McpToolRegistry, Portia, Config config = Config.from_default() tool_registry = DefaultToolRegistry(config) + McpToolRegistry.from_stdio_connection( server_name="supabase", command="npx", args=[ "-y", "@supabase/mcp-server-supabase@latest", "--read-only", "--project-ref=", ], env={"SUPABASE_ACCESS_TOKEN": ""}, ) portia = Portia(config=config, tools=tool_registry) ``` -------------------------------- ### Configure Azure OpenAI API Keys Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Sets the environment variables for Azure OpenAI API key and endpoint. These are required for authenticating with Azure OpenAI services. ```bash export AZURE_OPENAI_API_KEY='your-api-key-here' export AZURE_OPENAI_ENDPOINT='your-api-key-here' ``` -------------------------------- ### Run MCP Server Fetch Tool Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/A tour of our SDK.md Configures an MCPToolRegistry to run the 'mcp-server-fetch' tool using uvx. This allows Portia to interact with a remote tool registry for fetching web page content. ```python from portia import McpToolRegistry registry = McpToolRegistry.from_stdio_connection( server_name="fetch", command="uvx", args=["mcp-server-fetch"], ) ``` -------------------------------- ### Execute a Task with Portia Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/A tour of our SDK.md Shows how to execute a defined task using the configured Portia instance. The `run` method returns a PlanRun object containing the outputs of the agent's execution. ```python plan_run = portia.run(task0) ``` -------------------------------- ### Chargebee MCP Server Setup Source: https://github.com/portiaai/docs/blob/main/docs/portia-tools/local-mcp/chargebee.mdx Sets up the Chargebee MCP server for integration. This involves creating an McpToolRegistry instance with the server name, command, and arguments to install and run the Chargebee MCP agent. ```python McpToolRegistry.from_stdio_connection( server_name="chargebee", command="npx", args=["-y", "@chargebee/mcp@latest"], ) ``` -------------------------------- ### Generated Plan JSON Example Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/Manage config options.md An example of a JSON object representing a generated plan, including its ID, context, and a list of steps with tasks, inputs, tool IDs, and outputs. ```json { "id": "plan-72cb538e-6d2b-42ca-a6c2-511a9a4c4f0e", "plan_context": { "query": "Which stock price grew faster in 2024, Amazon or Google?", "tool_ids": [ "calculator_tool", "weather_tool", "search_tool" ] }, "steps": [ { "task": "Search for the stock price growth of Amazon in 2024.", "inputs": [], "tool_id": "search_tool", "output": "$amazon_stock_growth_2024" }, { "task": "Search for the stock price growth of Google in 2024.", "inputs": [], "tool_id": "search_tool", "output": "$google_stock_growth_2024" }, { "task": "Compare the stock price growth of Amazon and Google in 2024.", "inputs": [ { "name": "$amazon_stock_growth_2024", "description": "The stock price growth of Amazon in 2024." }, { "name": "$google_stock_growth_2024", "description": "The stock price growth of Google in 2024." } ], "tool_id": "llm_tool", "output": "$faster_growth" } ] } ``` -------------------------------- ### Azure OpenAI Configuration for Portia AI Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/install.md Sets up Portia AI to use Azure OpenAI services with the GPT-4o model. It shows how to configure the API key and endpoint using environment variables. ```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 the test query and print the output! plan_run = portia.run('add 1 + 2') print(plan_run.model_dump_json(indent=2)) ``` -------------------------------- ### Replace LLMTool with Google Model Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/Manage config options.md Provides an example of configuring the LLMTool to use a Google model. The process includes environment loading, configuration setup, and updating the tool registry. ```python import dotenv from portia import Config, DefaultToolRegistry, LLMTool, Portia dotenv.load_dotenv() config = Config.from_default() tool_registry = DefaultToolRegistry(config).replace_tool( LLMTool(model="google/gemini-2.0-flash") ) portia = Portia(config=config, tools=tool_registry) ``` -------------------------------- ### Run Browser Automation Example Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/A tour of our SDK.md This command executes the Python script for browser automation. Ensure all Chrome instances are closed before running. The script will launch Chrome with debugging flags, navigate to LinkedIn, and allow user login before proceeding with automated tasks. ```sh uv run 4_browser_use.py ``` -------------------------------- ### Plan Run JSON Example Source: https://github.com/portiaai/docs/blob/main/docs/product/Get started/Manage config options.md An example of a JSON object representing a plan run in its final state, including its ID, associated plan ID, current step index, state, and detailed outputs for each step and the final output. ```json { "id": "prun-e3a77013-2bd4-459c-898c-6a8cc9e77d12", "plan_id": "plan-72cb538e-6d2b-42ca-a6c2-511a9a4c4f0e", "current_step_index": 2, "state": "COMPLETE", "outputs": { "clarifications": [], "step_outputs": { "$amazon_stock_growth_2024": { "value": "In 2024, Amazon's stock price reached an all-time high closing price of $214.10 in November, having risen consistently since the start of 2023. Analysts remain optimistic, with many maintaining a 'Buy' rating and predicting further growth. By the end of 2024, Amazon's stock was expected to continue its upward trend, with projections varying but generally positive. The latest closing stock price as of November 14, 2024, was $211.48, just below the all-time high of $214.10.", "summary": null }, "$google_stock_growth_2024": { "value": "As of today, January 23, 2025, Google's stock has experienced an 18% increase since the beginning of the year, starting at $139.56 and trading at $164.74. Analysts predict the stock price to reach $208 by the end of 2024, marking a year-on-year growth rate of 49.03%. The forecast for the end of 2024 is an estimated increase of 18.18% from today's price.", "summary": null }, "$faster_growth": { "value": "In 2024, Amazon's stock price growth was positive, reaching an all-time high closing price of $214.10 in November. Google's stock price growth in 2024 was also strong, with a year-on-year growth rate of 49.03% and a forecasted increase of 18.18% by the end of the year.", "summary": null } }, "final_output": { "value": "In 2024, Amazon's stock price growth was positive, reaching an all-time high closing price of $214.10 in November. Google's stock price growth in 2024 was also strong, with a year-on-year growth rate of 49.03% and a forecasted increase of 18.18% by the end of the year.", "summary": null } } } ``` -------------------------------- ### Initialize Cloud Run MCP Server Connection Source: https://github.com/portiaai/docs/blob/main/docs/portia-tools/local-mcp/gcp-cloud-run.mdx Establishes a connection to the Cloud Run MCP server using npx to install and run the specified GitHub repository. This is a basic setup for integrating with Cloud Run. ```python McpToolRegistry.from_stdio_connection( server_name="cloud-run-mcp", command="npx", args=["-y", "https://github.com/GoogleCloudPlatform/cloud-run-mcp"], ) ``` -------------------------------- ### Process Stream with SteelThread Source: https://github.com/portiaai/docs/blob/main/docs/product/Evals and SteelThread/Quickstart.md Process a stream of data using SteelThread. This example demonstrates how to set up a SteelThread instance and process a stream, utilizing built-in stream evaluators. Ensure your stream is configured in the Portia dashboard. ```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, ) ) ``` -------------------------------- ### Initialize Portia Client with Tool Stubs Source: https://github.com/portiaai/docs/blob/main/docs/product/Evals and SteelThread/Quickstart.md Initializes a Portia client with a custom configuration, including a ToolStubRegistry that maps tool names to their stub response functions. This allows Portia to use mocked tool behaviors during execution. ```python 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, }, ), ) ``` -------------------------------- ### List Tools with CLI Source: https://github.com/portiaai/docs/blob/main/docs/portia-tools/remote-mcp/invideo.mdx Demonstrates how to list available tools using the Portia CLI. Requires setting the PORTIA_API_KEY environment variable. ```bash $ PORTIA_API_KEY= portia-cli list-tools ``` -------------------------------- ### Get Portia SDK Version Source: https://github.com/portiaai/docs/blob/main/docs/SDK/portia/version.md Retrieves the current version of the Portia SDK. This function is designed to work whether the package is installed or run from source, reading the version from pyproject.toml when run directly from source. ```python def get_version() -> str: # Get the current version of the Portia SDK. # This function works both when the package is installed as a dependency # and when run directly from source. When run from source, it attempts # to read the version from pyproject.toml. # Returns: The current version of the Portia SDK ``` -------------------------------- ### Weather Tool Implementation Source: https://github.com/portiaai/docs/blob/main/docs/product/Extend and run tools/Intro to tools.md Demonstrates the implementation of a 'Weather Tool' using Python. It fetches weather data for a given city from OpenWeatherMap API. Requires an OPENWEATHERMAP_API_KEY environment variable. Includes input schema validation and error handling for API requests. ```python import os import httpx from pydantic import BaseModel, Field from portia.errors import ToolHardError, ToolSoftError from portia.tool import Tool, ToolRunContext class WeatherToolSchema(BaseModel): """Input for WeatherTool.""" city: str = Field(..., description="The city to get the weather for") class WeatherTool(Tool[str]): """Get the weather for a given city.""" id: str = "weather_tool" name: str = "Weather Tool" description: str = "Get the weather for a given city" args_schema: type[BaseModel] = WeatherToolSchema output_schema: tuple[str, str] = ("str", "String output of the weather with temp and city") def run(self, _: ToolRunContext, city: str) -> str: """Run the WeatherTool.""" api_key = os.getenv("OPENWEATHERMAP_API_KEY") if not api_key or api_key == "": raise ToolHardError("OPENWEATHERMAP_API_KEY is required") url = ( f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric" ) response = httpx.get(url) response.raise_for_status() data = response.json() if "weather" not in data: raise ToolSoftError(f"No data found for: {city}") weather = data["weather"][0]["description"] if "main" not in data: raise ToolSoftError(f"No main data found for city: {city}") temp = data["main"]["temp"] return f"The current weather in {city} is {weather} with a temperature of {temp}°C." ```