{ "cells": [ { "cell_type": "code", "execution_count": 66, "id": "49d94364", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Requirement already satisfied: streamlit in c:\\users\\shagu\\anaconda3\\lib\\site-packages (1.32.0)\n", "Requirement already satisfied: langchain-community in c:\\users\\shagu\\anaconda3\\lib\\site-packages (0.3.24)\n", "Requirement already satisfied: langchain-openai in c:\\users\\shagu\\anaconda3\\lib\\site-packages (0.3.19)\n", "Requirement already satisfied: langchain-text-splitters in c:\\users\\shagu\\anaconda3\\lib\\site-packages (0.3.8)\n", "Requirement already satisfied: requests in c:\\users\\shagu\\anaconda3\\lib\\site-packages (2.32.2)\n", "Requirement already satisfied: pathlib in c:\\users\\shagu\\anaconda3\\lib\\site-packages (1.0.1)\n", "Requirement already satisfied: pypdf in c:\\users\\shagu\\anaconda3\\lib\\site-packages (5.6.0)\n", "Requirement already satisfied: altair<6,>=4.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (5.0.1)\n", "Requirement already satisfied: blinker<2,>=1.0.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (1.6.2)\n", "Requirement already satisfied: cachetools<6,>=4.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (5.3.3)\n", "Requirement already satisfied: click<9,>=7.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (8.1.7)\n", "Requirement already satisfied: numpy<2,>=1.19.3 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (1.26.4)\n", "Requirement already satisfied: packaging<24,>=16.8 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (23.2)\n", "Requirement already satisfied: pandas<3,>=1.3.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (2.2.2)\n", "Requirement already satisfied: pillow<11,>=7.1.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (10.3.0)\n", "Requirement already satisfied: protobuf<5,>=3.20 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (3.20.3)\n", "Requirement already satisfied: pyarrow>=7.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (14.0.2)\n", "Requirement already satisfied: rich<14,>=10.14.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (13.3.5)\n", "Requirement already satisfied: tenacity<9,>=8.1.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (8.5.0)\n", "Requirement already satisfied: toml<2,>=0.10.1 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (0.10.2)\n", "Requirement already satisfied: typing-extensions<5,>=4.3.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (4.14.0)\n", "Requirement already satisfied: gitpython!=3.1.19,<4,>=3.0.7 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (3.1.37)\n", "Requirement already satisfied: pydeck<1,>=0.8.0b4 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (0.8.0)\n", "Requirement already satisfied: tornado<7,>=6.0.3 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (6.4.1)\n", "Requirement already satisfied: watchdog>=2.1.5 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from streamlit) (4.0.1)\n", "Requirement already satisfied: langchain-core<1.0.0,>=0.3.59 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langchain-community) (0.3.64)\n", "Requirement already satisfied: langchain<1.0.0,>=0.3.25 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langchain-community) (0.3.25)\n", "Requirement already satisfied: SQLAlchemy<3,>=1.4 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langchain-community) (2.0.30)\n", "Requirement already satisfied: PyYAML>=5.3 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langchain-community) (6.0.1)\n", "Requirement already satisfied: aiohttp<4.0.0,>=3.8.3 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langchain-community) (3.9.5)\n", "Requirement already satisfied: dataclasses-json<0.7,>=0.5.7 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langchain-community) (0.6.7)\n", "Requirement already satisfied: pydantic-settings<3.0.0,>=2.4.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langchain-community) (2.9.1)\n", "Requirement already satisfied: langsmith<0.4,>=0.1.125 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langchain-community) (0.3.45)\n", "Requirement already satisfied: httpx-sse<1.0.0,>=0.4.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langchain-community) (0.4.0)\n", "Requirement already satisfied: openai<2.0.0,>=1.68.2 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langchain-openai) (1.84.0)\n", "Requirement already satisfied: tiktoken<1,>=0.7 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langchain-openai) (0.9.0)\n", "Requirement already satisfied: charset-normalizer<4,>=2 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from requests) (2.0.4)\n", "Requirement already satisfied: idna<4,>=2.5 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from requests) (3.7)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from requests) (2.2.2)\n", "Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from requests) (2024.8.30)\n", "Requirement already satisfied: aiosignal>=1.1.2 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (1.2.0)\n", "Requirement already satisfied: attrs>=17.3.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (23.1.0)\n", "Requirement already satisfied: frozenlist>=1.1.1 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (1.4.0)\n", "Requirement already satisfied: multidict<7.0,>=4.5 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (6.0.4)\n", "Requirement already satisfied: yarl<2.0,>=1.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (1.9.3)\n", "Requirement already satisfied: jinja2 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from altair<6,>=4.0->streamlit) (3.1.4)\n", "Requirement already satisfied: jsonschema>=3.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from altair<6,>=4.0->streamlit) (4.19.2)\n", "Requirement already satisfied: toolz in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from altair<6,>=4.0->streamlit) (0.12.0)\n", "Requirement already satisfied: colorama in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from click<9,>=7.0->streamlit) (0.4.6)\n", "Requirement already satisfied: marshmallow<4.0.0,>=3.18.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from dataclasses-json<0.7,>=0.5.7->langchain-community) (3.26.1)\n", "Requirement already satisfied: typing-inspect<1,>=0.4.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from dataclasses-json<0.7,>=0.5.7->langchain-community) (0.9.0)\n", "Requirement already satisfied: gitdb<5,>=4.0.1 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from gitpython!=3.1.19,<4,>=3.0.7->streamlit) (4.0.7)\n", "Requirement already satisfied: pydantic<3.0.0,>=2.7.4 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langchain<1.0.0,>=0.3.25->langchain-community) (2.11.5)\n", "Requirement already satisfied: jsonpatch<2.0,>=1.33 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langchain-core<1.0.0,>=0.3.59->langchain-community) (1.33)\n", "Requirement already satisfied: httpx<1,>=0.23.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langsmith<0.4,>=0.1.125->langchain-community) (0.27.0)\n", "Requirement already satisfied: orjson<4.0.0,>=3.9.14 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langsmith<0.4,>=0.1.125->langchain-community) (3.10.18)\n", "Requirement already satisfied: requests-toolbelt<2.0.0,>=1.0.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langsmith<0.4,>=0.1.125->langchain-community) (1.0.0)\n", "Requirement already satisfied: zstandard<0.24.0,>=0.23.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from langsmith<0.4,>=0.1.125->langchain-community) (0.23.0)\n", "Requirement already satisfied: anyio<5,>=3.5.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from openai<2.0.0,>=1.68.2->langchain-openai) (4.2.0)\n", "Requirement already satisfied: distro<2,>=1.7.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from openai<2.0.0,>=1.68.2->langchain-openai) (1.9.0)\n", "Requirement already satisfied: jiter<1,>=0.4.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from openai<2.0.0,>=1.68.2->langchain-openai) (0.10.0)\n", "Requirement already satisfied: sniffio in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from openai<2.0.0,>=1.68.2->langchain-openai) (1.3.0)\n", "Requirement already satisfied: tqdm>4 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from openai<2.0.0,>=1.68.2->langchain-openai) (4.66.4)\n", "Requirement already satisfied: python-dateutil>=2.8.2 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from pandas<3,>=1.3.0->streamlit) (2.9.0.post0)\n", "Requirement already satisfied: pytz>=2020.1 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from pandas<3,>=1.3.0->streamlit) (2024.1)\n", "Requirement already satisfied: tzdata>=2022.7 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from pandas<3,>=1.3.0->streamlit) (2023.3)\n", "Requirement already satisfied: python-dotenv>=0.21.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from pydantic-settings<3.0.0,>=2.4.0->langchain-community) (0.21.0)\n", "Requirement already satisfied: typing-inspection>=0.4.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from pydantic-settings<3.0.0,>=2.4.0->langchain-community) (0.4.1)\n", "Requirement already satisfied: markdown-it-py<3.0.0,>=2.2.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from rich<14,>=10.14.0->streamlit) (2.2.0)\n", "Requirement already satisfied: pygments<3.0.0,>=2.13.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from rich<14,>=10.14.0->streamlit) (2.15.1)\n", "Requirement already satisfied: greenlet!=0.4.17 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from SQLAlchemy<3,>=1.4->langchain-community) (3.0.1)\n", "Requirement already satisfied: regex>=2022.1.18 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from tiktoken<1,>=0.7->langchain-openai) (2023.10.3)\n", "Requirement already satisfied: smmap<5,>=3.0.1 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from gitdb<5,>=4.0.1->gitpython!=3.1.19,<4,>=3.0.7->streamlit) (4.0.0)\n", "Requirement already satisfied: httpcore==1.* in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from httpx<1,>=0.23.0->langsmith<0.4,>=0.1.125->langchain-community) (1.0.2)\n", "Requirement already satisfied: h11<0.15,>=0.13 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from httpcore==1.*->httpx<1,>=0.23.0->langsmith<0.4,>=0.1.125->langchain-community) (0.14.0)\n", "Requirement already satisfied: MarkupSafe>=2.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from jinja2->altair<6,>=4.0->streamlit) (2.1.3)\n", "Requirement already satisfied: jsonpointer>=1.9 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from jsonpatch<2.0,>=1.33->langchain-core<1.0.0,>=0.3.59->langchain-community) (2.1)\n", "Requirement already satisfied: jsonschema-specifications>=2023.03.6 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from jsonschema>=3.0->altair<6,>=4.0->streamlit) (2023.7.1)\n", "Requirement already satisfied: referencing>=0.28.4 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from jsonschema>=3.0->altair<6,>=4.0->streamlit) (0.30.2)\n", "Requirement already satisfied: rpds-py>=0.7.1 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from jsonschema>=3.0->altair<6,>=4.0->streamlit) (0.10.6)\n", "Requirement already satisfied: mdurl~=0.1 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from markdown-it-py<3.0.0,>=2.2.0->rich<14,>=10.14.0->streamlit) (0.1.0)\n", "Requirement already satisfied: annotated-types>=0.6.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from pydantic<3.0.0,>=2.7.4->langchain<1.0.0,>=0.3.25->langchain-community) (0.6.0)\n", "Requirement already satisfied: pydantic-core==2.33.2 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from pydantic<3.0.0,>=2.7.4->langchain<1.0.0,>=0.3.25->langchain-community) (2.33.2)\n", "Requirement already satisfied: six>=1.5 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from python-dateutil>=2.8.2->pandas<3,>=1.3.0->streamlit) (1.16.0)\n", "Requirement already satisfied: mypy-extensions>=0.3.0 in c:\\users\\shagu\\anaconda3\\lib\\site-packages (from typing-inspect<1,>=0.4.0->dataclasses-json<0.7,>=0.5.7->langchain-community) (1.0.0)\n", "Note: you may need to restart the kernel to use updated packages.\n" ] } ], "source": [ "pip install streamlit langchain-community langchain-openai langchain-text-splitters requests pathlib pypdf" ] }, { "cell_type": "code", "execution_count": 67, "id": "d0bb4874-7f7b-40a9-88ea-922aaed0f3a3", "metadata": {}, "outputs": [], "source": [ "## Handle secrets either from env vars or streamlit manager\n", "import streamlit as st\n", "import os\n", "api_key = os.getenv(\"LITELLM_KEY\")\n", "if api_key is None:\n", " api_key = st.secrets[\"LITELLM_KEY\"]\n", "cirrus_key = os.getenv(\"CIRRUS_KEY\")\n", "if cirrus_key is None:\n", " cirrus_key = st.secrets[\"CIRRUS_KEY\"] \n" ] }, { "cell_type": "code", "execution_count": 68, "id": "95ed10f3-5339-40cd-bf16-b0854f8b4b91", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\\nimport os\\nimport requests\\nimport zipfile\\n\\ndef download_and_unzip(url, output_dir):\\n response = requests.get(url)\\n zip_file_path = os.path.basename(url)\\n with open(zip_file_path, \\'wb\\') as f:\\n f.write(response.content)\\n with zipfile.ZipFile(zip_file_path, \\'r\\') as zip_ref:\\n zip_ref.extractall(output_dir)\\n os.remove(zip_file_path)\\n\\ndownload_and_unzip(\"https://minio.carlboettiger.info/public-data/hwc.zip\", \"hwc\")\\n'" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"\"\"\n", "import os\n", "import requests\n", "import zipfile\n", "\n", "def download_and_unzip(url, output_dir):\n", " response = requests.get(url)\n", " zip_file_path = os.path.basename(url)\n", " with open(zip_file_path, 'wb') as f:\n", " f.write(response.content)\n", " with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:\n", " zip_ref.extractall(output_dir)\n", " os.remove(zip_file_path)\n", "\n", "download_and_unzip(\"https://minio.carlboettiger.info/public-data/hwc.zip\", \"hwc\")\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 69, "id": "2fbca6dc-a90b-4dd4-8225-8baac5c6622d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"\\ndef pdf_loader(path):\\n all_documents = []\\n docs_dir = pathlib.Path(path)\\n for file in docs_dir.iterdir():\\n loader = PyPDFLoader(file)\\n documents = loader.load()\\n all_documents.extend(documents)\\n return all_documents\\n\\ndocs = pdf_loader('hwc/')\\ndocs\\n\"" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pathlib\n", "from langchain_community.document_loaders import PyPDFLoader\n", "\"\"\"\n", "def pdf_loader(path):\n", " all_documents = []\n", " docs_dir = pathlib.Path(path)\n", " for file in docs_dir.iterdir():\n", " loader = PyPDFLoader(file)\n", " documents = loader.load()\n", " all_documents.extend(documents)\n", " return all_documents\n", "\n", "docs = pdf_loader('hwc/')\n", "docs\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 70, "id": "60fe1968", "metadata": {}, "outputs": [], "source": [ "\n", "# NRP embedding model tends to throw errors\n", "# embedding = OpenAIEmbeddings(model = \"embed-mistral\", api_key = api_key, base_url = \"https://llm.nrp-nautilus.io\")\n", "\n" ] }, { "cell_type": "code", "execution_count": 71, "id": "0a8a004d-bb80-42bf-b7e6-15a54e2dd804", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\\nfrom langchain_openai import OpenAIEmbeddings\\nembedding = OpenAIEmbeddings(\\n model = \"cirrus\",\\n api_key = cirrus_key, \\n base_url = \"https://llm.cirrus.carlboettiger.info/v1\",\\n)\\n'" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "## Use the model on Cirrus instead:\n", "\"\"\"\n", "from langchain_openai import OpenAIEmbeddings\n", "embedding = OpenAIEmbeddings(\n", " model = \"cirrus\",\n", " api_key = cirrus_key, \n", " base_url = \"https://llm.cirrus.carlboettiger.info/v1\",\n", ")\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 72, "id": "fd8bcc13-d06d-43dd-9e06-4f29da803133", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\\nfrom langchain_text_splitters import RecursiveCharacterTextSplitter\\ntext_splitter = RecursiveCharacterTextSplitter(chunk_size=5000, chunk_overlap=500)\\nsplits = text_splitter.split_documents(docs)\\n'" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Build a retrival agent\n", "\"\"\"\n", "from langchain_text_splitters import RecursiveCharacterTextSplitter\n", "text_splitter = RecursiveCharacterTextSplitter(chunk_size=5000, chunk_overlap=500)\n", "splits = text_splitter.split_documents(docs)\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 73, "id": "7f388394-5da2-4db8-8e48-e10436c8532d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\\nfrom langchain_core.vectorstores import InMemoryVectorStore\\nvectorstore = InMemoryVectorStore.from_documents(documents = splits, embedding = embedding)\\nretriever = vectorstore.as_retriever()\\n'" ] }, "execution_count": 73, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# slow part here, runs on remote GPU\n", "\"\"\"\n", "from langchain_core.vectorstores import InMemoryVectorStore\n", "vectorstore = InMemoryVectorStore.from_documents(documents = splits, embedding = embedding)\n", "retriever = vectorstore.as_retriever()\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 74, "id": "0a82aee2-b20d-4025-b644-ab3306f4f752", "metadata": {}, "outputs": [], "source": [ "from langchain.schema import Document\n", "from langchain.chat_models import ChatOpenAI\n", "\n", "documents = [\n", " Document(\n", " page_content=(\n", " \"Abstract\\n\"\n", " \"African lions (Panthera leo) are in decline across many parts of the continent, with retaliatory killing for livestock attacks being a major cause. \"\n", " \"In East Africa, projects are fortifying bomas (livestock enclosures) to reduce conflict between large carnivores and people, aiming to prevent the indiscriminate killing of lions. \"\n", " \"However, the lack of evidence-based studies has made it difficult to scientifically verify the effectiveness of these interventions. \"\n", " \"This study evaluates fortified bomas—called Living Walls—by comparing carnivore attack rates at 84 unprotected bomas and 62 fortified ones. \"\n", " \"The Living Walls were 99.9% effective at preventing nighttime carnivore attacks over 1,790 boma-months, with no lion deaths occurring at fortified sites. \"\n", " \"These findings emphasize the importance of predator-proof enclosures for lion conservation in human–livestock-dominated landscapes.\\n\\n\"\n", " \"Keywords: African lion, Maasai, Large carnivores, Community-based conservation, Tanzania, East Africa\\n\\n\"\n", " \"Introduction\\n\"\n", " \"Much of conservation literature emphasizes problems, with few studies rigorously testing the effectiveness of solutions. \"\n", " \"Lions are declining across Africa, especially outside protected areas, due to retaliatory killings following livestock predation. \"\n", " \"This mirrors challenges faced by other large carnivores globally. In response, East African conservation programs are promoting fortified bomas to reduce predation and associated retaliatory killings. \"\n", " \"Despite the growing adoption of such interventions, few empirical studies have assessed their real-world impact. \"\n", " \"This study seeks to answer: how effective are fortified bomas in reducing carnivore attacks and supporting lion conservation?\\n\\n\"\n", " \"Materials and Methods\\n\"\n", " \"We monitored 146 permanent bomas on the Maasai Steppe near Tarangire National Park in northern Tanzania over a 10-year period, covering 9,296 boma-months. \"\n", " \"Depredation events were verified by trained Maasai community members, who recorded attack locations, times, and photographic evidence where possible. \"\n", " \"In total, 274 carnivore attacks were verified, with 68 attacks on the permanent bomas included in this study. \"\n", " \"These data provide a minimum estimate of conflict, acknowledging underreporting may have occurred.\"\n", " ),\n", " metadata={\n", " \"title\": \"Evidence-based conservation: predator-proof bomas protect livestock and lions\",\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"Abstract\\n\"\n", " \"The global lion (Panthera leo) population decline is partly a result of retaliatory killing in response to livestock depredation. \"\n", " \"Nairobi National Park (NNP) in Kenya, surrounded by human settlements, is one such area. \"\n", " \"To mitigate conflict, communities have implemented LED flashlight systems at livestock bomas to deter nocturnal lion attacks. \"\n", " \"We assessed lion responses to these flashlights from 2007 to 2016 by interviewing 80 boma owners—43 with flashlights and 37 without—and comparing 10 years of predation data. \"\n", " \"Bomas equipped with flashlights experienced significantly fewer attacks. \"\n", " \"After flashlight installation, predation events shifted away from fortified bomas and became more diurnal. \"\n", " \"These findings suggest the flashlight method is an effective tool for reducing nocturnal lion predation and improving coexistence.\\n\\n\"\n", " \"Introduction\\n\"\n", " \"Lion populations are declining due to habitat loss, prey depletion, and retaliatory killings. \"\n", " \"These challenges are particularly acute where human-livestock densities are high. \"\n", " \"Across Kenya, Namibia, and Botswana, lions are frequently killed after attacking livestock. \"\n", " \"This is also a major concern in West and Central Africa, where populations are critically low. \"\n", " \"This study investigates a community-based, non-lethal deterrent method—LED flashlights—and its potential to reduce human-lion conflict near Nairobi National Park.\\n\\n\"\n", " \"Results show LED flashlights significantly reduce nighttime livestock predation and shift lion activity patterns. \"\n", " \"Broader implementation of this low-cost strategy could support lion conservation in similar settings.\\n\\n\"\n", " \"Data Availability: All relevant data are within the paper and its Supporting Information files.\\n\"\n", " \"Funding: This study was part of the PhD project of the lead author, supported by the Louwes Fund for Water and Food, Leiden University, and the Leo Foundation.\"\n", " ),\n", " metadata={\n", " \"title\": \"Effectiveness of a LED flashlight technique in reducing livestock depredation by lions (Panthera leo) around Nairobi National Park\",\n", " }\n", " )\n", "]\n" ] }, { "cell_type": "code", "execution_count": 75, "id": "2bf50abf-5ccd-4de5-9fc4-c9043a66a108", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Based on the provided texts, here's what interventions might work best for you in Tanzania, given your lion/cattle conflict:\n", "\n", "**1. Fortified Bomas (\"Living Walls\"):**\n", "\n", "* **Highly Effective:** The first study specifically conducted in Tanzania (near Tarangire National Park) found that fortified bomas – called \"Living Walls\" – were **99.9% effective** at preventing nighttime carnivore attacks over a 10-year period. Crucially, **no lion deaths occurred at fortified sites.**\n", "* **Recommendation:** This is the *most* strongly supported intervention for your situation, given the research was done in a similar context to yours.\n", "\n", "**2. LED Flashlight Systems:**\n", "\n", "* **Effective Deterrent:** The second study (from Kenya, but relevant given the shared lion populations and challenges) showed that installing LED flashlight systems at bomas **significantly reduced attacks.**\n", "* **Shifts Behavior:** Importantly, flashlights didn't just reduce attacks overall, they also caused lions to shift their hunting to *daytime* rather than nighttime. This could be useful information for managing livestock during the day.\n", "* **Low Cost:** The study highlights this as a \"low-cost strategy.\"\n", "\n", "**In summary:**\n", "\n", "I would strongly recommend investing in **fortified bomas (\"Living Walls\")** as your primary defense. If that isn't immediately feasible, or as a supplementary measure, **LED flashlight systems** are a promising and affordable option.\n", "\n", "\n", "\n", "**Important Considerations:**\n", "\n", "* **Community Involvement:** Both studies emphasize community-based conservation. Working with local conservation programs and involving community members in monitoring and maintenance of these interventions is likely to increase their success.\n", "* **Underreporting:** The Tanzania study acknowledges that conflict events may be underreported. Be diligent in reporting any attacks, even minor ones, to help build a more accurate picture of the problem and the effectiveness of solutions.\n", "\n", "\n", "\n", "\n" ] } ], "source": [ "models = {\"llama3\": \"llama3-sdsc\", \n", " \"deepseek-small\": \"DeepSeek-R1-Distill-Qwen-32B\",\n", " \"deepseek\": \"deepseek-r1-qwen-qualcomm\",\n", " \"gemma3\": \"gemma3\",\n", " \"phi3\": \"phi3\",\n", " \"olmo\": \"olmo\"\n", " }\n", "\n", "from langchain_openai import ChatOpenAI\n", "llm = ChatOpenAI(model = models['gemma3'],\n", " api_key = api_key, \n", " base_url = \"https://llm.nrp-nautilus.io\", \n", " temperature=0)\n", "\n", "\"\"\"\n", "from langchain.chains import create_retrieval_chain\n", "from langchain.chains.combine_documents import create_stuff_documents_chain\n", "from langchain_core.prompts import ChatPromptTemplate\n", "system_prompt = (\n", " \"You are an assistant for question-answering tasks. \"\n", " \"Use the following scientific articles as the retrieved context to answer \"\n", " \"the question. Appropriately cite the articles from the context on which your answer is based using (Author, Year) format. \"\n", " \"Do not attempt to cite articles that are not in the context.\"\n", " \"If you don't know the answer, say that you don't know.\"\n", " \"Use up to five sentences maximum and keep the \"\n", " \"answer concise.\"\n", " \"\\n\\n\"\n", " \"{context}\"\n", ")\n", "prompt = ChatPromptTemplate.from_messages(\n", " [\n", " (\"system\", system_prompt),\n", " (\"human\", \"{input}\"),\n", " ]\n", ")\n", "question_answer_chain = create_stuff_documents_chain(llm, prompt)\n", "\n", "rag_chain = create_retrieval_chain(retriever, question_answer_chain)\n", "\"\"\"\n", "# Combine all document texts into one string as context\n", "context = \"\\n\\n\".join(doc.page_content for doc in documents)\n", "\n", "# Build the prompt with the question and context\n", "prompt = (\n", " f\"Context:\\n{context}\\n\\n\"\n", " \"Question: I live in Tanzania and am having issues with lions breaking into my boma and preying on cattle. \"\n", " \"What interventions might work best for me?\"\n", ")\n", "\n", "response = llm.invoke(prompt)\n", "\n", "print(response.content)\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": 88, "id": "7dda789c-0781-44b6-9dbb-a3527fe5df2f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Okay, based on the provided texts, here's a breakdown of what you can do if elephants are destroying your crops, and the most cost-effective prevention methods:\n", "\n", "**What to Do (and What *Not* to Do):**\n", "\n", "* **Avoid Retaliation:** The texts highlight that killing or harming elephants (even as \"problem animals\") often leads to a cycle of negative consequences – further conflict, potential poaching, and doesn't address the root of the problem.\n", "* **Report to Authorities:** While not explicitly stated as a first step, reporting incidents to game wardens or wildlife authorities is generally advisable, especially to document the problem and potentially access support. However, the texts emphasize *preventative* measures are key to reducing reliance on reactive responses from authorities.\n", "\n", "**Cost-Effective Prevention Methods (Ranked by Apparent Effectiveness & Cost):**\n", "\n", "1. **Chili Fences:** (Most Promising & Relatively Low Cost)\n", " * **How it Works:** Sisal string fences soaked in a mixture of engine oil and ground chili (Capsicum spp.). The smell and irritation deter elephants.\n", " * **Effectiveness:** In Tanzania, these fences have a 100% success rate over nine years – no broken fences.\n", " * **Cost & Implementation:** Materials are relatively affordable, and the texts emphasize the success of *community-based organizations (CBOs)* and *farmer-to-farmer exchanges* in making this method accessible. CBOs can help with funding and construction. This is a key element – it's not just about the materials, but the community support system.\n", " * **Scalability:** The method is rapidly spreading through farmer-to-farmer learning.\n", "\n", "2. **Community-Based Crop Guarding (with/without Chili):** (Good Effectiveness, Moderate Cost)\n", " * **How it Works:** Farmers actively guarding crops, potentially *enhanced* with chili-based deterrents.\n", " * **Effectiveness:** Demonstrated success in Indonesia, repelling elephants in a high percentage of attempted raids (73.9% - 100% in some villages).\n", " * **Cost & Implementation:** Requires farmer time and effort. Chili can be added to increase effectiveness.\n", " * **Scalability:** Relies on community organization and willingness to participate.\n", "\n", "3. **Beehive Fences:** (Good Effectiveness, Moderate to Higher Cost)\n", " * **How it Works:** A fence constructed with beehives spaced along the perimeter of a farm. Elephants are deterred by the bees.\n", " * **Effectiveness:** 80% of elephants were kept out of farms protected by beehive fences in Kenya. Smaller groups were more likely to break the fence.\n", " * **Cost & Implementation:** Requires building/acquiring beehives, wire, and labor. Using dummy hives can reduce costs. Farmers can also benefit from honey production.\n", " * **Scalability:** Demonstrated positive adoption by farmers once its success was known.\n", "\n", "\n", "\n", "**Key Takeaways & Recommendations:**\n", "\n", "* **Community is Crucial:** All successful methods rely on community involvement, organization (like CBOs), and knowledge sharing.\n", "* **Evidence-Based Approach:** The texts emphasize the importance of *demonstrating* the effectiveness of a method before widespread adoption.\n", "* **Start with Chili Fences:** Given the high success rate and relatively low cost in the Tanzanian example, chili fences appear to be the most promising starting point.\n", "* **Consider Beehive Fences:** If chili fences aren't feasible or sufficient, beehive fences are a viable alternative, especially if honey production can offset the costs.\n", "* **Combine Methods:** Crop guarding can be used in conjunction with chili or beehive fences for added protection.\n", "\n", "\n", "\n", "**Where to Learn More:**\n", "\n", "While the provided texts are a good starting point, you'd want to research specific adaptations of these methods for your local context (elephant behavior, available materials, community resources).\n", "\n", "\n", "\n", "\n" ] } ], "source": [ "documents = [\n", " Document(\n", " page_content=(\n", " \"Elephants (Loxodonta africana) raiding crops around Tanzanian national parks threaten farmers’ lives and livelihoods, thus contributing to negative local attitudes towards wildlife. \"\n", " \"As a result, there is often tacit support for poaching among local communities, and elephants suffer through reprisal poisoning or wounding or through being shot as ‘problem animals’ by game wardens. \"\n", " \"Human-elephant conflict (HEC) is growing as the wildlands that still have elephants, especially around national parks, reserves, and wildlife corridors, are increasingly being settled. \"\n", " \"Sisal string fences soaked in engine oil mixed with ground chili (Capsicum spp.) can dissuade elephants from entering fenced fields. \"\n", " \"For the last nine years, farmers around Mikumi National Park in Tanzania have been constructing these fences around ripening crops, and there have been no incidents of fences being broken by elephants. \"\n", " \"Community-based organizations (CBOs) that manage members’ savings through village micro-credit associations help ensure the costs of materials and fence construction are met. \"\n", " \"Chili fences are rapidly becoming widespread, facilitated through farmer-to-farmer exchanges where teams of farmers demonstrate both the fences and the CBOs needed to support the project. \"\n", " \"We argue that promoting the use of chili fences, coupled with supporting CBOs, as a best practice within communities and government programs and budgets, will help reduce the need for HEC compensation, protect livelihoods, empower rural women, increase the food security of rural farmers, and help conserve elephants.\"\n", " ),\n", " metadata={\n", " \"title\": \"Chili Fences and Community-Based Solutions to Human-Elephant Conflict in Tanzania\",\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"Community-Based Human-Elephant Conflict Mitigation: The value of an evidence-based approach in promoting the uptake of effective method\\n\"\n", " \"DonnyGunaryadi a1111111111 a1111111111 a1111111111 a1111111111 a1111111111 1 , Sugiyo 1 , SimonHedges 2 *\\n\"\n", " \"Humanelephant conflict (HEC) is a serious threat to elephants and can cause major eco nomic losses. It is widely accepted that reduction of HEC will often require community based methods for repelling elephants but there are few tests of such methods. \"\n", " \"We tested community-based crop-guarding methods with and without novel chili-based elephant deter rents and describe changes in farmers' willingness to adopt these methods following our demonstration of their relative effectiveness. \"\n", " \"In three separate field-trials that took place over almost two years (October 2005 May 2007) in two villages adjacent to Way Kambas National Park (WKNP) in Indonesia, we found that community-based crop-guarding was effective at keeping Asian elephants (Elephas maximus) out of crop fields in 91.2% (52 out of 57), 87.6% (156 out of 178), and 80.0% (16 out of 20) of attempted raids. \"\n", " \"Once the methodhadbeenshowntobeeffectiveat demonstration sites, farmers in 16 villages around WKNPvoluntarily adopted it during the July 2008 to March 2009 period and were able to repel elephants in 73.9% (150 out of 203) of attempted raids, with seven villages repelling 100%ofattempted raids. \"\n", " \"These 16 villages had all experienced high levels of HEC in the preceding years; e.g. they accounted for >97% of the 742 HEC incidents recorded for the entire park in 2006. \"\n", " \"Our work shows, therefore, that a simple evidence-based approach can facilitate significant reductions in HEC at the protected area scale.\"\n", " ),\n", " metadata={\n", " \"title\": \"Community-Based Human-Elephant Conflict Mitigation in Indonesia\",\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"Beehive Fences as a MultiDimensional Conflict-Mitigation Tool for Farmers Coexisting with Elephants\\n\"\n", " \"Lucy E. King,1,2∗ Fredrick Lala,3 Hesron Nzumu,4 Emmanuel Mwambingu,4 and Iain Douglas-Hamilton1,2\\n\"\n", " \"Increasing habitat fragmentation and human population growth in Africa has resulted in an escalation in human–elephant conflict between small-scale farmers and free-ranging African elephants (Lox odonta Africana). \"\n", " \"In 2012 Kenya Wildlife Service (KWS) implemented the national 10-year Conservation and Management Strategy for the Elephant in Kenya, which includes an action aimed at testing whether beehive fences can be used to mitigate human–elephant conflict. \"\n", " \"From 2012 to 2015, we field-tested the efficacy of beehive fences to protect 10 0.4-ha farms next to Tsavo East National Park from elephants. We hung a series of beehives every 10 m around the boundary of each farm plot. The hives were linked with strong wire. \"\n", " \"After an initial pilot test with 2 farms, the remaining 8 of 10 beehive fences also contained 2-dimensional dummy hives between real beehives to help reduce the cost of the fence. Each trial plot had a neighboring control plot of the same size within the same farm. \"\n", " \"Of the 131 beehives deployed 88% were occupied at least once during the 3.5-year trial. Two hundred and fifty-three elephants, predominantly 20–45 years old entered the community farming area, typically during the crop- ripening season. \"\n", " \"Eighty percent of the elephants that approached the trial farms were kept out of the areas protected by the beehive fences, and elephants that broke a fence were in smaller than average groups. \"\n", " \"Beehive fences not only kept large groups of elephants from invading the farmland plots but the farmers also benefited socially and financially from the sale of 228 kg of elephant friendly honey. \"\n", " \"As news of the success of the trial spread, a further 12 farmers requested to join the project, bringing the number of beehive fence protected farms to 22 and beehives to 297. \"\n", " \"This demonstrates positive adoption of beehive fences as a community mitigation tool. Understanding the response of elephants to the beehive fences, the seasonality of crop raiding and fence breaking, and the willingness of the community to engage with the mitigation method will help contribute to future management strategies for this high human–elephant conflict hotspot and other similar areas in Kenya.\"\n", " ),\n", " metadata={\n", " \"title\": \"Beehive Fences as Conflict-Mitigation Tools for Farmers and Elephants in Kenya\",\n", " }\n", " )\n", "]\n", "\n", "# Combine all document texts into one string as context\n", "context = \"\\n\\n\".join(doc.page_content for doc in documents)\n", "\n", "# Build the prompt with the question and context\n", "prompt = (\n", " f\"Context:\\n{context}\\n\\n\"\n", " \"Question: What should I do if elephants are destroying my crops? And what are the most cost-effective prevention methods, if there are any you know of?\"\n", ")\n", "\n", "response = llm.invoke(prompt)\n", "\n", "print(response.content)\n", "\n", "\n", "#there were more texts I could have given but I wanted to see this first (also I have been giving primarily abstracts)" ] }, { "cell_type": "code", "execution_count": 90, "id": "f4480a13-c9f2-4407-99f2-71e4de630471", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Okay, based on the two provided texts, here's a breakdown of measures you can take to protect your goats and cattle from jaguar and puma predation, along with how the texts support those recommendations. I'll prioritize based on what the studies *specifically* found to be effective or related to risk.\n", "\n", "**Key Takeaways & Recommended Measures (Prioritized):**\n", "\n", "1. **Manage Proximity to Forest Cover/Riparian Corridors:** This is the *most* consistently highlighted factor in both studies.\n", " * **What to do:** If possible, avoid grazing livestock in areas immediately adjacent to forests or riparian (river/stream-side) corridors. The closer the cattle are to these areas, the higher the predation risk. The second study specifically notes distance to riparian corridors as *negatively* correlated with predation – meaning further away is safer.\n", " * **Why it works:** These areas provide cover and travel routes for jaguars and pumas. They are hunting grounds.\n", " * **Evidence:** Both studies emphasize forest proximity as a key driver of predation. The first study found predation risk increased as distance to forest cover *declined*. The second study found distance to riparian corridors was negatively correlated with predation.\n", "\n", "2. **Calving Management (Timing & Location):** Both studies point to calving season as a peak risk period.\n", " * **What to do:** The second study specifically notes a peak in depredation during the peak calving period at the end of the dry season. Consider moving calving areas *away* from forest edges or riparian areas. Provide extra monitoring during this time.\n", " * **Why it works:** Calves are more vulnerable (as the first study confirms – jaguars killed a greater proportion of calves). Concentrating calving makes them easier targets.\n", " * **Evidence:** The second study explicitly identifies the calving peak as a time of increased predation. The first study showed calves had lower survival rates.\n", "\n", "3. **Herd Size (Potentially – with nuance):** The second study suggests a complex relationship with herd size.\n", " * **What to do:** The second study found a *positive* effect of bovine herd size on predation rates in a subset of ranches. However, larger ranches (≥1500 head) actually had *lower* percentages of cattle lost. This suggests that very large herds might have a \"dilution effect\" (predators can't focus on individual animals as easily), but smaller to medium herds might be more vulnerable. This is the least clear recommendation.\n", " * **Why it works (potentially):** Larger herds may overwhelm a predator's ability to consistently target individuals.\n", " * **Evidence:** The second study's findings on herd size are complex and require careful consideration of your specific ranch size.\n", "\n", "4. **Focus on Overall Livestock Loss Control (Beyond Predation):** The first study suggests that, in this region, predation represents a relatively *small* percentage of overall livestock losses.\n", " * **What to do:** Investigate and address other causes of cattle death (disease, accidents, theft, etc.). Improving overall livestock health and management may have a greater impact on your bottom line than solely focusing on predator control.\n", " * **Why it works:** Predation may be a symptom of broader management issues.\n", " * **Evidence:** The first study found predation accounted for only 0.2-0.3% of total livestock holdings.\n", "\n", "\n", "\n", "**What the studies *did not* find to be effective (and therefore shouldn't be relied upon):**\n", "\n", "* **Changing Cattle Movement/Grouping:** The first study found that cattle movement patterns and grouping behavior *did not* change in response to jaguar presence, suggesting these aren't naturally occurring protective behaviors in this context and interventions to force them wouldn't be effective.\n", "\n", "\n", "\n", "**Important Considerations & Caveats:**\n", "\n", "* **Location Specificity:** These studies are from western Brazil and southern Brazilian Amazonia. The specific behaviors of jaguars and pumas, and the landscape factors influencing predation, can vary significantly in other regions.\n", "* **Alternative Prey:** Both studies acknowledge that livestock may be an \"alternative prey\" for these cats, especially when natural prey is scarce. This means reducing other prey options (if feasible and ecologically sound) *might* reduce predation, but this is a complex issue.\n", "* **Monetary Costs:** The second study highlights that the highest monetary costs associated with predation are on large ranches, even though the *percentage* of loss is lower. This is because of the sheer number of animals.\n", "\n", "\n", "\n", "**To help me refine these recommendations further, could you tell me:**\n", "\n", "* **Where are you located?** (Country, region)\n", "* **What is the landscape like around your property?** (Forest, open grassland, mountains, rivers, etc.)\n", "* **What is the size of your herd?**\n", "* **When do your goats/cattle typically calve/give birth?**\n", "\n", "\n", "\n", "**Disclaimer:** I am an AI chatbot and cannot provide professional wildlife management advice. These recommendations are based on the provided texts and should be considered alongside advice from local wildlife experts and agricultural extension agents.\n" ] } ], "source": [ "documents = [\n", " Document(\n", " page_content=(\n", " \"Depredation of livestock by large carnivores is an important but poorly understood source of human–carnivore conflict. \"\n", " \"We examined patterns of livestock depredation by jaguars (Panthera onca) and pumas (Puma concolor) on a ranch–wildlife reserve in western Brazil to assess factors contributing to prey mortality. \"\n", " \"We predicted jaguars would kill a greater proportion of calves than yearling and adult cattle and that proximity to suitable habitat would increase mortality risk. \"\n", " \"We further speculated that exposure to predation risk would promote livestock grouping and increased movement distance. \"\n", " \"We recorded 169 cattle mortality incidents during 2003–2004, of which 19% were due to predation by jaguars and pumas. \"\n", " \"This level of mortality represented 0.2–0.3% of the total livestock holdings on the ranch. \"\n", " \"Jaguars caused most (69%) cattle predation events, and survival in allotments was lower for calves than for other age classes. \"\n", " \"Forest proximity was the only variable we found to explain patterns of livestock mortality, with predation risk increasing as distance to forest cover declined. \"\n", " \"Due to low predation risk, cattle movement patterns and grouping behavior did not vary relative to level of spatial overlap with radiocollared jaguars. \"\n", " \"The overall effect of predation on cattle was low and livestock likely constituted an alternative prey for large cats in our study area. \"\n", " \"However, selection of calves over other age cohorts and higher predation risk among cattle in proximity to forest cover is suggestive of selection of substandard individuals. \"\n", " \"Cattle ranchers in the Pantanal region may reduce cattle mortality rates by concentrating on losses due to nonpredation causes that could be more easily controlled.\"\n", " ),\n", " metadata={\n", " \"title\": \"Evaluation of Potential Factors Predisposing Livestock to Predation by Jaguars\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"Most large carnivore species are in global decline. Conflicts with people, particularly over depredation on small and large livestock, is one of the major causes of this decline. \"\n", " \"Along tropical deforestation frontiers, large felids often shift from natural to livestock prey because of their increased proximity to human agriculture, thus increasing the likelihood of conflicts with humans. \"\n", " \"On the basis of data from 236 cattle ranches, we describe levels of depredation by jaguars (Panthera onca) and pumas (Puma concolor) on bovine herd stocks and examine the effects of both landscape structure and cattle management on the spatial patterns and levels of predation in a highly fragmented forest landscape of southern Brazilian Amazonia. \"\n", " \"Generalized linear models showed that landscape variables, including proportion of forest area remaining and distance to the nearest riparian forest corridor, were key positive and negative determinants of predation events, respectively. \"\n", " \"We detected clear peaks of depredation during the peak calving period at the end of the dry season. Bovine herd size and proportion of forest area had positive effects on predation rates in 60 cattle ranches investigated in more detail. \"\n", " \"On the other hand, distance from the nearest riparian forest corridor was negatively correlated with the number of cattle predated. \"\n", " \"The mean proportion of cattle lost to large felids in 24 months for the region varied according to the herd class size (≤500: 0.82%; 500–1500: 1.24%; ≥1500: 0.26%) but was never greater than 1.24%. \"\n", " \"The highest annual monetary costs were detected in large cattle ranches (≥1500 head of cattle), reaching US$ 885.40. \"\n", " \"Patterns of depredation can be explained by a combination of landscape and livestock management variables such as proportion of forest area, distance to the nearest riparian corridor, annual calving peak, and bovine herd size.\"\n", " ),\n", " metadata={\n", " \"title\": \"Human-Wildlife Conflicts in a Fragmented Amazonian Forest Landscape: Determinants of Large Felid Depredation on Livestock\"\n", " }\n", " )\n", "]\n", "# Combine all document texts into one string as context\n", "context = \"\\n\\n\".join(doc.page_content for doc in documents)\n", "\n", "# Build the prompt with the question and context\n", "prompt = (\n", " f\"Context:\\n{context}\\n\\n\"\n", " \"Question: I know jaguars can prey on goats and cattle, which I have; what measures can I take to save them from getting harmed? Can you check these pdfs to see which ones might help?\"\n", ")\n", "\n", "response = llm.invoke(prompt)\n", "\n", "print(response.content)" ] }, { "cell_type": "code", "execution_count": 92, "id": "d3e89cb1-0102-4816-8a2a-e8464f16a507", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Okay, let's break down what these studies tell us about large carnivore (and by extension, potentially coyote) predation on cattle, and how that might inform your strategy. While these studies focus on jaguars and pumas in Brazil, the underlying principles can be applied to coyote behavior.\n", "\n", "**Key Takeaways from the Studies (and how they relate to coyotes):**\n", "\n", "* **Calves are Vulnerable:** Both studies consistently show that calves are disproportionately targeted. This is likely due to their smaller size, lower defensive capabilities, and potentially their higher nutritional value. *This is a critical point for your situation.*\n", "* **Habitat Proximity Matters:** Predation risk increases closer to cover (forest in the studies, but this translates to brush, woods, or any sheltered area for coyotes). Coyotes will use these areas for ambush points and escape routes.\n", "* **Herd Size & Density:** Larger herds *can* experience higher overall predation numbers (more targets), but smaller herds may have a higher *rate* of loss. The second study showed a correlation between herd size and predation rates.\n", "* **Calving Season is Peak Risk:** The peak calving period is when predators focus their efforts.\n", "* **Predation is Often a Small Percentage of Overall Loss:** While impactful to individual ranchers, predation is often a smaller percentage of total cattle losses compared to other factors (disease, weather, etc.).\n", "\n", "**Applying this to Coyote Prevention - What Might Work Best:**\n", "\n", "Given the information, here's a breakdown of strategies, ranked from potentially most to least effective, and considering incentives for coyotes to stay away:\n", "\n", "**1. Intensive Management During Calving Season (Highest Priority):**\n", "\n", "* **Confined Calving:** If feasible, temporarily confine cows during calving in a smaller, more easily monitored area (a corral or smaller pasture). This concentrates the calves, making them easier to protect.\n", "* **Increased Human Presence:** During calving, *actively* patrol the calving area frequently. Human presence is a deterrent. Consider spending nights in the calving pasture, if possible.\n", "* **Guard Animals:** This is a highly effective method.\n", " * **Livestock Guardian Dogs (LGDs):** Specifically bred to bond with and protect livestock. They are *very* effective at deterring coyotes. (This is a significant investment, but often pays off.)\n", " * **Llamas/Donkeys:** Can be effective at alarming and sometimes chasing away coyotes. They need to be properly introduced to the herd.\n", "* **Fladry:** This involves stringing a line of flags (often red) along the pasture perimeter. The movement and visual cue can deter coyotes from crossing. It needs to be maintained and moved periodically.\n", "\n", "**2. Habitat Management (Medium Priority):**\n", "\n", "* **Reduce Cover Near Calving Areas:** If possible, reduce brush or wooded areas immediately surrounding calving pastures. This removes ambush points. *Be mindful of the need for shade and windbreaks for the cattle.*\n", "* **Maintain Clear Lines of Sight:** Ensure good visibility across pastures. Coyotes prefer to approach unseen.\n", "\n", "**3. Herd Management (Medium Priority):**\n", "\n", "* **Grouping/Paddock Size:** Consider smaller paddocks during calving to concentrate calves and make monitoring easier. However, be aware that very dense groupings can also stress cattle.\n", "* **Calf Density:** Avoid extremely high calf densities, as this can make them a more attractive target.\n", "\n", "**4. Non-Lethal Deterrents (Lower Priority - often need to be combined with other methods):**\n", "\n", "* **Motion-Activated Lights/Sprinklers:** Can startle coyotes, but they may habituate over time.\n", "* **Noise Makers:** Propane cannons, alarms, or radios can provide temporary deterrence, but coyotes can also get used to these.\n", "* **Guardianship through scent:** Using predator urine (like coyote urine) around the perimeter of the pasture can deter them.\n", "\n", "**5. Incentivizing Coyotes to Stay Away (This is about making your cattle *less* attractive):**\n", "\n", "* **Promptly Remove Sick or Weak Calves:** Coyotes may target vulnerable individuals. Removing these reduces the incentive.\n", "* **Good Nutrition for Cows:** Well-nourished cows produce stronger, healthier calves that are more likely to survive.\n", "* **Minimize Scavenging Opportunities:** Remove dead livestock promptly to avoid attracting coyotes.\n", "\n", "\n", "\n", "**Important Considerations:**\n", "\n", "* **Coyotes are Adaptable:** Coyotes are intelligent and can learn to circumvent deterrents. You may need to rotate strategies.\n", "* **Local Coyote Behavior:** Coyote behavior varies by region. Talk to other ranchers in your area to see what has worked for them.\n", "* **Legal Regulations:** Be aware of any local laws regarding coyote control.\n", "* **Integrated Approach:** The most effective strategy is usually a combination of methods.\n", "\n", "\n", "\n", "**To help me refine this advice further, could you tell me:**\n", "\n", "* **What is the size of your cattle operation (approximate number of cows)?**\n", "* **What is the terrain like (open pasture, wooded, hilly)?**\n", "* **What is the typical coyote activity like in your area?**\n", "* **Are you open to using livestock guardian dogs?**\n", "\n", "\n", "\n", "**Disclaimer:** I am an AI chatbot and cannot provide professional agricultural or wildlife management advice. This information is for general guidance only. Always consult with local experts for specific recommendations tailored to your situation.\n" ] } ], "source": [ "documents = [\n", " Document(\n", " page_content=(\n", " \"Estimates indicate coyotes (Canis latrans) kill an average of 1–2.5% of the domestic adult sheep and 4–9% of the lambs \"\n", " \"in the 17 western states. Livestock producers reduce losses (mortality) by using various livestock management practices, \"\n", " \"frightening devices, trapping, snaring, calling and shooting, sodium cyanide guns, denning, aerial gunning, and livestock guarding dogs. \"\n", " \"Livestock producers in the U.S. began using guarding dogs to protect domestic sheep from predators during the mid-1970s. \"\n", " \"Their effectiveness has been evaluated in enclosures and under ranching conditions. These evaluations usually compared losses before and after producers obtained guarding dogs. \"\n", " \"In this study, the effectiveness of livestock guarding dogs for protecting domestic sheep from predators was determined from two postal and three telephone surveys. \"\n", " \"A general survey was mailed to all 433 Colorado Wool Grower Association members. The survey requested information on type of operation (fenced pasture, open range, feedlot); \"\n", " \"the number of ewes and lambs in an operation; ewe and lamb mortality from all causes (weather, disease, predation, etc.); and ewe and lamb mortality from coyotes, mountain lions (Felis concolor), \"\n", " \"black bears (Ursus americanus), and other predators. Responses from 124 of 174 producers that completed the general mail survey were used to estimate sheep mortalities for producers without guarding dogs. \"\n", " \"A random sample of 29 nonrespondents was surveyed by telephone to determine if there was a nonresponse bias. Responses from 21 of these producers were used to estimate herd sizes and mortality rates for nonrespondents without guarding dogs. \"\n", " \"Respondents with guarding dogs, respondents without sheep, those with sheep primarily in feedlots, and incomplete responses were eliminated from both surveys. \"\n", " \"This study compares domestic sheep losses in fenced pastures and on open ranges both with and without livestock guarding dogs in Colorado during 1986 and provides producer estimates of the value of sheep saved from predators by guarding dogs.\"\n", " ),\n", " metadata={\n", " \"title\": \"Effective Use of Livestock Guarding Dogs for Reducing Predation on Domestic Sheep\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"Coyotes (Canis latrans) are showing increasingly bold behaviors toward people and their pets throughout North America. \"\n", " \"Bold behavior by wildlife might be reduced by hazing and aversive conditioning, which is recommended in many management plans for coyotes, \"\n", " \"but there is little information about how it is to be conducted, and few studies have tested this approach. \"\n", " \"We conducted an online search for coyote management plans across North America to review techniques and recommendations related to hazing or aversive conditioning, \"\n", " \"and reported on the implementation of a high-intensity aversive conditioning program in Calgary, Alberta, Canada. \"\n", " \"Almost all the management plans recommended hazing coyotes, most often by using a combination of noises, lights, and movements, \"\n", " \"but only 20% of 71 plans recommended high-intensity techniques like those used by the contractors in Calgary. \"\n", " \"Contractors there searched for coyotes in 72 public park areas where members of the public had submitted reports to a civic call center for bold coyotes. \"\n", " \"They attended sites on 1,917 occasions, observed coyotes on 765 occasions, and reported coyote treatments and responses on 734 occasions. \"\n", " \"The probability of coyote retreats increased by 29%–37% with each additional previous aversive conditioning event at the site, and doubled with the presence of dogs and with the application of projected chalk balls. \"\n", " \"During engagements with contractors, coyote retreat probability declined by 21%–25% with each additional day since the last aversive conditioning event, \"\n", " \"and by 97.2%–97.6% with the presence of dogs and when shots were fired from a paintball gun, presumably because these tools were used only on the boldest coyotes. \"\n", " \"We found no effect of the presence or past number of aversive conditioning events on the number of coyote reports per week by the public. \"\n", " \"Although such high-intensity aversive conditioning is rarely recommended in management plans, our results suggest that its repeated application can reduce coyote boldness over time, \"\n", " \"though coyotes may not generalize this response to other people owing to visual cues (e.g., high-visibility vests, consistent vehicles) associated with contractors.\"\n", " ),\n", " metadata={\n", " \"title\": \"Proactive Use of Intensive Aversive Conditioning Increases Probability of Retreat by Coyotes\"\n", " }\n", " )\n", "]\n", "# Combine all document texts into one string as context\n", "context = \"\\n\\n\".join(doc.page_content for doc in documents)\n", "\n", "# Build the prompt with the question and context\n", "prompt = (\n", " f\"Context:\\n{context}\\n\\n\"\n", " \"Question: I am trying to prevent coyotes from eating the calves of my free-range cattle. What may work best and incentivize them to stay away?\"\n", ")\n", "\n", "response = llm.invoke(prompt)\n", "\n", "print(response.content)" ] }, { "cell_type": "code", "execution_count": 96, "id": "52412c57-d46a-41e1-a28e-5d5e98b508e2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Based on the provided texts, here's a breakdown of options for preventing deer damage to your agricultural fields, keeping cost in mind:\n", "\n", "**1. Hunting (Potentially Cost-Effective, but with Limitations):**\n", "\n", "* Historically, hunting was a primary control method. However, the texts note that **hunting is often not possible today due to land-use conflicts.** If feasible in your area, it could be a relatively low-cost option.\n", "* In the past, venison from hunted deer offset crop losses, making it economically viable.\n", "\n", "**2. Fencing (Variable Cost, Alternatives to Expensive Options):**\n", "\n", "* **Traditional woven wire fences (2.4m high)** are considered \"deer-proof\" but are **too expensive for most agricultural uses.**\n", "* **Research is focused on developing *low-cost* alternatives to woven wire.** The texts mention studies evaluating the effectiveness and cost-benefit of **alternative fence designs.**\n", "* **Electrified fences** (high-tensile steel wire, polytape, or polyrope) are mentioned as options, and improvements in fence technology are making them more accessible. These are likely more affordable than woven wire.\n", "* **Fence effectiveness is affected by:**\n", " * **Net height:** Lower nets increase damage.\n", " * **Slope:** Steeper slopes increase damage.\n", " * **Digging prevention:** Using a digging prevention net (especially stainless wire) can reduce damage.\n", "\n", "**3. Repellents (Generally Ineffective or Too Costly):**\n", "\n", "* The texts state that **repellents have generally been ineffective or too costly** for widespread agricultural use.\n", "* However, repellents *can* be used, but their effectiveness increases with deer density, tree age, and maximum snow depth. They are not affected by the type of tree.\n", "\n", "**4. Considering Your Specific Situation (Important for Fence Choice):**\n", "\n", "* **Deer Density:** The higher the deer density, the more robust your protection needs to be (fence height, electrification).\n", "* **Snow Depth:** High snow depth increases the likelihood of deer jumping or pushing through fences.\n", "* **Slope:** Steeper slopes make it easier for deer to jump fences.\n", "* **Crop Value:** If you're growing high-value crops, investing in a more effective (and potentially more expensive) fence might be worthwhile.\n", "\n", "\n", "\n", "**In summary, your best bet for a cost-effective solution is to explore alternative fence designs to the traditional woven wire fence. Focus on electrified options and consider the specific environmental conditions of your fields (deer density, snow depth, slope) when choosing a fence design and height.**\n", "\n", "\n", "\n", "It's worth researching local agricultural extension offices or wildlife management agencies for specific recommendations tailored to your region and deer population. They may have information on cost-sharing programs or effective fence designs for your area.\n" ] } ], "source": [ "documents += [\n", " Document(\n", " page_content=(\n", " \"Population expansion of deer and the damage to planted trees caused by them is becoming a serious conflict between deer and humans. Although there are many methods for tree protection, their effectiveness varies from case to case, and the determinant of effectiveness has rarely been clarified. \"\n", " \"We investigated the following three specific questions: 1) What factors influence forest managers’ choice of protection methods? 2) What factors were important in reducing tree damage by each protection method? 3) Which of the repellents and fences was more effective in reducing tree damage? \"\n", " \"In 2018, we obtained data of plantation tree damages caused by sika deer (Cervus nippon) and tree protection methods from 1424 plantations in Japan. No protection was chosen at low deer densities, and repellents and fences were chosen at middle and high densities by forest managers. \"\n", " \"In the case of repellents, the damage rank increased with increasing deer density, tree age, and maximum snow depth, but was not affected by planted tree species (Cryptomeria japonica and Chamaecyparis obtusa). \"\n", " \"In the case of fences, the damage rank increased with increasing deer density, tree age, maximum snow depth, slope, and decreasing net height. The damage rank also increased with the usage of separable digging prevention net and the net without stainless wire. \"\n", " \"Deer protection methods should be selected according to environmental conditions such as deer density, snow depth, and slope degree in the case of the treated tree species.\"\n", " ),\n", " metadata={\n", " \"title\": \"Fences are More Effective than Repellents in Reducing Deer Browsing on Planted Two Conifer Species\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"William L. Palmer, Jack M. Payne, Robert G. Wingard, John L. George\\n\"\n", " \"White-tailed deer (Odocoileus virginianus) have fed on agricultural crops since settlers first planted fields on homesteads. In colonial days, deer populations were relatively sparse, farms were small, families were large, and fields were attended regularly. Damage by deer was controlled by hunting, and costs were offset by substituting venison for lost crops. \"\n", " \"Today, deer herd numbers are large, agricultural fields are larger and attended infrequently, and deer damage to crops is both widespread and locally severe. Farmers have used repellents, fencing, and firearms to discourage deer from damaging crops; repellents and fencing generally have been ineffective or too costly. \"\n", " \"Hunting, although effective in reducing deer numbers, is not possible in many areas because of land-use conflicts. Research at The Pennsylvania State University was conducted to develop a low-cost alternative to the traditional 2.4-m woven wire barrier fence, considered to be deer-proof but too expensive for most agricultural uses. \"\n", " \"This study evaluates the effectiveness of alternative fence designs in reducing deer damage and quantifies the cost-benefit relationships of fencing on various crops.\"\n", " ),\n", " metadata={\n", " \"title\": \"A Practical Fence to Reduce Deer Damage\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"White-tailed deer (Odocoileus virginianus) may cause more damage than any other species of wildlife. These damages include crop loss, automobile and aviation collisions, disease transmission, environmental degradation, and destruction of ornamental plantings. \"\n", " \"One practical method of controlling deer damage is the use of exclusionary fences. The relatively high cost of labor and materials required to build effective fences has limited most applications to the protection of orchards, vegetable farms, other high-value resources, and mitigation of human health and safety risks. \"\n", " \"Improvements in fence technology resulting in less expensive, yet effective fences have expanded the use of fences to manage damage caused by deer. Fences typically installed to manage white-tailed deer damage include wire or plastic mesh, electrified high-tensile steel wire, and electrified polytape or polyrope fence. \"\n", " \"This review of scientific literature on fencing determines which fence designs would be the most effective for excluding deer in a variety of situations.\"\n", " ),\n", " metadata={\n", " \"title\": \"Fences and Deer Damage Management: A Review of Designs and Efficacy\"\n", " }\n", " )\n", "]\n", "# Combine all document texts into one string as context\n", "context = \"\\n\\n\".join(doc.page_content for doc in documents)\n", "\n", "# Build the prompt with the question and context\n", "prompt = (\n", " f\"Context:\\n{context}\\n\\n\"\n", " \"Question: Deers keep destroying and taking over our large agricultural fields. Is there anything I can try to prevent this that won’t break the bank?\"\n", ")\n", "\n", "response = llm.invoke(prompt)\n", "\n", "print(response.content)" ] }, { "cell_type": "code", "execution_count": 98, "id": "f283a5b9-5ab3-4f79-8157-c771b50bc7ac", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Okay, based on the provided texts, here's a breakdown of the best ways to prevent bear-human conflict in a suburban setting like yours, focusing on keeping your fruit trees and minimizing attractants, drawing directly from the research. I'll also indicate which documents support each recommendation.\n", "\n", "**Key Strategies for Your Community (and Individual Actions):**\n", "\n", "1. **Attractant Management is Crucial:** This is the *most* consistently emphasized point across all the documents relating to bear conflict. Bears are drawn in by food sources. Removing or securing these is the primary defense.\n", " * **Secure Trash:** This is repeatedly mentioned as a major attractant. Ensure all trash cans are bear-resistant or stored in a secure location (garage, shed) until collection day. ([Human-bear conflicts cause annoyance...](https://www.researchgate.net/publication/344099999_Human-bear_conflicts_cause_annoyance_financial_losses_injuries_and_even_death_to_people))\n", " * **Manage Fruit Trees:** While you want to keep the trees, proactive management is key.\n", " * **Prompt Harvesting:** Pick fruit as soon as it ripens. Don't let it accumulate on the ground. ([Human-bear conflicts cause annoyance...](https://www.researchgate.net/publication/344099999_Human-bear_conflicts_cause_annoyance_financial_losses_injuries_and_even_death_to_people))\n", " * **Clean Up Fallen Fruit:** Regularly remove any fallen fruit from the ground.\n", " * **Consider Netting:** While not explicitly mentioned, netting trees *could* be a preventative measure, though it may not be practical for large trees.\n", " * **Other Potential Attractants:** Be mindful of other potential food sources: bird feeders (remove during bear season), pet food left outdoors, compost piles (secure them). ([Human-bear conflicts cause annoyance...](https://www.researchgate.net/publication/344099999_Human-bear_conflicts_cause_annoyance_financial_losses_injuries_and_even_death_to_people))\n", "\n", "2. **Physical Barriers (Where Feasible):**\n", " * **Electric Fencing:** The meta-analysis ([Human-bear conflicts triggered by nuisance behaviour...](https://www.researchgate.net/publication/344099999_Human-bear_conflicts_cause_annoyance_financial_losses_injuries_and_even_death_to_people)) identifies electric fences as *highly* effective in reducing damage. This could be used around beehives, compost piles, or even potentially around fruit trees (though it might be impractical for large trees).\n", " * **Fencing (General):** While expensive, fencing can be effective. The documents on deer fencing also discuss the importance of height and construction for effectiveness. ([White-tailed deer may cause more damage...](https://www.researchgate.net/publication/228844411_White-tailed_deer_may_cause_more_damage_than_any_other_species_of_wildlife))\n", "\n", "3. **Education & Community Involvement:**\n", " * **Public Awareness:** The bear experts surveyed agree that education is a key component of conflict mitigation. ([Human-bear conflicts cause annoyance...](https://www.researchgate.net/publication/344099999_Human-bear_conflicts_cause_annoyance_financial_losses_injuries_and_even_death_to_people)) A community-wide education campaign about proper food storage and attractant management is essential.\n", " * **Neighborhood Coordination:** If everyone in the neighborhood is diligent about securing attractants, it will be much more effective than just a few households doing so.\n", "\n", "4. **Aversive Conditioning (Potentially, but with Caveats):**\n", " * **AC as a Tool:** The research on black bears in Whistler ([Conflict between humans and black bears...](https://www.researchgate.net/publication/344099999_Conflict_between_humans_and_black_bears_Ursus_americanus_occurs_throughout_North_America_with_increasing_public_demand_to_replace_lethal_management_with_non-lethal_methods_such_as_aversive_conditioning_AC)) shows that aversive conditioning (using projectiles to discourage bears) can *temporarily* increase bear wariness.\n", " * **Limitations:** However, it doesn't change their use of human-dominated spaces and requires consistent, repeated application. It's also best done by trained professionals. It's not a long-term solution on its own.\n", "\n", "\n", "\n", "**What the Documents *Don't* Recommend (or are less effective):**\n", "\n", "* **Repellents (for bears):** The documents on deer protection mention repellents, but their effectiveness is variable and not consistently reliable. There's no specific mention of effective bear repellents in these texts.\n", "* **Lethal Control:** While mentioned as a historical practice, the trend is towards non-lethal methods. Lethal control is also not a sustainable long-term solution.\n", "* **Hunting (as a primary solution):** While hunting can reduce deer populations, it's not always feasible due to land-use conflicts.\n", "\n", "\n", "\n", "**To summarize, your best approach is a community-wide effort focused on eliminating attractants, especially securing trash and managing fruit trees. Consider electric fencing for vulnerable areas. Education is key to ensuring everyone participates.**\n", "\n", "\n", "\n", "**Important Note:** Bear behavior can vary by region. It's always best to consult with your local wildlife agency for specific recommendations tailored to your area. They can provide information on bear activity, regulations, and best practices for bear-human conflict prevention.\n" ] } ], "source": [ "documents += [\n", " Document(\n", " page_content=(\n", " \"Human-bear conflicts cause annoyance, financial losses, injuries, and even death to people. In poorer parts of the world, conflicts with bears can affect local economies. Retaliation against bears may threaten the future of small, isolated populations. \"\n", " \"Our survey of the world’s bear experts revealed that the problem is worsening in terms of severity of conflicts and their impact on bear conservation on all four continents inhabited by bears. However, the main drivers of conflict, and its manifestations, differ among bear species. \"\n", " \"We reviewed human-bear conflict management plans from which we identified 10 categories of mitigating interventions that together comprise a ubiquitous bear conflict management toolbox. Within this toolbox, the peer-reviewed literature indicates heavy reliance on education and physical barriers for conflict mitigation. \"\n", " \"In customizing these general approaches to local circumstances, it is important to be mindful of starkly varying geopolitical and social circumstances. There is a pressing need to improve transfer of knowledge from places with active empirical research on mitigation (especially North America), and adapting methodologies to other parts of the world. \"\n", " \"We saw little evidence of evaluation and adaptive management in the conflict plans. Failure to mitigate conflicts may reduce society’s tolerance of bears and diminish conservation efforts.\"\n", " ),\n", " metadata={\n", " \"title\": \"Resolving Human Bear Conflict: A Global Survey of Countries, Experts, and Key Factors\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"Conflict between humans and black bears (Ursus americanus) occurs throughout North America with increasing public demand to replace lethal management with non-lethal methods, such as aversive conditioning (AC). \"\n", " \"AC aims to teach animals to associate negative stimuli with humans or their infrastructure. We sought to test the efficacy of AC using radio-collared black bears in Whistler, British Columbia, by monitoring individuals and assigning those in conflict with people to control or treatment groups. \"\n", " \"We measured wariness using overt reaction distance, displacement distance, and reaction to researchers before, during and after executing 3–5-day AC programs that consisted of launching projectiles at bears in the treatment group. \"\n", " \"We also assessed predictors of successful AC events (i.e., leaving at a run), changes in bear use of human-dominated habitat during the day and at night, and the effects of including a sound stimulus to signal the beginning and end of AC events. \"\n", " \"Among treated bears, overt reaction distance increased by 46.5% and displacement distance increased by 69.0% following AC programs, whereas both overt reaction distance and displacement distance decreased over time among control group bears. \"\n", " \"Each additional AC event during the previous 30 days increased likelihood of bear departure in response to researcher presence by 4.5%. The success of AC events varied among individuals, declined with distance to cover, and increased with exposure to previous AC events. \"\n", " \"Projectiles launched from guns were slightly more effective at causing bears to displace compared to those launched from slingshots, and sound stimuli decreased the likelihood of a successful AC event. \"\n", " \"AC did not alter diurnal use by bears of human-dominated habitat. Our results suggest that AC effectively increases short-term wariness in black bears but does not alter bear use of human-dominated spaces, highlighting the importance of proactive attractant management and prevention of food conditioning.\"\n", " ),\n", " metadata={\n", " \"title\": \"Aversive Conditioning Increases short-term Wariness but does not change habitat use in black bears associated with conflict\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"Human-bear conflicts triggered by nuisance behaviour in public places and damage to livestock, crops, beehives and trees are among the main threats to bear populations globally. \"\n", " \"The effectiveness of interventions used to minimize bear-caused damage is insufficiently known and comparative reviews are lacking. \"\n", " \"We conducted a meta-analysis of 77 cases from 48 publications and used the relative risk of damage to compare the effectiveness of non-invasive interventions, invasive management (translocations) and lethal control (shooting) against bears. \"\n", " \"We show that the most effective interventions are electric fences (95% confidence interval = 79.2–100% reduction in damage), calving control (100%) and livestock replacement (99.8%), but the latter two approaches were applied in only one case each and need more testing. \"\n", " \"Deterrents varied widely in their effectiveness (13.7–79.5%) and we recommend applying these during the peak periods of damage infliction. \"\n", " \"We found shooting (−34.2 to 100%) to have a short-term positive effect with its effectiveness decreasing significantly and linearly over time. \"\n", " \"We did not find relationships between bear density and intervention effectiveness, possibly due to differences in spatial scales at which they were measured (large scales for densities and local fine scales for effectiveness). \"\n", " \"We appeal for more effectiveness studies and their scientific publishing in regard to under-represented conflict species and regions.\"\n", " ),\n", " metadata={\n", " \"title\": \"Variation and Conservation Implications of the Effectiveness of Anti-Bear Interventions\"\n", " }\n", " )\n", "]\n", "\n", "# Combine all document texts into one string as context\n", "context = \"\\n\\n\".join(doc.page_content for doc in documents)\n", "\n", "# Build the prompt with the question and context\n", "prompt = (\n", " f\"Context:\\n{context}\\n\\n\"\n", " \"Question: We live in a suburb and bears sometimes come into our town to eat from our fruit trees and trash. What are the best ways for us to prevent this as a community without removing our fruit trees? Can you check these pdfs to see which ones might help?\"\n", ")\n", "\n", "response = llm.invoke(prompt)\n", "\n", "print(response.content)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "2976912a-dd1e-477a-94f9-9111d040effa", "metadata": {}, "outputs": [], "source": [ "documents += [\n", " Document(\n", " page_content=(\n", " \"Mitigating conflicts associated with predation on livestock is essential for conserving large carnivores in human dominated landscapes. \"\n", " \"This is generally addressed by targeting individual management practices affecting predation risk, often disregarding that different livestock husbandry systems (i.e., groups of farms sharing similar resource bases, production patterns and management practices) with different vulnerabilities to predation may coexist within predator ranges, each of which requiring tailored prescriptions to reduce predation. \"\n", " \"Here we evaluated the importance of considering both husbandry systems and individual management practices to mitigate conflicts due to cattle predation by wolves in Portugal, where attacks on cattle increased N3 times in 1999–2013. \"\n", " \"Government records from 2012 to 2013 indicated that only b2% of cattle farms suffered wolf attacks, of which b4% had N10 attacks per year. \"\n", " \"We found that attacks were concentrated in the free-ranging husbandry system, which was characterized by multi-owner herds, largely grazing communal land far from shelter, and seldom confined. \"\n", " \"Protecting these herds at night in winter was the most important factor reducing wolf attacks, which could be achieved by changing practices of ≈25% of farmers in this system. \"\n", " \"Attacks were much lower in the semi-confined system, probably because herds grazed pastures closer to shelter, and they were often confined with fences or in barns. \"\n", " \"Farms bringing calves b3 months old to pastures were associated with about 90% of attacks, but changing this practice would involve ≈50% of farmers in this system. \"\n", " \"Our results underline the importance of identifying livestock husbandry systems and to adjust mitigation strategies to each system.\"\n", " ),\n", " metadata={\n", " \"title\": \"Wolf Predation on Cattle in Portugal: Assessing the Effects of Husbandry Systems\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"Worldwide, native predators are killed to protect livestock, an action that can undermine wildlife conservation efforts and create conflicts among stakeholders. \"\n", " \"An ongoing example is occurring in the western United States, where wolves (Canis lupus) were eradicated by the 1930s but are again present in parts of their historic range. \"\n", " \"While livestock losses to wolves represent a small fraction of overall livestock mortality, the response to these depredations has resulted in widespread conflicts including significant efforts at lethal wolf control to reduce impacts on livestock producers, especially those with large-scale grazing operations on public lands. \"\n", " \"A variety of nonlethal methods have proven effective in reducing livestock losses to wolves in small-scale operations but in large-scale, open-range grazing operations, nonlethal management strategies are often presumed ineffective or infeasible. \"\n", " \"To demonstrate that nonlethal techniques can be effective at large scales, we report a 7-year case study where we strategically applied nonlethal predator deterrents and animal husbandry techniques on an adaptive basis (i.e., based on terrain, proximity to den or rendezvous sites, avoiding overexposure to techniques such as certain lights or sound devices that could result in wolves losing their fear of that device, etc.) to protect sheep (Ovis aries) and wolves on public grazing lands in Idaho. \"\n", " \"We collected data on sheep depredation mortalities in the protected demonstration study area and compared these data to an adjacent wolf-occupied area where sheep were grazed without the added nonlethal protection measures. \"\n", " \"Over the 7-year period, sheep depredation losses to wolves were 3.5 times higher in the Nonprotected Area (NPA) than in the Protected Area (PA). \"\n", " \"Furthermore, no wolves were lethally controlled within the PA and sheep depredation losses to wolves were just 0.02% of the total number of sheep present, the lowest loss rate among sheep-grazing areas in wolf range statewide, whereas wolves were lethally controlled in the NPA. \"\n", " \"Our demonstration project provides evidence that proactive use of a variety of nonlethal techniques applied conditionally can help reduce depredation on large open-range operations.\"\n", " ),\n", " metadata={\n", " \"title\": \"Adaptive Use of Nonlethal Strategies for Minimizing Wolf-Sheep Conflict in Idaho\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"There is growing interest in developing effective interventions to manage socially and environmentally damaging conservation conflicts. \"\n", " \"There are a variety of intervention strategies that can be applied in various contexts, but the reasons one type of intervention is chosen over another remain underexplored. \"\n", " \"We surveyed conservation researchers and practitioners (n = 427) to explore how characteristics of conflicts and characteristics of decision makers influence recommendations to alleviate conservation conflict. \"\n", " \"Using a full-factorial design, we experimentally manipulated 3 aspects of the descriptions of 8 different wildlife-conflict scenarios (development status of the conflict country, conflict framing, and legality of killing wild animals) and recorded which of 5 intervention types (wildlife impact reduction, awareness, enforcement, economic incentives, or stakeholder engagement) respondents prioritized. \"\n", " \"We also recorded information on respondents’ demographic and disciplinary backgrounds. \"\n", " \"Stakeholder-based interventions were recommended most often in the survey and in written feedback. However, when we fitted multinomial mixed logit models with fully completed scenario responses (n = 411), recommendations were influenced by small changes in the details of conflict and differed according to respondent characteristics. \"\n", " \"Enforcement and awareness interventions were prioritized relatively more for conflicts in more highly developed nations and by respondents with more natural science backgrounds and relatively less experience with conflict. \"\n", " \"Contrastingly, economic interventions were prioritized more when wildlife killing was described as illegal. \"\n", " \"Age, gender, and development status of the respondent’s home country also predicted some intervention decisions. \"\n", " \"Further, interrogating the influences shaping conservation decision making will further help in the development of evidence-informed interventions.\"\n", " ),\n", " metadata={\n", " \"title\": \"Predicting Intervention Priorities for Wildlife Conflict\"\n", " }\n", " )\n", "]\n", "\n", "# Combine all document texts into one string as context\n", "context = \"\\n\\n\".join(doc.page_content for doc in documents)\n", "\n", "# Build the prompt with the question and context\n", "prompt = (\n", " f\"Context:\\n{context}\\n\\n\"\n", " \"Question: We live in a suburb and bears sometimes come into our town to eat from our fruit trees and trash. What are the best ways for us to prevent this as a community without removing our fruit trees? Can you check these pdfs to see which ones might help?\"\n", ")\n", "\n", "response = llm.invoke(prompt)\n", "\n", "print(response.content)\n" ] }, { "cell_type": "code", "execution_count": 100, "id": "0e0e00a4-f1a7-496f-9b7e-58493508b42f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Okay, based on the provided PDFs, here's a breakdown of cattle husbandry strategies to prevent wolf-livestock conflict, tailored to different situations, and drawing from the research presented. I'll categorize them by the \"husbandry system\" approach highlighted in the first paper, and then add some general best practices.\n", "\n", "**Key Takeaway:** The most effective strategies *depend on your specific situation* – whether you have a free-ranging or semi-confined system. A one-size-fits-all approach won't work.\n", "\n", "\n", "\n", "**1. Free-Ranging Husbandry System (Herds grazing communal land, far from shelter, seldom confined - Portugal Study)**\n", "\n", "This system is the *most vulnerable* according to the Portugal study. Here's what to do:\n", "\n", "* **Night Protection in Winter:** This is the *most important* factor identified in the Portugal study. Confine cattle at night during the winter months. This is achievable for about 25% of farmers in this system.\n", "* **Shelter Access:** While the study notes herds are *far* from shelter, improving access to shelter during the day is also beneficial. Consider strategically placed temporary shelters or identifying grazing areas closer to natural features that provide cover.\n", "* **Multi-Owner Herd Management:** The Portugal study notes multi-owner herds are common. Coordination among owners is *critical* for implementing consistent protection measures. This might be the biggest challenge.\n", "* **Consider Guard Animals:** While not specifically mentioned in the Portugal study, the coyote study highlights the effectiveness of livestock guarding dogs. This could be a valuable addition, especially given the free-ranging nature of the herds.\n", "\n", "**2. Semi-Confined System (Herds graze pastures closer to shelter, often confined with fences/barns - Portugal Study)**\n", "\n", "This system is already less prone to attacks, but improvements can be made:\n", "\n", "* **Maintain Proximity to Shelter:** Continue to graze herds in pastures close to barns or fences. This is already a strength of this system.\n", "* **Calf Management:** *This is crucial.* The Portugal study found that bringing calves under 3 months old to pasture was associated with 90% of attacks. Delay pasturing calves until they are older, or provide significantly increased protection when they *are* pastured. This would involve changing practices for about 50% of farmers in this system.\n", "* **Reinforce Confinement:** Ensure fences are well-maintained and effective at keeping cattle contained. Regularly check for breaches.\n", "* **Consider Guard Animals:** Even in a semi-confined system, livestock guarding dogs can provide an extra layer of protection.\n", "\n", "**3. General Best Practices (Drawing from all studies)**\n", "\n", "These apply regardless of your specific system:\n", "\n", "* **Adaptive Nonlethal Deterrents (Idaho Study):** Don't rely on a single method. Use a *variety* of nonlethal deterrents, and *change them up* to prevent habituation. Consider:\n", " * Lights (but be mindful of habituation – the Idaho study emphasizes avoiding overexposure).\n", " * Sound devices (again, avoid overexposure).\n", " * Olfactory barriers (mentioned in the behavioral ecology study – scents that deter wolves).\n", "* **Habitat Management (Mongolia Study):** Be aware of landscape factors. Wolves prefer areas where they are less likely to be detected. Avoid grazing livestock in areas with dense vegetation or near isolated ger camps.\n", "* **Community Collaboration & Education (Quichua Community Study):** Education and building positive attitudes towards wolf conservation are important. Work with your community to develop and implement conflict mitigation strategies.\n", "* **Rapid Response to Depredation:** If an attack occurs, document it and report it to the appropriate authorities. This helps track patterns and inform management decisions.\n", "* **Consider Fencing:** While expensive, well-maintained fencing is a proven deterrent.\n", "* **Livestock Guarding Dogs (Coyote Study):** These have a long history of success in protecting livestock.\n", "\n", "\n", "\n", "**Important Considerations:**\n", "\n", "* **Cost:** Some of these strategies (e.g., fencing, guard dogs) can be expensive.\n", "* **Labor:** Implementing and maintaining these strategies requires labor.\n", "* **Terrain:** The feasibility of some strategies will depend on the terrain of your land.\n", "* **Wolf Behavior:** Wolves are intelligent and adaptable. What works in one area may not work in another. Monitoring and adapting your strategies is essential.\n", "\n", "\n", "\n", "\n", "**To help me refine these recommendations further, could you tell me:**\n", "\n", "* **What type of husbandry system do you currently use?** (Free-ranging, semi-confined, or something else?)\n", "* **What is the terrain like in your area?** (e.g., open grasslands, forested hills, mountainous)\n", "* **What is the level of wolf activity in your area?** (e.g., frequent sightings, occasional attacks)\n", "\n", "\n", "\n", "**Disclaimer:** I am an AI chatbot and cannot provide professional wildlife management advice. This information is based on the provided PDFs and should be used as a starting point for developing a comprehensive conflict mitigation plan. Consult with local wildlife experts and government agencies for tailored recommendations.\n" ] } ], "source": [ "documents = [\n", " Document(\n", " page_content=(\n", " \"Mitigating conflicts associated with predation on livestock is essential for conserving large carnivores in human dominated landscapes. \"\n", " \"This is generally addressed by targeting individual management practices affecting predation risk, often disregarding that different livestock husbandry systems (i.e., groups of farms sharing similar resource bases, production patterns and management practices) with different vulnerabilities to predation may coexist within predator ranges, each of which requiring tailored prescriptions to reduce predation. \"\n", " \"Here we evaluated the importance of considering both husbandry systems and individual management practices to mitigate conflicts due to cattle predation by wolves in Portugal, where attacks on cattle increased N3 times in 1999–2013. \"\n", " \"Government records from 2012 to 2013 indicated that only b2% of cattle farms suffered wolf attacks, of which b4% had N10 attacks per year. \"\n", " \"We found that attacks were concentrated in the free-ranging husbandry system, which was characterized by multi-owner herds, largely grazing communal land far from shelter, and seldom confined. \"\n", " \"Protecting these herds at night in winter was the most important factor reducing wolf attacks, which could be achieved by changing practices of ≈25% of farmers in this system. \"\n", " \"Attacks were much lower in the semi-confined system, probably because herds grazed pastures closer to shelter, and they were often confined with fences or in barns. \"\n", " \"Farms bringing calves b3 months old to pastures were associated with about 90% of attacks, but changing this practice would involve ≈50% of farmers in this system. \"\n", " \"Our results underline the importance of identifying livestock husbandry systems and to adjust mitigation strategies to each system.\"\n", " ),\n", " metadata={\n", " \"title\": \"Wolf Predation on Cattle in Portugal: Assessing the Effects of Husbandry Systems\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"Worldwide, native predators are killed to protect livestock, an action that can undermine wildlife conservation efforts and create conflicts among stakeholders. \"\n", " \"An ongoing example is occurring in the western United States, where wolves (Canis lupus) were eradicated by the 1930s but are again present in parts of their historic range. \"\n", " \"While livestock losses to wolves represent a small fraction of overall livestock mortality, the response to these depredations has resulted in widespread conflicts including significant efforts at lethal wolf control to reduce impacts on livestock producers, especially those with large-scale grazing operations on public lands. \"\n", " \"A variety of nonlethal methods have proven effective in reducing livestock losses to wolves in small-scale operations but in large-scale, open-range grazing operations, nonlethal management strategies are often presumed ineffective or infeasible. \"\n", " \"To demonstrate that nonlethal techniques can be effective at large scales, we report a 7-year case study where we strategically applied nonlethal predator deterrents and animal husbandry techniques on an adaptive basis (i.e., based on terrain, proximity to den or rendezvous sites, avoiding overexposure to techniques such as certain lights or sound devices that could result in wolves losing their fear of that device, etc.) to protect sheep (Ovis aries) and wolves on public grazing lands in Idaho. \"\n", " \"We collected data on sheep depredation mortalities in the protected demonstration study area and compared these data to an adjacent wolf-occupied area where sheep were grazed without the added nonlethal protection measures. \"\n", " \"Over the 7-year period, sheep depredation losses to wolves were 3.5 times higher in the Nonprotected Area (NPA) than in the Protected Area (PA). \"\n", " \"Furthermore, no wolves were lethally controlled within the PA and sheep depredation losses to wolves were just 0.02% of the total number of sheep present, the lowest loss rate among sheep-grazing areas in wolf range statewide, whereas wolves were lethally controlled in the NPA. \"\n", " \"Our demonstration project provides evidence that proactive use of a variety of nonlethal techniques applied conditionally can help reduce depredation on large open-range operations.\"\n", " ),\n", " metadata={\n", " \"title\": \"Adaptive Use of Nonlethal Strategies for Minimizing Wolf-Sheep Conflict in Idaho\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"There is growing interest in developing effective interventions to manage socially and environmentally damaging conservation conflicts. \"\n", " \"There are a variety of intervention strategies that can be applied in various contexts, but the reasons one type of intervention is chosen over another remain underexplored. \"\n", " \"We surveyed conservation researchers and practitioners (n = 427) to explore how characteristics of conflicts and characteristics of decision makers influence recommendations to alleviate conservation conflict. \"\n", " \"Using a full-factorial design, we experimentally manipulated 3 aspects of the descriptions of 8 different wildlife-conflict scenarios (development status of the conflict country, conflict framing, and legality of killing wild animals) and recorded which of 5 intervention types (wildlife impact reduction, awareness, enforcement, economic incentives, or stakeholder engagement) respondents prioritized. \"\n", " \"We also recorded information on respondents’ demographic and disciplinary backgrounds. \"\n", " \"Stakeholder-based interventions were recommended most often in the survey and in written feedback. However, when we fitted multinomial mixed logit models with fully completed scenario responses (n = 411), recommendations were influenced by small changes in the details of conflict and differed according to respondent characteristics. \"\n", " \"Enforcement and awareness interventions were prioritized relatively more for conflicts in more highly developed nations and by respondents with more natural science backgrounds and relatively less experience with conflict. \"\n", " \"Contrastingly, economic interventions were prioritized more when wildlife killing was described as illegal. \"\n", " \"Age, gender, and development status of the respondent’s home country also predicted some intervention decisions. \"\n", " \"Further, interrogating the influences shaping conservation decision making will further help in the development of evidence-informed interventions.\"\n", " ),\n", " metadata={\n", " \"title\": \"Predicting Intervention Priorities for Wildlife Conflict\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"Estimates indicate coyotes (Canis latrans) kill an average of 1-2.5% of the domestic adult sheep and 4-9% of the lambs in the 17 western states (U.S. Fish and Wildl. Serv. 1978, Pearson 1986). \"\n", " \"Livestock producers reduce losses (mortality) by using various livestock management practices, frightening devices, trapping, snaring, calling and shooting, sodium cyanide guns, denning, aerial gunning, and livestock guarding dogs (Andelt 1987). \"\n", " \"Livestock producers in the U.S. began using guarding dogs to protect domestic sheep from predators during the mid-1970's (McGrew and Blakesley 1982, Pfeifer and Goos 1982). \"\n", " \"Their effectiveness has been evaluated in enclosures (McGrew and Blakesley 1982) and under ranching conditions (Linhart et al. 1979; Pfeifer and Goos 1982; Coppinger et al. 1983; Green and Woodruff 1983, 1988, 1990; Green et al. 1984; Andelt 1985; Black and Green 1985). \"\n", " \"These evaluations usually compared losses before and after producers obtained guarding dogs. \"\n", " \"In this study, I compare domestic sheep losses in fenced pastures and on open ranges both with and without livestock guarding dogs in Colorado during 1986. \"\n", " \"I also provide producer estimates of the value of sheep saved from predators by guarding dogs. \"\n", " \"A general survey was mailed to all (433) Colorado Wool Grower Association members. The survey requested information on type of operation (fenced pasture, open range, feedlot); the number of ewes and lambs in an operation; ewe and lamb mortality from all causes (weather, disease, predation, etc.); and ewe and lamb mortality from coyotes, mountain lions (Felis concolor), black bears (Ursus americanus), and other predators. \"\n", " \"Responses from 124 of 174 producers that completed the general mail survey were used to estimate sheep mortalities for producers without guarding dogs. \"\n", " \"A random sample of 29 of the nonrespondents was surveyed by telephone to determine if there was a nonresponse bias. \"\n", " \"Responses from 21 of these producers were used to estimate herd sizes and mortality rates for nonrespondents without guarding dogs. \"\n", " \"Respondents with guarding dogs, respondents without sheep, respondents with sheep primarily in feedlots, and incomplete responses were eliminated from both surveys.\"\n", " ),\n", " metadata={\n", " \"title\": \"Effective of Livestock Guarding Dogs for Reducing Predation on Domestic Sheep\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"There is no proverbial silver bullet for mitigating human-wildlife conflict, but the study of animal behaviour is foundational to solving issues of coexistence between people and wild animals. \"\n", " \"Our purpose is to examine the theoretical and applied role that behavioural principles play in understanding and mitigating human-wildlife conflict, and delineate gaps in behavioural theory relative to mitigating these conflicts. \"\n", " \"Specifically, we consider two different, yet contemporary, examples of human-wildlife conflict: animal-vehicle collisions and carnivore depredation of livestock. \"\n", " \"Although ostensibly unrelated, both conflict areas share common themes relative to animal behavioural responses to disturbance and perception of risk. \"\n", " \"We first place the effects on wildlife due to these conflicts in the scope of population sustainability, and then examine current research relative to the following three questions. \"\n", " \"How is behavioural ecology relevant to these particular areas of conflict? \"\n", " \"Are advances toward understanding the mechanisms by which animals process information and make decisions being translated into management methods? \"\n", " \"How might management efforts be affected over time by individual behaviours, method integration and habituation/sensitization? \"\n", " \"Regarding animal-vehicle collisions, only in the last decade have researchers applied an antipredator theoretical framework with sensory ecology to understand aspects of marine mammal, terrestrial mammal and bird responses to vehicle approach, speed and associated stimuli. \"\n", " \"However, the size and speeds of modern vehicles demand that we improve economic models and possibly develop novel theoretical frameworks to better predict animal responses to vehicle approach. \"\n", " \"Within the context of carnivore-livestock depredation, our understanding of individual predator behaviour relative to perceived risk and factors contributing to the development of problem individuals will influence the efficacy of the most promising, nonlethal management approaches (e.g. distractive techniques, reproductive inhibition and olfactory barriers). \"\n", " \"In both cases, successful management is contingent upon a mechanistic understanding of how animals respond to disturbance and the information utilized to assess risk.\"\n", " ),\n", " metadata={\n", " \"title\": \"No Single Solution: Application of Behavioural Principles in Mitigating Wildlife-Human Conflict\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"Gray wolves (Canis lupus) are a top predator in northern Asian ecosystems and often perceived as a threat to livestock. \"\n", " \"As a result, wolves are heavily persecuted and populations have declined throughout much of the region. \"\n", " \"Understanding the dynamics of wolf-livestock conflict is important for developing conservation actions that benefit wolves and human livelihoods. \"\n", " \"We measured the influence of landscape factors on patterns of wolf-livestock conflict in Ikh Nart Nature Reserve, Mongolia by modeling livestock predation risk using a partitioned Mahalanobis D2 (k) analysis. \"\n", " \"We based the model on 44 known predation sites obtained through 102 interviews with rural pastoralists and mapped risk at a 500 m spatial scale. \"\n", " \"Four factors strongly influenced predation risk at a given site in the landscape including distance to nearest ger camp, and the percent of surrounding tall vegetation, shrubland, and forbland habitat. \"\n", " \"Our results indicate that wolves tend to kill livestock in areas where their detection by humans and livestock is low. \"\n", " \"Managing wolves in Mongolia will require reducing livestock predation and subsequent retribution killing. \"\n", " \"This may be achieved by focusing conservation in areas where predation risk is highest, such as habitats with greater vegetation cover and areas near particular ger sites.\"\n", " ),\n", " metadata={\n", " \"title\": \"Measuring and Mapping the Influence of Landscape Factors on Livestock Predation by Wolves in Mongolia\"\n", " }\n", " ),\n", " Document(\n", " page_content=(\n", " \"Environmental education is a widespread, yet relatively unexamined strategy to reduce human-wildlife conflicts. \"\n", " \"We evaluated knowledge, attitudes and behavioral intentions toward bear conservation after five years of environmental education in a Quichua community. \"\n", " \"Conflicts with livestock predation created mixed attitudes and behaviors toward bear conservation. \"\n", " \"Some program objectives were achieved, such as 88% of participants reported satisfaction with environmental knowledge gained. \"\n", " \"Behavioral intentions to decrease bear conflicts increased, and multiple regression analysis revealed support for the project was associated with program participation. \"\n", " \"Focus group meetings with teachers, local policy makers and para-biologists provided a context for recommendations to improve program success and revealed new issues for better bear management.\"\n", " ),\n", " metadata={\n", " \"title\": \"Human-Wildlife Conflict and Environmental Education: Evaluating a Community Program to Protect the Andean Bear in Ecuador\"\n", " }\n", " )\n", "]\n", "\n", "# Combine all document texts into one string as context\n", "context = \"\\n\\n\".join(doc.page_content for doc in documents)\n", "\n", "# Build the prompt with the question and context\n", "prompt = (\n", " f\"Context:\\n{context}\\n\\n\"\n", " \"Question: If we live in an area with a lot of wolves, what cattle husbandry strategies should I employ to prevent any sort of wildlife-human conflict? Can you check these pdfs to see which ones might help?\"\n", ")\n", "\n", "response = llm.invoke(prompt)\n", "\n", "print(response.content)\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.4" } }, "nbformat": 4, "nbformat_minor": 5 }