|
| 1 | +# Copyright 2011-2026 Splunk, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"): you may |
| 4 | +# not use this file except in compliance with the License. You may obtain |
| 5 | +# a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 11 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 | +# License for the specific language governing permissions and limitations |
| 13 | +# under the License. |
| 14 | + |
| 15 | +import asyncio |
| 16 | +import csv |
| 17 | +import json |
| 18 | +import os |
| 19 | +import sys |
| 20 | +from _collections_abc import dict_items |
| 21 | +from typing import final, override |
| 22 | + |
| 23 | +# ! NOTE: This insert is only needed for splunk-sdk-python CI/CD to work. |
| 24 | +# ! Remove this if you're modifying this example locally. |
| 25 | +sys.path.insert(0, "/splunklib-deps") |
| 26 | + |
| 27 | +# Include all 3rd party dependencies from <app_name>/bin/lib/ |
| 28 | +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "lib")) |
| 29 | + |
| 30 | +from setup_logging import setup_logging # pyright: ignore[reportImplicitRelativeImport] |
| 31 | + |
| 32 | +from splunklib.ai import OpenAIModel |
| 33 | +from splunklib.ai.agent import Agent |
| 34 | +from splunklib.ai.messages import HumanMessage |
| 35 | +from splunklib.modularinput.argument import Argument |
| 36 | +from splunklib.modularinput.event import Event |
| 37 | +from splunklib.modularinput.event_writer import EventWriter |
| 38 | +from splunklib.modularinput.input_definition import InputDefinition |
| 39 | +from splunklib.modularinput.scheme import Scheme |
| 40 | +from splunklib.modularinput.script import Script |
| 41 | + |
| 42 | +# BUG: For some reason the process is started with its trust store path overridden with |
| 43 | +# one that might not exist on the filesystem. In such case we unset the env, which |
| 44 | +# causes the default Certificate Authorities to be used instead. |
| 45 | +CA_TRUST_STORE = "/opt/splunk/openssl/cert.pem" |
| 46 | +if os.environ.get("SSL_CERT_FILE") == CA_TRUST_STORE and not os.path.exists( |
| 47 | + CA_TRUST_STORE |
| 48 | +): |
| 49 | + del os.environ["SSL_CERT_FILE"] |
| 50 | + |
| 51 | + |
| 52 | +LLM_MODEL = OpenAIModel( |
| 53 | + model="gpt-4o-mini", |
| 54 | + base_url="https://api.openai.com/v1", |
| 55 | + # To store API keys, consider secret storage: |
| 56 | + # https://dev.splunk.com/enterprise/docs/developapps/manageknowledge/secretstorage/secretstoragepython |
| 57 | + api_key="<super_secret_key>", |
| 58 | +) |
| 59 | + |
| 60 | +APP_NAME = "ai_modinput_app" |
| 61 | +logger = setup_logging(APP_NAME) |
| 62 | + |
| 63 | + |
| 64 | +@final |
| 65 | +class AgenticWeatherModInput(Script): |
| 66 | + @override |
| 67 | + def get_scheme(self) -> Scheme: # pyright: ignore[reportIncompatibleMethodOverride] |
| 68 | + scheme = Scheme("Agentic Weather") |
| 69 | + |
| 70 | + csv_file_path = Argument( |
| 71 | + name="csv_file_path", |
| 72 | + title="CSV file path", |
| 73 | + data_type=Argument.data_type_string, |
| 74 | + description="Path to file to read the weather logs from", |
| 75 | + required_on_create=True, |
| 76 | + required_on_edit=True, |
| 77 | + ) |
| 78 | + scheme.add_argument(csv_file_path) |
| 79 | + return scheme |
| 80 | + |
| 81 | + @override |
| 82 | + def stream_events(self, inputs: InputDefinition, ew: EventWriter) -> None: |
| 83 | + input_items: dict_items[str, dict[str, str]] = inputs.inputs.items() # pyright: ignore[reportUnknownVariableType] |
| 84 | + for input_name, input_params in input_items: |
| 85 | + logger.info(f"Beginning agentic enrichment for {input_name}.") |
| 86 | + logger.debug(f"{input_params=}") |
| 87 | + |
| 88 | + csv_file_path = input_params.get("csv_file_path", "") |
| 89 | + output_index = input_params.get("index", "") |
| 90 | + output_sourcetype = input_params.get("sourcetype", "") |
| 91 | + try: |
| 92 | + weather_events: list[dict[str, str | int]] = [] |
| 93 | + with open(csv_file_path) as csv_file: |
| 94 | + logger.info(f"Parsing search results from {csv_file_path}") |
| 95 | + reader = csv.DictReader(csv_file) |
| 96 | + weather_events += list(reader) |
| 97 | + |
| 98 | + for weather_event in weather_events: |
| 99 | + weather_event["human_readable"] = asyncio.run( |
| 100 | + self.invoke_agent(json.dumps(weather_event)) |
| 101 | + ) |
| 102 | + logger.debug(f"{weather_event=}") |
| 103 | + |
| 104 | + event = Event( |
| 105 | + stanza=csv_file_path, |
| 106 | + index=output_index, |
| 107 | + sourcetype=output_sourcetype, |
| 108 | + data=json.dumps(weather_event), |
| 109 | + ) |
| 110 | + ew.write_event(event) |
| 111 | + except Exception as e: |
| 112 | + logger.exception(e, stack_info=True) |
| 113 | + |
| 114 | + logger.debug(f"Finishing enrichment for {input_name} at {csv_file_path}") |
| 115 | + |
| 116 | + async def invoke_agent(self, data_json: str) -> str: |
| 117 | + if not self.service: |
| 118 | + raise AssertionError("No Splunk connection available") |
| 119 | + |
| 120 | + logger.info(f"Invoking {LLM_MODEL.model} at {LLM_MODEL.base_url}") |
| 121 | + async with Agent( |
| 122 | + model=LLM_MODEL, |
| 123 | + system_prompt="You're an expert meteorologist.", |
| 124 | + service=self.service, |
| 125 | + ) as agent: |
| 126 | + prompt = ( |
| 127 | + f"Parse {data_json=} into a into a short, human-readable sentence. " |
| 128 | + + "Was it a good day to go outside if you're human?" |
| 129 | + ) |
| 130 | + response = await agent.invoke([HumanMessage(role="user", content=prompt)]) |
| 131 | + logger.debug(f"{response=}") |
| 132 | + return response.messages[-1].content |
| 133 | + |
| 134 | + |
| 135 | +if __name__ == "__main__": |
| 136 | + sys.exit(AgenticWeatherModInput().run(sys.argv)) |
0 commit comments