commit 66d3c0623088f7dd2fce6b18ec30742670c6a8af Author: geoffsee <> Date: Fri May 23 09:48:26 2025 -0400 init diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..5345600 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +* +!packages/genaiscript/genaisrc +!src +!Cargo.lock +!Cargo.toml +!package.json +!package-lock.json +!assets +!bun.lockb +!packages diff --git a/.env b/.env new file mode 100644 index 0000000..55d33a4 --- /dev/null +++ b/.env @@ -0,0 +1,12 @@ +OPENAI_API_KEY="" +OPENAI_API_BASE="https://api.openai.com/v1" +GENAISCRIPT_MODEL_LARGE="" +GENAISCRIPT_MODEL_SMALL="" +SEARXNG_API_BASE_URL="" +SEARXNG_PASSWORD= + +BING_SEARCH_API_KEY= +PERIGON_API_KEY= +TAVILY_API_KEY= +CCC_API_KEY= +HF_API_KEY= \ No newline at end of file diff --git a/.env.cerebras b/.env.cerebras new file mode 100644 index 0000000..706505e --- /dev/null +++ b/.env.cerebras @@ -0,0 +1,4 @@ +OPENAI_API_KEY="" +OPENAI_API_BASE="https://api.cerebras.ai/v1" +GENAISCRIPT_MODEL_LARGE="" +GENAISCRIPT_MODEL_SMALL="" \ No newline at end of file diff --git a/.env.fireworks b/.env.fireworks new file mode 100644 index 0000000..7d992a3 --- /dev/null +++ b/.env.fireworks @@ -0,0 +1,4 @@ +OPENAI_API_KEY="" +OPENAI_API_BASE="https://api.fireworks.ai/inference/v1" +GENAISCRIPT_MODEL_LARGE="" +GENAISCRIPT_MODEL_SMALL="" \ No newline at end of file diff --git a/.env.google b/.env.google new file mode 100644 index 0000000..72e3eeb --- /dev/null +++ b/.env.google @@ -0,0 +1,4 @@ +OPENAI_API_KEY="" +OPENAI_API_BASE="https://generativelanguage.googleapis.com/v1beta/openai" +GENAISCRIPT_MODEL_LARGE="" +GENAISCRIPT_MODEL_SMALL="" diff --git a/.env.groq b/.env.groq new file mode 100644 index 0000000..f7657e5 --- /dev/null +++ b/.env.groq @@ -0,0 +1,4 @@ +OPENAI_API_KEY="" +OPENAI_API_BASE="https://api.groq.com/openai/v1" +GENAISCRIPT_MODEL_LARGE="" +GENAISCRIPT_MODEL_SMALL="" \ No newline at end of file diff --git a/.env.openai b/.env.openai new file mode 100644 index 0000000..87c506f --- /dev/null +++ b/.env.openai @@ -0,0 +1,4 @@ +OPENAI_API_KEY="" +OPENAI_API_BASE="https://api.openai.com/v1" +GENAISCRIPT_MODEL_LARGE="gpt-4o" +GENAISCRIPT_MODEL_SMALL="gpt-4o-mini" \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cdcc4c9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +/target +/node_modules/ +/.idea +prompt.md +todo +chrome +stream_store +data/ +web-agent-rs/ +./.env* +/.genaiscript/ +/packages/genaiscript/node_modules/ diff --git a/.toak-ignore b/.toak-ignore new file mode 100644 index 0000000..e70f0d6 --- /dev/null +++ b/.toak-ignore @@ -0,0 +1,3 @@ +package.json +genaisrc/genaiscript.d.ts +.toak-ignore \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..f208495 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1391 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "addr2line" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" + +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.97" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" + +[[package]] +name = "async-trait" +version = "0.1.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "autocfg" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" + +[[package]] +name = "axum" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" +dependencies = [ + "async-trait", + "axum-core", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "multer", + "percent-encoding", + "pin-project-lite", + "rustversion", + "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper 1.0.2", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" +dependencies = [ + "async-trait", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "rustversion", + "sync_wrapper 1.0.2", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "backtrace" +version = "0.3.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", + "windows-targets", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ac0150caa2ae65ca5bd83f25c7de183dea78d4d366469f148435e2acfbad0da" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "cpufeatures" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b80225097f2e5ae4e7179dd2266824648f3e2f49d9134d584b76389d31c4c3" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dotenv" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f" + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "fips204" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9fb5a367b9846933e271a3c2a992930743f82ae5e8cb7faa780715a80fa0b15" +dependencies = [ + "rand_core", + "sha2", + "sha3", + "zeroize", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "form_urlencoded" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "futures" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" + +[[package]] +name = "futures-executor" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" + +[[package]] +name = "futures-macro" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" + +[[package]] +name = "futures-task" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" + +[[package]] +name = "futures-util" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "fxhash" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" +dependencies = [ + "byteorder", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "gimli" +version = "0.31.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" + +[[package]] +name = "hermit-abi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" + +[[package]] +name = "http" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" +dependencies = [ + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d71d3574edd2771538b901e6549113b4006ece66150fb69c0fb6d9a2adae946" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97818827ef4f364230e16705d4706e2897df2bb60617d6ca15d598025a3c481f" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df2dcfbe0677734ab2f3ffa7fa7bfd4706bfdc1ef393f2ee30184aed67e631b4" +dependencies = [ + "bytes", + "futures-util", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "instant" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "itoa" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" + +[[package]] +name = "keccak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc2af9a1119c51f12a14607e783cb977bde58bc069ff0c3da1095e635d70654" +dependencies = [ + "cpufeatures", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.166" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2ccc108bbc0b1331bd061864e7cd823c0cab660bbe6970e66e2c0614decde36" + +[[package]] +name = "lock_api" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" + +[[package]] +name = "matchers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" +dependencies = [ + "regex-automata 0.1.10", +] + +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + +[[package]] +name = "memchr" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "miniz_oxide" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" +dependencies = [ + "adler2", +] + +[[package]] +name = "mio" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" +dependencies = [ + "hermit-abi", + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + +[[package]] +name = "nu-ansi-term" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" +dependencies = [ + "overload", + "winapi", +] + +[[package]] +name = "object" +version = "0.36.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedf0a2d09c573ed1d8d85b30c119153926a2b36dce0ab28322c09a117a4683e" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" + +[[package]] +name = "overload" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" + +[[package]] +name = "parking_lot" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" +dependencies = [ + "instant", + "lock_api", + "parking_lot_core 0.8.6", +] + +[[package]] +name = "parking_lot" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" +dependencies = [ + "lock_api", + "parking_lot_core 0.9.10", +] + +[[package]] +name = "parking_lot_core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc" +dependencies = [ + "cfg-if", + "instant", + "libc", + "redox_syscall 0.2.16", + "smallvec", + "winapi", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.7", + "smallvec", + "windows-targets", +] + +[[package]] +name = "percent-encoding" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" + +[[package]] +name = "pin-project-lite" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915a1e146535de9163f3987b8944ed8cf49a18bb0056bcebcdcece385cece4ff" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "proc-macro2" +version = "1.0.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "redox_syscall" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" +dependencies = [ + "bitflags 2.6.0", +] + +[[package]] +name = "regex" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata 0.4.9", + "regex-syntax 0.8.5", +] + +[[package]] +name = "regex-automata" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" +dependencies = [ + "regex-syntax 0.6.29", +] + +[[package]] +name = "regex-automata" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax 0.8.5", +] + +[[package]] +name = "regex-syntax" +version = "0.6.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" + +[[package]] +name = "regex-syntax" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" + +[[package]] +name = "rust-embed" +version = "8.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa66af4a4fdd5e7ebc276f115e895611a34739a9c1c01028383d612d550953c0" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "8.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6125dbc8867951125eec87294137f4e9c2c96566e61bf72c45095a7c77761478" +dependencies = [ + "proc-macro2", + "quote", + "rust-embed-utils", + "syn", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "8.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5347777e9aacb56039b0e1f28785929a8a3b709e87482e7442c72e7c12529d" +dependencies = [ + "sha2", + "walkdir", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" + +[[package]] +name = "rustversion" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e819f2bc632f285be6d7cd36e25940d45b2391dd6d9b939e79de557f7014248" + +[[package]] +name = "ryu" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.215" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.215" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.133" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af99884400da37c88f5e9146b7f1fd0fbcae8f6eec4e9da38b67d05486f814a6" +dependencies = [ + "itoa", + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha3" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60" +dependencies = [ + "digest", + "keccak", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shell-escape" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45bb67a18fa91266cc7807181f62f9178a6873bfad7dc788c42e6430db40184f" + +[[package]] +name = "signal-hook-registry" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" +dependencies = [ + "libc", +] + +[[package]] +name = "slab" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" +dependencies = [ + "autocfg", +] + +[[package]] +name = "sled" +version = "0.34.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f96b4737c2ce5987354855aed3797279def4ebf734436c6aa4552cf8e169935" +dependencies = [ + "crc32fast", + "crossbeam-epoch", + "crossbeam-utils", + "fs2", + "fxhash", + "libc", + "log", + "parking_lot 0.11.2", +] + +[[package]] +name = "smallvec" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" + +[[package]] +name = "socket2" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + +[[package]] +name = "syn" +version = "2.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d46482f1c1c87acd84dea20c1bf5ebff4c757009ed6bf19cfd36fb10e92c4e" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "thread_local" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" +dependencies = [ + "cfg-if", + "once_cell", +] + +[[package]] +name = "tokio" +version = "1.41.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cfb5bee7a6a52939ca9224d6ac897bb669134078daa8735560897f69de4d33" +dependencies = [ + "backtrace", + "bytes", + "libc", + "mio", + "parking_lot 0.12.3", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-stream" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f4e6ce100d0eb49a2734f8c0812bcd324cf357d21810932c5df6b96ef2b86f1" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61e7c3654c13bcd040d4a03abee2c75b1d14a37b423cf5a813ceae1cc903ec6a" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2873938d487c3cfb9aed7546dc9f2711d867c9f90c46b889989a2cb84eba6b4f" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper 0.1.2", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "403fa3b783d4b626a8ad51d766ab03cb6d2dbfc46b1c5d4448395e6628dc9697" +dependencies = [ + "bitflags 2.6.0", + "bytes", + "http", + "http-body", + "pin-project-lite", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "typenum" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" + +[[package]] +name = "unicode-ident" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" + +[[package]] +name = "uuid" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8c5f0a0af699448548ad1a2fbf920fb4bee257eae39953ba95cb84891a0446a" +dependencies = [ + "getrandom", +] + +[[package]] +name = "valuable" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "web-agent-rs" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "base64", + "bytes", + "dotenv", + "fips204", + "futures", + "http", + "lazy_static", + "rust-embed", + "serde", + "serde_json", + "shell-escape", + "sled", + "tokio", + "tokio-stream", + "tokio-util", + "tower-http", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "zeroize" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..ddbb0e5 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "web-agent-rs" +version = "0.1.0" +edition = "2021" + +[[bin]] +edition = "2021" +name = "agent-server" +path = "src/main.rs" + +[dependencies] +axum = { version = "0.7", features = ["multipart"] } +serde = { version = "1.0", features = ["derive"] } +tokio = { version = "1.0", features = ["full"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +http = "1.1.0" +tokio-stream = "0.1.16" +uuid = { version = "1.11.0", features = ["v4"] } +tokio-util = { version = "0.7", features = ["io"] } +serde_json = "1.0.133" +futures = "0.3.31" +dotenv = "0.15.0" +shell-escape = "0.1.5" +rust-embed = "8.5.0" +bytes = "1.8.0" +lazy_static = "1.5.0" +sled = "0.34.7" +tower-http = { version = "0.6.2", features = ["trace"] } +anyhow = "1.0.97" +base64 = "0.22.1" +fips204 = "0.4.6" + diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..ef133fc --- /dev/null +++ b/Dockerfile @@ -0,0 +1,88 @@ +# Stage 1: Build the Rust agent-core binary +FROM rust:1.73-slim-bullseye as agent-server-builder + +WORKDIR /build-context + +# Install only the minimal required build dependencies +RUN apt-get update && apt-get install -y --no-install-recommends \ + pkg-config \ + musl-tools \ + && rm -rf /var/core/apt/lists/* + +# Build for musl to ensure static linking +RUN rustup target add aarch64-unknown-linux-musl + +# Copy only necessary files for building +COPY Cargo.toml Cargo.lock ./ +COPY src ./src +COPY assets ./assets + +# Build with musl target for static linking +RUN cargo build --release --target aarch64-unknown-linux-musl && \ + strip /build-context/target/aarch64-unknown-linux-musl/release/agent-core + +# Stage 2: Build Bun dependencies +FROM oven/bun:alpine as node-builder + +# Install system dependencies and node-gyp +RUN apk add --no-cache \ + ca-certificates \ + curl \ + unzip \ + git \ + python3 \ + py3-pip \ + build-base \ + pkgconf \ + cmake \ + nodejs \ + npm \ + bash \ + chromium \ + nss \ + freetype \ + freetype-dev \ + harfbuzz \ + ca-certificates \ + ttf-freefont \ + font-noto-emoji \ + nodejs \ + wqy-zenhei \ + && rm -rf /var/cache/* \ + && mkdir /var/cache/apk \ + && npm install -g node-gyp + +WORKDIR /app +# dep files +COPY packages packages +COPY package.json package-lock.json ./ +## Install deps +RUN bun install && bun --filter='./packages/genaiscript-rust-shim' run buildShim + + +FROM node:20-bookworm as app + +WORKDIR /app + +# Install playwright +ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/lib/chromium/chromium \ + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npx -y playwright@1.49.1 install --with-deps chromium && npm install -g bun + + +COPY --from=node-builder /app/node_modules ./node_modules +COPY --from=node-builder /app/package.json . +COPY --from=agent-server-builder /build-context/target/aarch64-unknown-linux-musl/release/agent-server ./agent-server + +# Ensure the binary is executable +RUN chmod +x ./agent-core + +# copy agent source files +COPY packages/genaiscript-rust-shim/dist ./dist +COPY genaisrc ./genaisrc + +# Expose the required port +EXPOSE 3006 + +# Set the entrypoint to the Rust binary +ENTRYPOINT ["./agent-server"] diff --git a/Local.Dockerfile b/Local.Dockerfile new file mode 100644 index 0000000..ebd13e7 --- /dev/null +++ b/Local.Dockerfile @@ -0,0 +1,88 @@ +# Stage 1: Build the Rust agent-core binary +FROM rust:1-slim-bullseye as agent-server-builder + +WORKDIR /build-context + +# Install only the minimal required build dependencies +RUN apt-get update && apt-get install -y --no-install-recommends \ + pkg-config \ + musl-tools \ + && rm -rf /var/lib/apt/lists/* + +# Build for musl to ensure static linking +RUN rustup target add aarch64-unknown-linux-musl + +# Copy only necessary files for building +COPY Cargo.toml Cargo.lock ./ +COPY src ./src +COPY assets ./assets + +# Build with musl target for static linking +RUN cargo build --release --target aarch64-unknown-linux-musl && \ + strip /build-context/target/aarch64-unknown-linux-musl/release/agent-server + +# Stage 2: Build Bun dependencies +FROM oven/bun:alpine as node-builder + +# Install system dependencies and node-gyp +RUN apk add --no-cache \ + ca-certificates \ + curl \ + unzip \ + git \ + python3 \ + py3-pip \ + build-base \ + pkgconf \ + cmake \ + nodejs \ + npm \ + bash \ + chromium \ + nss \ + freetype \ + freetype-dev \ + harfbuzz \ + ca-certificates \ + ttf-freefont \ + font-noto-emoji \ + nodejs \ + wqy-zenhei \ + && rm -rf /var/cache/* \ + && mkdir /var/cache/apk \ + && npm install -g node-gyp + +WORKDIR /app +# dep files +COPY packages packages +COPY package.json package-lock.json bun.lockb ./ +## Install deps +RUN bun install + + +FROM node:20-bookworm as app + +WORKDIR /app + +# Install playwright +ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/lib/chromium/chromium \ + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npx -y playwright@1.49.1 install --with-deps chromium && npm install -g bun + + +COPY --from=node-builder /app/node_modules ./node_modules +COPY --from=node-builder /app/package.json . +COPY --from=node-builder /app/packages ./packages +COPY --from=agent-server-builder /build-context/target/aarch64-unknown-linux-musl/release/agent-server ./agent-server + +# Ensure the binary is executable +RUN chmod +x ./agent-server + +# copy agent source files +COPY packages/genaiscript-rust-shim/dist ./dist + +# Expose the required port +EXPOSE 3006 + +# Set the entrypoint to the Rust binary +ENTRYPOINT ["./agent-server"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..e8fae7a --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# web-agent-rs +Hacky genaiscript host for integration into conversational AI applications. + +### Disclaimer +This has not undergone a formal security assessment. You should do your own evaluation before using this. + +### How it works +1. A chat client specifies the URL to this host in their environment. +2. They send a request with their credentials to create a stream resource + + +## Docs +The [docs](./docs) folder is under construction \ No newline at end of file diff --git a/Remote.Dockerfile b/Remote.Dockerfile new file mode 100644 index 0000000..5a57a97 --- /dev/null +++ b/Remote.Dockerfile @@ -0,0 +1,88 @@ +# Stage 1: Build the Rust agent-server binary +FROM rust:1-slim-bullseye as agent-server-builder + +WORKDIR /build-context + +# Install only the minimal required build dependencies +RUN apt-get update && apt-get install -y --no-install-recommends \ + pkg-config \ + musl-tools \ + && rm -rf /var/lib/apt/lists/* + +# Build for musl to ensure static linking +RUN rustup target add x86_64-unknown-linux-musl + +# Copy only necessary files for building +COPY Cargo.toml Cargo.lock ./ +COPY src ./src +COPY assets ./assets + +# Build with musl target for static linking +RUN cargo build --release --target x86_64-unknown-linux-musl && \ + strip /build-context/target/x86_64-unknown-linux-musl/release/agent-server + +# Stage 2: Build Bun dependencies +FROM oven/bun:alpine as node-builder + +# Install system dependencies and node-gyp +RUN apk add --no-cache \ + ca-certificates \ + curl \ + unzip \ + git \ + python3 \ + py3-pip \ + build-base \ + pkgconf \ + cmake \ + nodejs \ + npm \ + bash \ + chromium \ + nss \ + freetype \ + freetype-dev \ + harfbuzz \ + ca-certificates \ + ttf-freefont \ + font-noto-emoji \ + nodejs \ + wqy-zenhei \ + && rm -rf /var/cache/* \ + && mkdir /var/cache/apk \ + && npm install -g node-gyp + +WORKDIR /app +# dep files +COPY packages packages +COPY package.json package-lock.json bun.lockb ./ +## Install deps +RUN bun install + + +FROM node:20-bookworm as app + +WORKDIR /app + +# Install playwright +ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/lib/chromium/chromium \ + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npx -y playwright@1.49.1 install --with-deps chromium && npm install -g bun + + +COPY --from=node-builder /app/node_modules ./node_modules +COPY --from=node-builder /app/package.json . +COPY --from=node-builder /app/packages ./packages +COPY --from=agent-server-builder /build-context/target/x86_64-unknown-linux-musl/release/agent-server ./agent-server + +# Ensure the binary is executable +RUN chmod +x ./agent-server + +# copy agent source files +COPY packages/genaiscript-rust-shim/dist ./dist + +# Expose the required port +EXPOSE 3006 + +# Set the entrypoint to the Rust binary +ENTRYPOINT ["./agent-server"] diff --git a/assets/index.html b/assets/index.html new file mode 100644 index 0000000..1f04423 --- /dev/null +++ b/assets/index.html @@ -0,0 +1,62 @@ + + + + + Axum Server UI + + + + +

Axum Server UI

+ + +
+ + \ No newline at end of file diff --git a/bun.lockb b/bun.lockb new file mode 100755 index 0000000..515319e Binary files /dev/null and b/bun.lockb differ diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..ec80c5f --- /dev/null +++ b/compose.yml @@ -0,0 +1,32 @@ +services: + agent-server: + build: + context: . + dockerfile: Local.Dockerfile + ports: + - "3006:3006" + environment: + # Load environment variables from the .env file + # The .env file should contain OPENAI_API_KEY, BING_SEARCH_API_KEY, TAVILY_API_KEY, etc. + - OPENAI_API_BASE=${OPENAI_API_BASE} + - OPENAI_API_KEY=${OPENAI_API_KEY} + - GENAISCRIPT_MODEL_LARGE=${GENAISCRIPT_MODEL_LARGE} + - GENAISCRIPT_MODEL_SMALL=${GENAISCRIPT_MODEL_SMALL} + - BING_SEARCH_API_KEY=${BING_SEARCH_API_KEY} + - BING_SEARCH_API_KEY=${BING_SEARCH_API_KEY} + - TAVILY_API_KEY=${TAVILY_API_KEY} + - PERIGON_API_KEY=${PERIGON_API_KEY} + - SEARXNG_API_BASE_URL=${SEARXNG_API_BASE_URL} + - PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium-browser + env_file: "./.env" + develop: + watch: + - action: sync + path: ./packages/genaiscript/genaisrc + target: /app/web/packages/genaiscript/genaisrc + ignore: + - node_modules/ + - action: rebuild + path: ./src + - action: rebuild + path: cargo.toml diff --git a/docs/tokens.md b/docs/tokens.md new file mode 100644 index 0000000..c2afdfa --- /dev/null +++ b/docs/tokens.md @@ -0,0 +1,77 @@ +# Authentication System Documentation + +## Overview + +This document outlines the token-based authentication system used in web-agent-rs. The system uses FIPS204 signatures to +generate secure session tokens containing user data. + +## Core Components + +TODO: In the meantime, here's some hamfisted knowledge. + + +```javascript +class FIPS204KeyPair { + constructor() { + this.publicKey = "FIPS204_PUBLIC_KEY"; // Placeholder + this.privateKey = "FIPS204_PRIVATE_KEY"; // Placeholder + } + + sign(data) { + // Placeholder for actual FIPS204 signing logic + return `FIPS204_${data}_SIGNED`; + } + + verify(data, signature) { + // Placeholder for actual FIPS204 verification + return true; + } +} + +/* NOTES: +- the public key needs to be retrievable, so it can be used to verify payload signature at the time of the request. +- the private key is disposed so it can't be used to create more signatures +- future tokens should use a completely new keypair + + +- The fips204 authentication scheme was selected for its performance, flexibility, and key-length. +- It would be wise to configure additional protections like ip whitelisting and rate limiting. +*/ + +// User object representing token payload data +const user = { + sub: "user123", + name: "John Doe", + email: "john@example.com", + roles: ["user"], + iat: Math.floor(Date.now() / 1000), + exp: Math.floor(Date.now() / 1000) + (60 * 60) // 1 hour from now +}; + +const keyPair = new FIPS204KeyPair(); +const signature = keyPair.sign(JSON.stringify(user)); + +function createToken(payload, signature) { + const encodedPayload = Buffer.from(JSON.stringify(payload)).toString('base64'); + const encodedSignature = Buffer.from(signature).toString('base64'); + return `${encodedPayload}.${encodedSignature}`; +} + +const token = createToken(user, signature); + + +async function createStreamRequest(eventHost = "https://agent.example.com") { + + const requestParams = { + // will automagically include the session token as a cookie, where it will be parsed by the agent server + credentials: "include" + } + + const response = await fetch(eventHost, requestParams); + + const {streamId} = await response.json(); + + // This stream id is then supplied as a path parameter to stream, the token is validated to ensure the stream belongs to the user, and the stream is returned. + return streamId; +} +``` \ No newline at end of file diff --git a/fly.toml b/fly.toml new file mode 100644 index 0000000..b7fdefc --- /dev/null +++ b/fly.toml @@ -0,0 +1,54 @@ +app = "web-agent-rs" +primary_region = "iad" + +[deploy] + strategy = "rolling" + +[build] + dockerfile = "Remote.Dockerfile" + deploy-target = "app" + + + +[env] + OPENAI_API_KEY="" + OPENAI_API_BASE="" + GENAISCRIPT_MODEL_LARGE="" + GENAISCRIPT_MODEL_SMALL="" + GENAISCRIPT_MODEL_PROVIDER="" + + SEARXNG_API_BASE_URL="" + SEARXNG_PASSWORD="" + BING_SEARCH_API_KEY = "" + TAVILY_API_KEY = "" + PERIGON_API_KEY= "" + CEREBRAS_API_KEY = "" + CCC_API_KEY="" + HF_API_KEY="" + +[http_service] + internal_port = 3006 + force_https = true + auto_stop_machines = "suspend" + auto_start_machines = true + # automatic shutdown when not in use + min_machines_running = 0 + + [http_service.http_options] + idle_timeout = 180 + + + [[http_service.checks]] + interval = '30s' + timeout = '5s' + grace_period = '10s' + method = 'GET' + path = '/health' + +[[vm]] + size = "performance-1x" + + +[[mounts]] +source = "web_agent_app_mount" +destination = "/app/data" diff --git a/gitleaks-report.json b/gitleaks-report.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/gitleaks-report.json @@ -0,0 +1 @@ +[] diff --git a/package.json b/package.json new file mode 100644 index 0000000..8223549 --- /dev/null +++ b/package.json @@ -0,0 +1,20 @@ +{ + "name": "web-agent-rs", + "type": "module", + "workspaces": ["packages/*"], + "private": true, + "scripts": { + "dev": "bunx kill-port 3006 && bun run build && cargo watch -x 'run src/main.rs'", + "ai:search": "genaiscript run packages/genaiscript/genaisrc/web-search.genai.mts --vars USER_INPUT='who won the 2024 election?'", + "shim:ai:search": "pnpm build && ./dist/shim.js --file=genaisrc/search.genai.mts USER_INPUT=\"Who won the 2024 presidential election?\"\n", + "ai:news": "genaiscript run packages/genaiscript/genaisrc/news-search.genai.mts --vars USER_INPUT='What are the latest updates and developments in the Ukraine war?'", + "ai:url:read": "genaiscript run packages/genaiscript/genaisrc/web-scrape.genai.mts --vars USER_INPUT='{\"url\":\"https://geoff.seemueller.io/about\",\"query\":\"Describe the details of the page.\", \"action\": \"read\"}'", + "ai:url:scrape": "npx genaiscript run packages/genaiscript/genaisrc/web-scrape.genai.mts --vars USER_INPUT='{\"url\":\"https://www.time4learning.com/homeschool-curriculum/high-school/eleventh-grade/math.html\",\"query\":\"What is on this page?\", \"action\": \"scrape\"}'", + "crypto:quote": "npx genaiscript run packages/genaiscript/genaisrc/finance-query.genai.mts --vars USER_INPUT='Get a quote for BTC'", + "crypto:news": "npx genaiscript run packages/genaiscript/genaisrc/finance-query.genai.mts --vars USER_INPUT='What is the news for Bitcoin?'", + "crypto:overview": "npx genaiscript run packages/genaiscript/genaisrc/finance-query.genai.mts --vars USER_INPUT='What are the trending symbols in the market?'", + "compose:up": "docker compose up --build", + "prod:logs": "fly logs", + "build": "(cd packages/genaiscript-rust-shim && bun run buildShim)" + } +} diff --git a/packages/core/index.ts b/packages/core/index.ts new file mode 100644 index 0000000..5eb5667 --- /dev/null +++ b/packages/core/index.ts @@ -0,0 +1,4 @@ +export * from "../genaiscript/genaisrc/_state"; +export * from "./news"; +export * from "./quotes"; +export * from "./types"; \ No newline at end of file diff --git a/packages/core/market/index.ts b/packages/core/market/index.ts new file mode 100644 index 0000000..18a5b81 --- /dev/null +++ b/packages/core/market/index.ts @@ -0,0 +1,14 @@ +import {ApiResponse} from "./types"; + +export async function collect_gainers_losers(x: { apiKey: string, limit: number }): Promise { + const { apiKey, limit } = x; + + // + const data: ApiResponse = await fetch(`https://pro-api.coinmarketcap.com/v1/cryptocurrency/trending/gainers-losers?limit=${limit}`, { + headers: { + "x-cmc_pro_api_key": apiKey + } + }).then((symbolDataRequest) => symbolDataRequest.json()); + + return data; +} \ No newline at end of file diff --git a/packages/core/market/types.ts b/packages/core/market/types.ts new file mode 100644 index 0000000..636c0c4 --- /dev/null +++ b/packages/core/market/types.ts @@ -0,0 +1,48 @@ +type Quote = { + price: number; + volume_24h: number; + percent_change_1h: number; + percent_change_24h: number; + percent_change_7d: number; + market_cap: number; + last_updated: string; +}; + +type Platform = null; + +type Tag = string; + +type Data = { + id: number; + name: string; + symbol: string; + slug: string; + cmc_rank?: number; + num_market_pairs: number; + circulating_supply: number; + total_supply: number; + max_supply: number; + last_updated: string; + date_added: string; + tags: Tag[]; + platform: Platform; + quote: { + USD: Quote; + BTC?: Quote; + ETH?: Quote; + }; +}; + +type Status = { + timestamp: string; + error_code: number; + error_message: string | null; + elapsed: number; + credit_count: number; +}; + +export type ApiResponse = { + data: Data[]; + status: Status; +}; + diff --git a/packages/core/news/index.ts b/packages/core/news/index.ts new file mode 100644 index 0000000..a383801 --- /dev/null +++ b/packages/core/news/index.ts @@ -0,0 +1,178 @@ +import {types, Instance} from 'mobx-state-tree'; +import {runInAction} from "mobx"; + + +const Article = types.model('Article', { + title: types.string, + content: types.string, + url: types.maybe(types.string), + source: types.maybe(types.string), + pubDate: types.maybe(types.string), + + summary: types.maybe(types.string), + description: types.maybe(types.string), + authorsByline: types.maybe(types.string), + shortSummary: types.maybe(types.string), + labels: types.maybe(types.frozen()), + imageUrl: types.maybe(types.string), + score: types.maybe(types.number), +}); + + +export const NewsStore = types + .model('NewsStore', { + symbolsNews: types.map(types.array(Article)), + isLoading: types.boolean, + error: types.maybe(types.string), + apiKey: types.string, + }) + .actions((self) => ({ + + addNews(symbol: string, articles: any[]) { + if (!self.symbolsNews.has(symbol)) { + self.symbolsNews.set(symbol, []); + } + + + const mappedArticles = articles.map((article) => Article.create({ + title: article.title || 'No Title', + content: article.content || 'No Content', + url: article.url, + source: article.domain, + pubDate: article.pubDate, + summary: article.summary, + description: article.description, + authorsByline: article.authorsByline, + shortSummary: article.shortSummary, + labels: article.labels, + imageUrl: article.imageUrl, + score: article.score, + + + })); + self.symbolsNews.get(symbol)!.push(...mappedArticles); + self.isLoading = false; + }, + + clearNews(symbol: string) { + if (self.symbolsNews.has(symbol)) { + self.symbolsNews.set(symbol, []); + } + }, + + setLoading(loading: boolean) { + self.isLoading = loading; + }, + + setError(message: string) { + self.error = message; + self.isLoading = false; + }, + + async fetchNewsForSymbol(symbol: string, limit: number, sort: "date" | "relevance") { + self.setLoading(true); + self.setError(undefined); + + try { + await runInAction(async () => { + const newsData = await collect_news({symbol, apiKey: self.apiKey, limit, sort}); + if (newsData && newsData.articles) { + self.addNews(symbol, newsData.articles); + } else { + self.setError("Failed to fetch news or invalid response format."); + } + }) + + + } catch (err: any) { + console.error('Error fetching news:', err); + self.setError(err.message || "Failed to fetch news."); + } + }, + })) + .views((self) => ({ + + getNewsForSymbol(symbol: string) { + + return self.symbolsNews.get(symbol) || []; + }, + + getAllSymbols() { + return Array.from(self.symbolsNews.keys()); + }, + + hasNewsForSymbol(symbol: string) { + return self.symbolsNews.has(symbol) && self.symbolsNews.get(symbol)!.length > 0; + }, + })); + +export type INewsStore = Instance; + + +export const createNewsStore = (apikey, perigon) => NewsStore.create({ + symbolsNews: {}, + isLoading: false, + error: undefined, + apiKey: apikey, +}); + +/* @collect_news return value structure +{ +news: { +status: 200, +numResults: 4080, +articles: [ + [Object], [Object], + [Object], [Object], + [Object], [Object], + [Object], [Object], + [Object], [Object] +] +} +} + */ +export async function collect_news(x: { symbol: string, apiKey: string, limit: number, sort: "date" | "relevance" }) { + + + const {symbol, apiKey, limit, sort} = x; + + const symbolNameMap = { + "BTC": "Bitcoin", + "ETH": "Ethereum", + "XRP": "Ripple", + "LTC": "Litecoin", + "ADA": "Cardano", + "DOGE": "Dogecoin", + "BNB": "Binance Coin", + "DOT": "Polkadot", + "SOL": "Solana", + "AVAX": "Avalanche" + }; + + + const cryptocurrencyName = symbolNameMap[symbol] ?? symbol; + + + const rawContentQuery = "scandal OR \"corporate misconduct*\" OR fraud OR \"financial irregularities*\" OR lawsuit OR \"legal action*\" OR bankruptcy OR \"financial distress*\" OR \"data breach\" OR \"security vulnerability*\" OR \"environmental impact\" OR \"ecological damage*\" OR \"labor dispute\" OR \"worker rights*\" OR \"product failure\" OR \"quality issue*\" OR \"ethical concern\" OR \"moral dilemma*\" OR \"health risk\" OR \"safety hazard*\" OR \"regulatory violation\" OR \"compliance issue*\" OR \"market manipulation\" OR \"trading irregularity*\" OR \"public relations crisis\" OR \"reputation damage*\" OR \"political controversy\" OR \"government intervention*\" OR \"consumer complaint\" OR \"customer dissatisfaction*\" OR \"supply chain disruption\" OR \"logistics problem*\" OR \"intellectual property dispute\" OR \"patent infringement*\""; + const contentQuery = encodeURIComponent(rawContentQuery); + + + const rawTitleQuery = `${cryptocurrencyName} OR ${symbol} OR "${cryptocurrencyName} price" OR "${cryptocurrencyName} market" OR "${cryptocurrencyName} news"`; + const titleQuery = encodeURIComponent(rawTitleQuery); + + try { + const result = await allNews({ + q: contentQuery, + title: titleQuery, + size: limit, + sortBy: sort, + apiKey: apiKey + }); + + + return result.data; + } catch (err) { + console.error('Error fetching news:', err); + throw err; + } +} diff --git a/packages/core/news/news.test.ts b/packages/core/news/news.test.ts new file mode 100644 index 0000000..3d4a3df --- /dev/null +++ b/packages/core/news/news.test.ts @@ -0,0 +1,75 @@ +import {describe, expect, it} from 'vitest'; +import {collect_news, createNewsStore, NewsStore} from './index'; + + +const testApiKey = ''; + +describe('NewsStore', () => { + it('should create a NewsStore instance', () => { + const store = createNewsStore(testApiKey); + expect(store).toBeDefined(); + expect(store.isLoading).toBe(false); + expect(store.error).toBeUndefined(); + expect(store.getAllSymbols()).toEqual([]); + }); + + it('should add news articles for a symbol', () => { + const store = createNewsStore(testApiKey); + const articles = [ + { title: 'Article 1', content: 'Content 1', url: 'http://example.com/1', source: 'Source 1', publishedAt: '2025-01-01' }, + { title: 'Article 2', content: 'Content 2', url: 'http://example.com/2', source: 'Source 2', publishedAt: '2025-01-02' } + ]; + + store.addNews('BTC', articles); + + expect(store.getNewsForSymbol('BTC')).toHaveLength(2); + expect(store.getNewsForSymbol('BTC')[0].title).toBe('Article 1'); + expect(store.getNewsForSymbol('BTC')[1].title).toBe('Article 2'); + expect(store.hasNewsForSymbol('BTC')).toBe(true); + }); + + it('should clear news articles for a symbol', () => { + const store = createNewsStore(testApiKey); + const articles = [ + { title: 'Article 1', content: 'Content 1', url: 'http://example.com/1', source: 'Source 1', publishedAt: '2025-01-01' } + ]; + + store.addNews('BTC', articles); + store.clearNews('BTC'); + + expect(store.getNewsForSymbol('BTC')).toHaveLength(0); + expect(store.hasNewsForSymbol('BTC')).toBe(false); + }); + + it('should handle fetchNewsForSymbol successfully', async () => { + const store = createNewsStore(testApiKey); + + await store.fetchNewsForSymbol('BTC', 10, 'date'); + + const storeNews = store.getNewsForSymbol('BTC'); + + console.log(storeNews); + + expect(storeNews).toHaveLength(10); + expect(store.getNewsForSymbol('BTC')[0].title).toBeTypeOf("string"); + expect(store.isLoading).toBe(false); + expect(store.error).toBeUndefined(); + }); + + + + + it('should throw an error for invalid symbol in collect_news', async () => { + await expect(collect_news({ symbol: 'INVALID', apiKey: testApiKey, limit: 10, sort: 'date' })) + .rejects.toThrow('Invalid symbol: INVALID. Must be one of BTC, ETH, XRP, LTC, ADA, DOGE, BNB, DOT, SOL, AVAX.'); + }); + + it('should fetch news using collect_news', async () => { + + const result = await collect_news({ symbol: 'BTC', apiKey: testApiKey, limit: 1, sort: 'date' }); + + expect(result).toBeDefined(); + expect(result.status).toBe(200); + expect(result.articles).toBeDefined(); + }); +}); \ No newline at end of file diff --git a/packages/core/package.json b/packages/core/package.json new file mode 100644 index 0000000..88604b1 --- /dev/null +++ b/packages/core/package.json @@ -0,0 +1,9 @@ +{ + "name": "@web-agent-rs/core", + "version": "1.0.0", + "type": "module", + "dependencies": { + "mobx-state-tree": "^7.0.2", + "@web-agent-rs/perigon": "workspace:*" + } +} \ No newline at end of file diff --git a/packages/core/portfolio/index.ts b/packages/core/portfolio/index.ts new file mode 100644 index 0000000..3609718 --- /dev/null +++ b/packages/core/portfolio/index.ts @@ -0,0 +1,137 @@ +import {getSnapshot, types} from "mobx-state-tree"; +import {NewsStore} from "../news"; + + +const PortfolioCashModel = types.model("PortfolioCash", { + amount: types.number, + currency: types.enumeration("Currency", ["USD", "BTC"]), +}); + + +const PortfolioActionModel = types.model("PortfolioAction", { + action: types.enumeration("Action", ["buy", "sell", "hold"]), + symbol: types.string, + quantity: types.number, + timestamp: types.Date, +}); + + +export const PortfolioNewsportfolioNewsModel = types.model("PortfolioNews", { + symbol: types.string, + date_created: types.string, + news: types.array(types.model("NewsItem", { + symbol: types.maybe(types.string), + date_created: types.maybe(types.string), + news: types.string, + timestamp: types.maybe(types.string), + })), + timestamp: types.maybe(types.string), +}); + +export const portfolioQuoteModel = types.model("PortfolioQuote", { + symbol: types.string, + quote: types.string, + date_created: types.string, +}); + + +const PortfolioAssetContextModel = types.model("PortfolioAssetContext", { + timestamp: types.Date, + portfolio_snapshot: PortfolioCashModel, +}); + + +const PortfolioAssetModel = types.model("PortfolioAsset", { + symbol: types.string, + quantity: types.number, + recommended_action: types.maybe( + types.enumeration("RecommendedAction", ["buy", "sell", "hold"]) + ), + last_taken_action: types.optional(types.enumeration("LastAction", ["buy", "sell", "hold", "none", "never"]), "never"), + context: PortfolioAssetContextModel, +}); + + +const PortfolioModel = types + .model("Portfolio", { + supportedSymbols: types.array(types.string), + liquidity: PortfolioCashModel, + actions: types.optional(types.array(PortfolioActionModel), []), + assets: types.array(PortfolioAssetModel), + news: types.optional(types.array(NewsStore), []), + quotes: types.optional(types.array(portfolioQuoteModel), []), + }) + .actions((self) => ({ + + addAction(actionData: { + action: "buy" | "sell" | "hold"; + symbol: string; + quantity: number; + }) { + self.actions.push({ + ...actionData, + timestamp: new Date(), + }); + }, + addNews(newsData: any) { + self.news.push({ + ...newsData, + timestamp: new Date(), + }); + }, + addQuote(quoteData: any) { + self.quotes + self.quotes.push({ + ...quoteData, + timestamp: new Date(), + }); + }, + + updateLiquidity(amount: number) { + self.liquidity.amount = amount; + }, + })); + +const tokenList = [ + "AAVE", "AVAX", "BAT", "BCH", "BTC", + "CRV", "DOGE", "DOT", "ETH", "GRT", + "LINK", "LTC", "MKR", "SHIB", "SUSHI", + "UNI", "USDC", "USDT", "XTZ", "YFI", +]; + + +const portfolioCash = PortfolioCashModel.create({ + amount: 10000, + currency: "USD", +}); + + +const portfolioAssets = tokenList.map((token) => + PortfolioAssetModel.create({ + symbol: token, + quantity: 0, + recommended_action: "hold", + last_taken_action: undefined, + context: { + timestamp: new Date(), + portfolio_snapshot: getSnapshot(portfolioCash), + }, + }) +); + + +const portfolioActions = []; +const portfolioNews = []; +const portfolioQuotes = []; + + +const portfolioInstance = PortfolioModel.create({ + liquidity: portfolioCash, + actions: portfolioActions, + assets: portfolioAssets, + supportedSymbols: tokenList, + news: portfolioNews, + quotes: portfolioQuotes +}); + +export default portfolioInstance; diff --git a/packages/core/quotes/index.ts b/packages/core/quotes/index.ts new file mode 100644 index 0000000..c911100 --- /dev/null +++ b/packages/core/quotes/index.ts @@ -0,0 +1,13 @@ +import {ApiResponse} from "./types"; + +export async function collect_quote(x: { symbol: string, apiKey: string }) { + const {symbol, apiKey} = x; + + const data: ApiResponse = await fetch(`https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest?symbol=${symbol}`, { + headers: { + "x-cmc_pro_api_key": apiKey + } + }).then((symbolDataRequest) => symbolDataRequest.json()); + + return data; +} \ No newline at end of file diff --git a/packages/core/quotes/models.ts b/packages/core/quotes/models.ts new file mode 100644 index 0000000..a38c9d5 --- /dev/null +++ b/packages/core/quotes/models.ts @@ -0,0 +1,77 @@ +import {types, flow, Instance} from "mobx-state-tree"; +import {collect_quote} from './index'; + + +const QuoteData = types.optional(types.frozen(), {}) + +export const QuoteStore = types + .model("QuoteStore", { + apiKey: types.string, + quotes: types.map(QuoteData), + }) + .views(self => ({ + getQuote(symbol) { + return self.quotes.get(symbol); + }, + + hasQuote(symbol) { + return self.quotes.has(symbol); + } + })) + .actions(self => { + + const extractUsefulData = (data, symbol) => { + return data.data[symbol].map(qd => ({ + symbol: qd.symbol, + slug: qd.slug, + tags: qd.tags, + id: qd.id, + ...qd.quote.USD + })).at(0); + }; + + const fetchQuote = flow(function* (symbol) { + try { + const data = yield collect_quote({symbol, apiKey: self.apiKey}); + const usefulData = extractUsefulData(data, symbol); + + + self.quotes.set(symbol, usefulData); + + return usefulData; + } catch (error) { + console.error(`An error occurred fetching the quote for symbol: ${symbol}`, error); + throw error; + } + }); + + const fetchQuotes = flow(function* (symbols) { + const results = {}; + + for (const symbol of symbols) { + + if (self.quotes.has(symbol)) { + results[symbol] = self.quotes.get(symbol); + } else { + + const data = yield fetchQuote(symbol); + results[symbol] = extractUsefulData(data, symbol); + } + } + + return results; + }); + + const clearCache = () => { + self.quotes.clear(); + }; + + return { + fetchQuote, + fetchQuotes, + clearCache + }; + }); + + +export type QuoteManagerType = Instance; \ No newline at end of file diff --git a/packages/core/quotes/quote.test.ts b/packages/core/quotes/quote.test.ts new file mode 100644 index 0000000..6e79ac3 --- /dev/null +++ b/packages/core/quotes/quote.test.ts @@ -0,0 +1,17 @@ +import {describe, it} from 'vitest'; +import {QuoteStore} from "./models"; + +describe('QuoteStore', () => { + it('should get data for symbols using the quoteManager', async () => { + const testApiKey = ''; + const quoteManager = QuoteStore.create({ + apiKey: testApiKey, + }); + + const symbol = 'BTC'; + + const data = await quoteManager.fetchQuote(symbol); + + console.log(JSON.stringify(data)); + }); +}); \ No newline at end of file diff --git a/packages/core/quotes/types.ts b/packages/core/quotes/types.ts new file mode 100644 index 0000000..06228fd --- /dev/null +++ b/packages/core/quotes/types.ts @@ -0,0 +1,71 @@ +type Status = { + timestamp: string; + error_code: number; + error_message: string | null; + elapsed: number; + credit_count: number; + notice: string | null; +}; + +type Tag = { + slug: string; + name: string; + category: string; +}; + +type Quote = { + USD: { + price: number | null; + volume_24h: number; + volume_change_24h: number; + percent_change_1h: number; + percent_change_24h: number; + percent_change_7d: number; + percent_change_30d: number; + percent_change_60d: number; + percent_change_90d: number; + market_cap: number | null; + market_cap_dominance: number | null; + fully_diluted_market_cap: number | null; + tvl: number | null; + last_updated: string; + }; +}; + +type Platform = { + id: number; + name: string; + symbol: string; + slug: string; + token_address: string; +}; + +type Cryptocurrency = { + id: number; + name: string; + symbol: string; + slug: string; + num_market_pairs: number; + date_added: string; + tags: Tag[]; + max_supply: number | null; + circulating_supply: number | null; + total_supply: number; + platform: Platform | null; + is_active: number; + infinite_supply: boolean; + cmc_rank: number | null; + is_fiat: number; + self_reported_circulating_supply: number | null; + self_reported_market_cap: number | null; + tvl_ratio: number | null; + last_updated: string; + quote: Quote; +}; + +export type ApiResponse = { + status: Status; + data: { + [SYMBOL: string]: Cryptocurrency[]; + }; +}; \ No newline at end of file diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts new file mode 100644 index 0000000..9654a7c --- /dev/null +++ b/packages/core/types/index.ts @@ -0,0 +1,69 @@ +export type CryptoDataResponse = { + status: { + timestamp: string; + error_code: number; + error_message: string | null; + elapsed: number; + credit_count: number; + notice: string | null; + }; + data: { + [key: string]: CryptoAsset[]; + }; +}; + +export type CryptoAsset = { + id: number; + name: string; + symbol: string; + slug: string; + num_market_pairs: number; + date_added: string; + tags: CryptoTag[]; + max_supply: number | null; + circulating_supply: number; + total_supply: number; + platform: CryptoPlatform | null; + is_active: number; + infinite_supply: boolean; + cmc_rank: number; + is_fiat: number; + self_reported_circulating_supply: number | null; + self_reported_market_cap: number | null; + tvl_ratio: number; + last_updated: string; + quote: { + [currency: string]: CryptoQuote; + }; +}; + +export type CryptoTag = { + slug: string; + name: string; + category: string; +}; + +export type CryptoPlatform = { + id: number; + name: string; + symbol: string; + slug: string; + token_address: string; +}; + +export type CryptoQuote = { + price: number; + volume_24h: number; + volume_change_24h: number; + percent_change_1h: number; + percent_change_24h: number; + percent_change_7d: number; + percent_change_30d: number; + percent_change_60d: number; + percent_change_90d: number; + market_cap: number; + market_cap_dominance: number; + fully_diluted_market_cap: number; + tvl: number; + last_updated: string; +}; \ No newline at end of file diff --git a/packages/genaiscript-rust-shim/.gitignore b/packages/genaiscript-rust-shim/.gitignore new file mode 100644 index 0000000..9b1ee42 --- /dev/null +++ b/packages/genaiscript-rust-shim/.gitignore @@ -0,0 +1,175 @@ +# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore + +# Logs + +logs +_.log +npm-debug.log_ +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Caches + +.cache + +# Diagnostic reports (https://nodejs.org/api/report.html) + +report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json + +# Runtime data + +pids +_.pid +_.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover + +lib-cov + +# Coverage directory used by tools like istanbul + +coverage +*.lcov + +# nyc test coverage + +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) + +.grunt + +# Bower dependency directory (https://bower.io/) + +bower_components + +# node-waf configuration + +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) + +build/Release + +# Dependency directories + +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) + +web_modules/ + +# TypeScript cache + +*.tsbuildinfo + +# Optional npm cache directory + +.npm + +# Optional eslint cache + +.eslintcache + +# Optional stylelint cache + +.stylelintcache + +# Microbundle cache + +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history + +.node_repl_history + +# Output of 'npm pack' + +*.tgz + +# Yarn Integrity file + +.yarn-integrity + +# dotenv environment variable files + +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) + +.parcel-cache + +# Next.js build output + +.next +out + +# Nuxt.js build / generate output + +.nuxt +dist + +# Gatsby files + +# Comment in the public line in if your project uses Gatsby and not Next.js + +# https://nextjs.org/blog/next-9-1#public-directory-support + +# public + +# vuepress build output + +.vuepress/dist + +# vuepress v2.x temp and cache directory + +.temp + +# Docusaurus cache and generated files + +.docusaurus + +# Serverless directories + +.serverless/ + +# FuseBox cache + +.fusebox/ + +# DynamoDB Local files + +.dynamodb/ + +# TernJS port file + +.tern-port + +# Stores VSCode versions used for testing VSCode extensions + +.vscode-test + +# yarn v2 + +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* + +# IntelliJ based IDEs +.idea + +# Finder (MacOS) folder config +.DS_Store diff --git a/packages/genaiscript-rust-shim/README.md b/packages/genaiscript-rust-shim/README.md new file mode 100644 index 0000000..7a20ecc --- /dev/null +++ b/packages/genaiscript-rust-shim/README.md @@ -0,0 +1,15 @@ +# genaiscript-rust-shim + +To install dependencies: + +```bash +bun install +``` + +To run: + +```bash +bun run index.ts +``` + +This project was created using `bun init` in bun v1.1.36. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime. diff --git a/packages/genaiscript-rust-shim/bun.lockb b/packages/genaiscript-rust-shim/bun.lockb new file mode 100755 index 0000000..9feb5b8 Binary files /dev/null and b/packages/genaiscript-rust-shim/bun.lockb differ diff --git a/packages/genaiscript-rust-shim/genaiscript-rust-shim.ts b/packages/genaiscript-rust-shim/genaiscript-rust-shim.ts new file mode 100644 index 0000000..4197a75 --- /dev/null +++ b/packages/genaiscript-rust-shim/genaiscript-rust-shim.ts @@ -0,0 +1,61 @@ +#!/usr/bin/env node +import minimist from "minimist"; +import { run } from "genaiscript/api"; +import { RunScriptOptions } from "./shim-types"; + +type Args = { + file: string; + vars: Record; + options: Partial & { + envVars?: Record; + signal?: AbortSignal; + }; +}; + +async function wrapper(args: Args) { + try { + await run(args.file, [], { vars: args.vars }, args.options); + } catch (error) { + console.error("Error executing script:", error); + process.exit(1); + } +} + +function parseCliArgs(): Args { + const argv = minimist(process.argv.slice(2), { + string: ["file"], + alias: { f: "file" }, + }); + + if (!argv.file) { + console.error("Error: Missing required argument --file"); + process.exit(1); + } + + const keyValuePairs = argv._; + + const vars: Record = keyValuePairs.reduce((acc, pair) => { + const [key, value] = pair.split("="); + if (key && value !== undefined) { + acc[key] = value; // Retain the `unknown` type for later flexibility + } else { + console.error(`Error: Invalid key=value pair "${pair}"`); + process.exit(1); + } + return acc; + }, {} as Record); + + return { + file: argv.file, + vars, + options: {}, + }; +} + +async function main() { + + const args = parseCliArgs(); + await wrapper(args); +} + +main(); diff --git a/packages/genaiscript-rust-shim/index.ts b/packages/genaiscript-rust-shim/index.ts new file mode 100644 index 0000000..598f124 --- /dev/null +++ b/packages/genaiscript-rust-shim/index.ts @@ -0,0 +1,2 @@ +import './genaiscript-rust-shim'; +export * from './genaiscript-rust-shim'; diff --git a/packages/genaiscript-rust-shim/package.json b/packages/genaiscript-rust-shim/package.json new file mode 100644 index 0000000..959e8b0 --- /dev/null +++ b/packages/genaiscript-rust-shim/package.json @@ -0,0 +1,19 @@ +{ + "name": "@web-agent-rs/genaiscript-rust-shim", + "module": "index.ts", + "private": true, + "type": "module", + "scripts": { + "buildShim": "esbuild genaiscript-rust-shim.ts --bundle --format=esm --packages=external --outdir=dist --platform=node && chmod +x dist/genaiscript-rust-shim.js", + "setupDev": "cp dist/genaiscript-rust-shim.js ../../dist/genaiscript-rust-shim.js" + }, + "devDependencies": { + "@types/bun": "latest", + "minimist": "^1.2.8", + "genaiscript": "^1.95.1", + "esbuild": "^0.24.2" + }, + "peerDependencies": { + "typescript": "^5.0.0" + } +} diff --git a/packages/genaiscript-rust-shim/shim-types.ts b/packages/genaiscript-rust-shim/shim-types.ts new file mode 100644 index 0000000..925bf94 --- /dev/null +++ b/packages/genaiscript-rust-shim/shim-types.ts @@ -0,0 +1,70 @@ +type FenceFormat = "markdown" | "xml" | "none" + +export interface WorkspaceFile { + /** + * Name of the file, relative to project root. + */ + filename: string + + /** + * Content mime-type if known + */ + type?: string + + /** + * Encoding of the content + */ + encoding?: "base64" + + /** + * Content of the file. + */ + content?: string +} + +export interface RunScriptOptions { + excludedFiles: string[] + excludeGitIgnore: boolean + runRetry: string + out: string + retry: string + retryDelay: string + maxDelay: string + json: boolean + yaml: boolean + outTrace: string + outOutput: string + outAnnotations: string + outChangelogs: string + pullRequest: string + pullRequestComment: string | boolean + pullRequestDescription: string | boolean + pullRequestReviews: boolean + outData: string + label: string + temperature: string | number + topP: string | number + seed: string | number + maxTokens: string | number + maxToolCalls: string | number + maxDataRepairs: string | number + model: string + smallModel: string + visionModel: string + embeddingsModel: string + modelAlias: string[] + provider: string + csvSeparator: string + cache: boolean | string + cacheName: string + applyEdits: boolean + failOnErrors: boolean + removeOut: boolean + vars: string[] | Record + fallbackTools: boolean + jsSource: string + logprobs: boolean + topLogprobs: number + fenceFormat: FenceFormat + workspaceFiles?: WorkspaceFile[] +} diff --git a/packages/genaiscript-rust-shim/tsconfig.json b/packages/genaiscript-rust-shim/tsconfig.json new file mode 100644 index 0000000..238655f --- /dev/null +++ b/packages/genaiscript-rust-shim/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + // Enable latest features + "lib": ["ESNext", "DOM"], + "target": "ESNext", + "module": "ESNext", + "moduleDetection": "force", + "jsx": "react-jsx", + "allowJs": true, + + // Bundler mode + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "noEmit": true, + + // Best practices + "strict": true, + "skipLibCheck": true, + "noFallthroughCasesInSwitch": true, + + // Some stricter flags (disabled by default) + "noUnusedLocals": false, + "noUnusedParameters": false, + "noPropertyAccessFromIndexSignature": false + } +} diff --git a/packages/genaiscript/genaisrc/.gitignore b/packages/genaiscript/genaisrc/.gitignore new file mode 100644 index 0000000..6641d96 --- /dev/null +++ b/packages/genaiscript/genaisrc/.gitignore @@ -0,0 +1,4 @@ +# auto-generated +genaiscript.d.ts +tsconfig.json +jsconfig.json \ No newline at end of file diff --git a/packages/genaiscript/genaisrc/_state/index.ts b/packages/genaiscript/genaisrc/_state/index.ts new file mode 100644 index 0000000..ecee7e2 --- /dev/null +++ b/packages/genaiscript/genaisrc/_state/index.ts @@ -0,0 +1,21 @@ +import {types} from "mobx-state-tree"; +import {QuoteStore} from "@web-agent-rs/core/quotes/models"; +import {NewsStore} from "@web-agent-rs/core/news"; + +import newsStore from "./news"; +import quoteStore from "./quotes"; + + +const StateModel = types.model("State", { + symbols: types.array(types.string), + quotes: QuoteStore, + news: NewsStore, +}); + + +const state = StateModel.create({ + quotes: quoteStore, + news: newsStore, +}); + +export default state; \ No newline at end of file diff --git a/packages/genaiscript/genaisrc/_state/news.ts b/packages/genaiscript/genaisrc/_state/news.ts new file mode 100644 index 0000000..2cdcb2a --- /dev/null +++ b/packages/genaiscript/genaisrc/_state/news.ts @@ -0,0 +1,11 @@ +import {NewsStore} from "@web-agent-rs/core/news"; +import {Instance} from "mobx-state-tree"; + +const newsStore = NewsStore.create({ + isLoading: false, + apiKey: process.env.PERIGON_API_KEY +}); + +export type NewsStore = Instance; + +export default newsStore; \ No newline at end of file diff --git a/packages/genaiscript/genaisrc/_state/quotes.ts b/packages/genaiscript/genaisrc/_state/quotes.ts new file mode 100644 index 0000000..1d7419f --- /dev/null +++ b/packages/genaiscript/genaisrc/_state/quotes.ts @@ -0,0 +1,7 @@ +import {QuoteStore} from "@web-agent-rs/core/quotes/models"; + +const quoteStore = QuoteStore.create({ + apiKey: process.env.CCC_API_KEY +}); + +export default quoteStore; \ No newline at end of file diff --git a/packages/genaiscript/genaisrc/agent.genai.mts b/packages/genaiscript/genaisrc/agent.genai.mts new file mode 100644 index 0000000..d630930 --- /dev/null +++ b/packages/genaiscript/genaisrc/agent.genai.mts @@ -0,0 +1,24 @@ +import {PerigonClient as NewsSearchTool} from "@agentic/perigon"; + +script({ + system: ["system.tools"], + tools: "agent", + maxTokens: 8192 +}) + +const newSearchTool = new NewsSearchTool(); + +defTool(newSearchTool) + +$`You are a chat assistant that uses agent tools to solve problems. + +while true: + - ask the user for a question using the agent_user_input + - make a plan to answer the question step by step + - answer the question +end while + +## guidance: + - use the agent tools to help you + - do NOT try to ask the user questions directly, use the agent_user_input tool instead. +` \ No newline at end of file diff --git a/packages/genaiscript/genaisrc/deep-research.genai.mts b/packages/genaiscript/genaisrc/deep-research.genai.mts new file mode 100644 index 0000000..1a15d84 --- /dev/null +++ b/packages/genaiscript/genaisrc/deep-research.genai.mts @@ -0,0 +1,281 @@ +import {task, entrypoint, interrupt, MemorySaver} from "@langchain/langgraph" +import "./tools/searxng.genai.mjs" +import {SearxngClient} from "@agentic/searxng"; + + +script({ + title: "Deep Research Program", + description: "Researchers can use this program to conduct deep research on a topic", + model: "large", + cache: "ephemeral", +}) +const {output, vars} = env + + +const breakdownResearch = task( + "breakdown_research", + async (question: string) => { + const result = await runPrompt( + async (ctx) => { + ctx.$`You are an expert research strategist. + +Task: Break down the following research question into 3-5 focused sub-questions that would help comprehensively answer the main question. + +Research question: ${question} + +For each sub-question: +1. Assign a unique ID (e.g., SQ1, SQ2) +2. Explain the rationale for why this sub-question is important +3. Ensure the sub-questions collectively cover the main research question + +Output the breakdown as a JSON object.` + }, + { + label: "breakdown research", + responseSchema: { + type: "object", + properties: { + mainQuestion: {type: "string"}, + subQuestions: { + type: "array", + items: { + type: "object", + properties: { + id: {type: "string"}, + question: {type: "string"}, + rationale: {type: "string"}, + }, + }, + }, + }, + }, + } + ) + + return result.json + } +) + +const globalCtx = this; + + +const researchSubQuestion = task( + "research_subquestion", + async (subQuestion: { id: string; question: string }) => { + + const searxng = new SearxngClient({apiBaseUrl: "https://search-engine-gsio.fly.dev"}); + + const {text} = await runPrompt( + (_) => { + _.defTool(searxng) + _.$`You are an expert researcher with access to comprehensive information. + +Task: Thoroughly research the following question and provide a detailed answer. + +Question ID: ${subQuestion.id} +Question: ${subQuestion.question} + +Provide your findings in a structured format that includes: +- Your answer to the sub-question +- Relevant sources that support your answer +- Your confidence level in the answer (0-1)` + }, + { + model: "small", + label: `research subquestion ${subQuestion.id}`, + maxDataRepairs: 2, + responseSchema: { + type: "object", + properties: { + subQuestionId: {type: "string"}, + answer: {type: "string"}, + sources: { + type: "array", + items: { + type: "object", + properties: { + title: {type: "string"}, + url: {type: "string"}, + relevance: {type: "string"}, + }, + }, + }, + confidence: {type: "number"}, + }, + }, + } + ) + return text + } +) + + +const synthesizeFindings = task( + "synthesize_findings", + async (mainQuestion: string, findings: any[]) => { + const result = await runPrompt( + async (ctx) => { + ctx.$`You are an expert research synthesizer. + +Task: Synthesize the following research findings into a coherent response to the main research question. + +Main Research Question: ${mainQuestion} + +Findings: +${JSON.stringify(findings, null, 2)} + +Provide a synthesis that: +1. Directly answers the main research question +2. Integrates the findings from all sub-questions +3. Identifies limitations in the current research +4. Suggests next steps for further investigation` + }, + { + label: "synthesize findings", + responseType: "markdown", + responseSchema: { + type: "object", + properties: { + summary: {type: "string"}, + findings: {type: "array", items: {type: "string"}}, + limitations: { + type: "array", + items: {type: "string"}, + }, + nextSteps: {type: "array", items: {type: "string"}}, + }, + }, + } + ) + + return result.json + } +) + + +const summarizeAndIdentifyGaps = task( + "summarize_and_identify_gaps", + async (synthesis: any, findings: any[]) => { + const result = await runPrompt( + async (ctx) => { + ctx.$`You are an expert research evaluator. + +Task: Review the research synthesis and identify any gaps or areas that need deeper investigation. + +Current synthesis: +${JSON.stringify(synthesis, null, 2)} + +Research findings: +${JSON.stringify(findings, null, 2)} + +Please provide: +1. A concise summary of current findings +2. Identify 2-3 specific knowledge gaps +3. Formulate follow-up questions to address these gaps` + }, + { + label: "identify research gaps", + responseSchema: { + type: "object", + properties: { + summary: {type: "string"}, + gaps: { + type: "array", + items: {type: "string"}, + }, + followUpQuestions: { + type: "array", + items: { + type: "object", + properties: { + id: {type: "string"}, + question: {type: "string"}, + }, + }, + }, + }, + }, + } + ) + return result.json + } +) + + +const researchWorkflow = entrypoint( + {checkpointer: new MemorySaver(), name: "research_workflow"}, + async (input: { question: string; context?: string }) => { + + const breakdown = await breakdownResearch(input.question) + + + const subQuestionFindings = [] + + for (const sq of breakdown.subQuestions) { + const analysis = await researchSubQuestion(sq); + console.log(analysis); + subQuestionFindings.push(analysis); + } + + + let synthesis = await synthesizeFindings( + input.question, + subQuestionFindings + ) + + const gapAnalysis = await summarizeAndIdentifyGaps( + synthesis, + subQuestionFindings + ) + + + const followUpFindings = []; + for (const fq of gapAnalysis.followUpQuestions) { + const anwser = await researchSubQuestion(fq); + console.log(anwser); + followUpFindings.push(anwser); + } + + + const allFindings = [...subQuestionFindings, ...followUpFindings] + const finalSynthesis = await synthesizeFindings( + input.question, + allFindings + ) + + + return { + question: input.question, + breakdown: breakdown, + initialFindings: subQuestionFindings, + gapAnalysis: gapAnalysis, + followUpFindings: followUpFindings, + synthesis: finalSynthesis, + } + } +) + + +const researchQuestion = + env.vars.question || + "What are the most promising approaches to climate change mitigation?" + + +const threadId = `research-${Date.now()}` + + +const config = { + configurable: { + thread_id: threadId, + }, +} + + +const results = await researchWorkflow.invoke( + { + question: researchQuestion, + context: vars.context || "", + }, + config +) +output.fence(results, "json") \ No newline at end of file diff --git a/packages/genaiscript/genaisrc/finance-query.genai.mts b/packages/genaiscript/genaisrc/finance-query.genai.mts new file mode 100644 index 0000000..40a0583 --- /dev/null +++ b/packages/genaiscript/genaisrc/finance-query.genai.mts @@ -0,0 +1,80 @@ +import state from "./_state/index.js"; +import {getSnapshot} from "mobx-state-tree"; +import {collect_gainers_losers} from "@web-agent-rs/core/market"; + +def("QUERY", env.vars.user_input); + + +defTool( + "get_quote", + "Fetch quote for symbol", + { + "symbol": { + type: "string", + default: "BTC" + } + }, + async (args) => { + const { symbol } = args; + await state.quotes.fetchQuote(symbol); + + + const quote = await state.quotes.getQuote(symbol); + + return JSON.stringify(quote) + } +); + +defTool( + "get_news", + "Fetches news for symbol", + { + "symbol": { + type: "string", + default: "BTC" + } + }, + async (args) => { + const { symbol } = args; + await state.news.fetchNewsForSymbol(symbol, 5, "date"); + + const news = await state.news.getNewsForSymbol(symbol).map(i => getSnapshot(i)); + + return news + } +); + + +defTool( + "get_market", + "Fetches trending symbols of market", + { + "limit": { + type: "number", + default: "25" + } + }, + async (args) => { + + const { limit } = args; + + + const marketOverviewRequest = await collect_gainers_losers({apiKey: process.env.CCC_API_KEY, limit: parseInt(limit) }) + + return marketOverviewRequest.data.map(item => ({ + symbol: item.symbol, + name: item.name, + + + change_1h: item.quote.USD.percent_change_1h, + price: item.quote.USD.price, + volume_24h: item.quote.USD.volume_24h + })) + } +); + + + +$`You are a market data assistant specializing in financial analysis. Respond to QUERIES with accurate, clear, and concise information relevant to professionals in the finance sector. Use available tools efficiently to gather and present quantitative data.`; + + diff --git a/packages/genaiscript/genaisrc/image-generator.genai.mts b/packages/genaiscript/genaisrc/image-generator.genai.mts new file mode 100644 index 0000000..a9e1724 --- /dev/null +++ b/packages/genaiscript/genaisrc/image-generator.genai.mts @@ -0,0 +1,11 @@ +console.log("Generating image") + +def("USER_INPUT", env.vars.user_input); + + +const inputs = { + host: JSON.parse(env.vars.user_input).host, + imageId: JSON.parse(env.vars.user_input).imageId +} + +console.log(`![Generated Image](/generated/image/${inputs.imageId})`); diff --git a/packages/genaiscript/genaisrc/incubator/firecrawl.genai.mts b/packages/genaiscript/genaisrc/incubator/firecrawl.genai.mts new file mode 100644 index 0000000..6bb9ea5 --- /dev/null +++ b/packages/genaiscript/genaisrc/incubator/firecrawl.genai.mts @@ -0,0 +1,26 @@ +script({ + title: "Stock Market News Scraper", + tools: ["searxng"], +}) + +defTool({ + "mcp-server-firecrawl": { + command: "npx", + args: ["-y", "firecrawl-mcp"], + }, +}) + +def("QUERY_NEWS", "Latest news on AAPL") +def("QUERY_SENTIMENT", "Market sentiment for technology sector") + + +$`Search the query with searxng: QUERY_NEWS` + + +$`Scrape the top search result with firecrawl` + + +$`Search the query with searxng: QUERY_SENTIMENT` + + +$`Scrape the top search result with firecrawl` \ No newline at end of file diff --git a/packages/genaiscript/genaisrc/news-search.genai.mts b/packages/genaiscript/genaisrc/news-search.genai.mts new file mode 100644 index 0000000..4ab41be --- /dev/null +++ b/packages/genaiscript/genaisrc/news-search.genai.mts @@ -0,0 +1,24 @@ +import {SearxngClient} from "@agentic/searxng"; +import "./tools/searxng.genai.mjs" + +script({ + title: "news_search_agent", + tools: ["searxng"], + maxToolCalls: 2, + cache: false, +}); + +def("USER_INPUT", env.vars.user_input); +def("TODAY", new Date().toISOString().split("T")[0]); +def("LINK_FORMAT", "[Link](url)"); + + +$`You are an assistant searching for news using complex queries to pinpoint results. + + +- tailor search to answer the question in USER_INPUT +- perform 2 searches in parallel sorted by relevance and date respectively +- create a markdown table of <=5 results of both searches +- header row: Date, Title, Summary, and Link + +Respond with a single table, no extra text.` diff --git a/packages/genaiscript/genaisrc/tools/searxng.genai.mts b/packages/genaiscript/genaisrc/tools/searxng.genai.mts new file mode 100644 index 0000000..5d400ed --- /dev/null +++ b/packages/genaiscript/genaisrc/tools/searxng.genai.mts @@ -0,0 +1,18 @@ +script({ + isSystem: true +}) + +import {SearxngClient} from "@agentic/searxng"; +import ky from 'ky'; + +const kyWithHeaders = ky.create({ + referrerPolicy: "unsafe-url", + + headers: { + 'Authorization': 'Basic ' + btoa(`admin:${process.env.SEARXNG_PASSWORD}`), + } +}); + +const searxng = new SearxngClient({ky: kyWithHeaders}); + +defTool(searxng) \ No newline at end of file diff --git a/packages/genaiscript/genaisrc/web-scrape.genai.mts b/packages/genaiscript/genaisrc/web-scrape.genai.mts new file mode 100644 index 0000000..726c801 --- /dev/null +++ b/packages/genaiscript/genaisrc/web-scrape.genai.mts @@ -0,0 +1,88 @@ +import {Window} from 'happy-dom'; +import {platform} from 'os'; + +script({ + title: "scrape", + cache: false, +}); + +/* + "url": "Full URL in the conversation that references the URL being interacted with. No trailing slash!", + "query": "Implied question about the resources at the URL.", + "action": "read | scrape | crawl" +*/ + +try { + const {url, query, action} = JSON.parse(env.vars.user_input); +} catch (e) { + throw "Sorry! Something went wrong."; +} + +const {url, query, action} = JSON.parse(env.vars.user_input); + +def("URL", url); + +def("QUERY", query); + +def("ACTION", action); + +// console.log({url, query, action}); + +if(!(new URL(url) ?? undefined)) { + throw "Bad URL. Maybe try again?" +} + +function getBrowser(): "webkit" | "chromium" | "firefox" { + if (platform() === 'darwin') { + return "webkit"; // macOS is identified by 'darwin' + } + return "chromium"; // default to chromium for other platforms +} + +const {text} = await host.fetchText(new URL(url).toString()); + +// const browser = getBrowser(); + +// const page = await host.browse(new URL(url).toString(), { +// browser: getBrowser(), +// headless: true, +// javaScriptEnabled: browser !== "chromium", +// // timeout: 3000, +// // bypassCSP: true, +// // baseUrl: new URL(url).origin, +// }); +// +// const html = (await page.content()); +// const title = (await page.title()); + +// console.log({html}); + +const window = new Window({ + // url: "http://localhost:8080", + height: 1920, + width: 1080, + settings: { + navigator: { + userAgent: 'Mozilla/5.0 (compatible; GeoffsAI/1.0; +https://geoff.seemueller.io)', + }, + } +}); + +window.document.body.innerHTML = text; + +const textContent = window.document.body.textContent; + +def("PAGE_TEXT", textContent); + +$`You a helpful assistant interacting with resources found at the URL. + +- markdown table is concise representation of PAGE_TEXT relevant to the QUERY + +### Respond Example: +### Data from ${url}: +| Header 1 | Header 2 | Header 3 | +|----------|----------|----------| +| Data 1 | Data 2 | Data 3 | +\n---[Example explanation of data significance to query.] +--- +Respond with the markdown table and an explanation of significance. Do not include extra text.`; diff --git a/packages/genaiscript/genaisrc/web-search.genai.mts b/packages/genaiscript/genaisrc/web-search.genai.mts new file mode 100644 index 0000000..d68a6e6 --- /dev/null +++ b/packages/genaiscript/genaisrc/web-search.genai.mts @@ -0,0 +1,28 @@ +import {SearxngClient} from "@agentic/searxng"; +import "./tools/searxng.genai.mjs" + + +script({ + title: "web_search_agent", + maxTokens: 8192, + cache: false, + tools: ["searxng"], +}); + + + +def("USER_INPUT", env.vars.user_input); + + + +def("LINK_FORMAT", "[Link](url)"); + +$`You are an assistant searching for web content using complex queries to pinpoint results. + + +- tailor search to answer the question in USER_INPUT +- perform 2 searches in parallel sorted by relevance and date respectively +- create a markdown table of <=5 results of both searches +- header row: Title, Description, and Link + +Respond with a single table, no extra text.` diff --git a/packages/genaiscript/package.json b/packages/genaiscript/package.json new file mode 100644 index 0000000..08a85d5 --- /dev/null +++ b/packages/genaiscript/package.json @@ -0,0 +1,28 @@ +{ + "name": "@web-agent-rs/genaiscript", + "type": "module", + "workspaces": ["packages/*"], + "private": true, + "scripts": { + "dev": "cargo watch -x 'run src/main.rs'", + "ai:search": "genaiscript run genaisrc/web-search.genai.mts --vars USER_INPUT='who won the 2024 election?'", + "shim:ai:search": "pnpm build && ./dist/shim.js --file=genaisrc/search.genai.mts USER_INPUT=\"Who won the 2024 presidential election?\"\n", + "ai:news": "genaiscript run genaisrc/news-search.genai.mts --vars USER_INPUT='What are the latest updates and developments in the Ukraine war?'", + "ai:url:read": "genaiscript run genaisrc/web-scrape.genai.mts --vars USER_INPUT='{\"url\":\"https://geoff.seemueller.io/about\",\"query\":\"Describe the details of the page.\", \"action\": \"read\"}'", + "ai:url:scrape": "npx genaiscript run genaisrc/web-scrape.genai.mts --vars USER_INPUT='{\"url\":\"https://www.time4learning.com/homeschool-curriculum/high-school/eleventh-grade/math.html\",\"query\":\"What is on this page?\", \"action\": \"scrape\"}'", + "crypto:quote": "npx genaiscript run genaisrc/finance-query.genai.mts --vars USER_INPUT='Get a quote for BTC'", + "crypto:news": "npx genaiscript run genaisrc/finance-query.genai.mts --vars USER_INPUT='What is the news for Bitcoin?'", + "crypto:overview": "npx genaiscript run genaisrc/finance-query.genai.mts --vars USER_INPUT='What are the trending symbols in the market?'" + }, + "dependencies": { + "@agentic/perigon": "^7.2.0", + "@agentic/searxng": "7.5.3", + "@kevinwatt/mcp-server-searxng": "^0.3.9", + "@types/node": "^22.10.2", + "genaiscript": "^1.95.1", + "happy-dom": "^16.0.1", + "@web-agent-rs/perigon": "workspace:*", + "@web-agent-rs/core": "workspace:*", + "ky": "^1.8.0" + } +} diff --git a/packages/perigon/index.ts b/packages/perigon/index.ts new file mode 100644 index 0000000..2bf58b1 --- /dev/null +++ b/packages/perigon/index.ts @@ -0,0 +1,106 @@ +import type * as types from './types'; +import type { ConfigOptions, FetchResponse } from 'api/dist/core' +import Oas from 'oas'; +import APICore from 'api/dist/core'; +import definition from './openapi.json'; + +class SDK { + spec: Oas; + core: APICore; + + constructor() { + this.spec = Oas.init(definition); + this.core = new APICore(this.spec, 'perigon/unknown (api/6.1.3)'); + } + + /** + * Optionally configure various options that the SDK allows. + * + * @param config Object of supported SDK options and toggles. + * @param config.timeout Override the default `fetch` request timeout of 30 seconds. This number + * should be represented in milliseconds. + */ + config(config: ConfigOptions) { + this.core.setConfig(config); + } + + /** + * If the API you're using requires authentication you can supply the required credentials + * through this method and the library will magically determine how they should be used + * within your API request. + * + * With the exception of OpenID and MutualTLS, it supports all forms of authentication + * supported by the OpenAPI specification. + * + * @example HTTP Basic auth + * sdk.auth('username', 'password'); + * + * @example Bearer tokens (HTTP or OAuth 2) + * sdk.auth('myBearerToken'); + * + * @example API Keys + * sdk.auth('myApiKey'); + * + * @see {@link https://spec.openapis.org/oas/v3.0.3#fixed-fields-22} + * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-22} + * @param values Your auth credentials for the API; can specify up to two strings or numbers. + */ + auth(...values: string[] | number[]) { + this.core.setAuth(...values); + return this; + } + + /** + * If the API you're using offers alternate server URLs, and server variables, you can tell + * the SDK which one to use with this method. To use it you can supply either one of the + * server URLs that are contained within the OpenAPI definition (along with any server + * variables), or you can pass it a fully qualified URL to use (that may or may not exist + * within the OpenAPI definition). + * + * @example Server URL with server variables + * sdk.server('https://{region}.api.example.com/{basePath}', { + * name: 'eu', + * basePath: 'v14', + * }); + * + * @example Fully qualified server URL + * sdk.server('https://eu.api.example.com/v14'); + * + * @param url Server URL + * @param variables An object of variables to replace into the server URL. + */ + server(url: string, variables = {}) { + this.core.setServer(url, variables); + } + + /** + * Search and filter all news articles available via the Perigon API. The result includes a + * list of individual articles that were matched to your specific criteria. + * + * @summary All Articles + * @throws FetchError<400, types.AllNewsResponse400> 400 + * @throws FetchError<401, types.AllNewsResponse401> 401 + * @throws FetchError<403, types.AllNewsResponse403> 403 + * @throws FetchError<404, types.AllNewsResponse404> 404 + * @throws FetchError<500, types.AllNewsResponse500> 500 + */ + allNews(metadata: types.AllNewsMetadataParam): Promise> { + return this.core.fetch('/v1/all', 'get', metadata); + } + + /** + * Stories + * + * @throws FetchError<400, types.Stories1Response400> 400 + */ + stories1(metadata: types.Stories1MetadataParam): Promise> { + return this.core.fetch('/v1/stories/all', 'get', metadata); + } +} + +const createSDK = (() => { return new SDK(); })() +; + +export default createSDK; + +export type { AllNewsMetadataParam, AllNewsResponse200, AllNewsResponse400, AllNewsResponse401, AllNewsResponse403, AllNewsResponse404, AllNewsResponse500, Stories1MetadataParam, Stories1Response200, Stories1Response400 } from './types'; diff --git a/packages/perigon/openapi.json b/packages/perigon/openapi.json new file mode 100644 index 0000000..1e9ab15 --- /dev/null +++ b/packages/perigon/openapi.json @@ -0,0 +1,1629 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "News & Stories", + "version": "unknown" + }, + "servers": [ + { + "url": "https://api.goperigon.com" + } + ], + "components": { + "securitySchemes": { + "sec0": { + "type": "apiKey", + "in": "query", + "name": "apiKey", + "x-default": "" + } + } + }, + "security": [ + { + "sec0": [] + } + ], + "paths": { + "/v1/all": { + "get": { + "summary": "All Articles", + "description": "Search and filter all news articles available via the Perigon API. The result includes a list of individual articles that were matched to your specific criteria.", + "operationId": "all-news", + "parameters": [ + { + "name": "apiKey", + "in": "query", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "q", + "in": "query", + "description": "Search query, each article will be scored and ranked against it. Articles are searched on the title, description, and content fields. More ➜", + "schema": { + "type": "string", + "default": "recall OR \"safety concern*\"" + } + }, + { + "name": "title", + "in": "query", + "description": "Search article headlines/title field. Semantic similar to q parameter.", + "schema": { + "type": "string", + "default": "tesla OR TSLA OR \"General Motors\" OR GM" + } + }, + { + "name": "desc", + "in": "query", + "description": "Search query on the description field. Semantic similar to q parameter.", + "schema": { + "type": "string" + } + }, + { + "name": "content", + "in": "query", + "description": "Search query on the article's body of content field. Semantic similar to q parameter.", + "schema": { + "type": "string" + } + }, + { + "name": "url", + "in": "query", + "description": "Search query on the url field. Semantic similar to q parameter. E.g. could be used for querying certain website sections, e.g. source=cnn.com&url=travel.", + "schema": { + "type": "string" + } + }, + { + "name": "articleId", + "in": "query", + "description": "Article ID will search for a news article by the ID of the article. If several parameters are passed, all matched articles will be returned.", + "schema": { + "type": "string" + } + }, + { + "name": "clusterId", + "in": "query", + "description": "Search for related content using a cluster ID. Passing a cluster ID will filter results to only the content found within the cluster.", + "schema": { + "type": "string" + } + }, + { + "name": "from", + "in": "query", + "description": "'from' filter, will search articles published after the specified date, the date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2023-03-01T00:00:00", + "schema": { + "type": "string", + "format": "date-time" + } + }, + { + "name": "to", + "in": "query", + "description": "'to' filter, will search articles published before the specified date, the date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2022-02-01T23:59:59", + "schema": { + "type": "string", + "format": "date-time" + } + }, + { + "name": "addDateFrom", + "in": "query", + "description": "'addDateFrom' filter, will search articles added after the specified date, the date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2022-02-01T00:00:00", + "schema": { + "type": "string", + "format": "date-time" + } + }, + { + "name": "addDateTo", + "in": "query", + "description": "'addDateTo' filter, will search articles added before the specified date, the date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2022-02-01T23:59:59", + "schema": { + "type": "string", + "format": "date-time" + } + }, + { + "name": "refreshDateFrom", + "in": "query", + "description": "Will search articles that were refreshed after the specified date. The date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2022-02-01T00:00:00", + "schema": { + "type": "string", + "format": "date-time" + } + }, + { + "name": "refreshDateTo", + "in": "query", + "description": "Will search articles that were refreshed before the specified date. The date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2022-02-01T23:59:59", + "schema": { + "type": "string", + "format": "date-time" + } + }, + { + "name": "medium", + "in": "query", + "description": "Medium will filter out news articles medium, which could be 'Video' or 'Article'. If several parameters are passed, all matched articles will be returned.", + "schema": { + "type": "string", + "enum": [ + "Article", + "Video" + ] + } + }, + { + "name": "source", + "in": "query", + "description": "Publisher's domain can include a subdomain. If multiple parameters are passed, they will be applied as OR operations. Wildcards (\\* and ?) are suported (e.g. \\*.cnn.com). More ➜", + "schema": { + "type": "string" + } + }, + { + "name": "sourceGroup", + "in": "query", + "description": "One of the supported source groups. Find Source Groups in the guided part of our documentation... More ➜", + "schema": { + "type": "string", + "enum": [ + "top10", + "top100", + "top25crypto", + "top25finance", + "top50tech", + "top100sports", + "top100leftUS", + "top100rightUS", + "top100centerUS" + ] + } + }, + { + "name": "excludeSource", + "in": "query", + "description": "The domain of the website, which should be excluded from the search. Multiple parameters could be provided. Wildcards (\\* and ?) are suported (e.g. \\*.cnn.com).", + "schema": { + "type": "string" + } + }, + { + "name": "paywall", + "in": "query", + "description": "Filter to show only results where the source has a paywall (true) or does not have a paywall (false).", + "schema": { + "type": "boolean" + } + }, + { + "name": "byline", + "in": "query", + "description": "Author names to filter by. Article author bylines are used as a source field. If multiple parameters are passed, they will be applied as OR operations.", + "schema": { + "type": "string" + } + }, + { + "name": "journalistId", + "in": "query", + "description": "Filter by journalist ID. Journalist IDs are unique journalist identifiers which can be found through the Journalist API, or in the matchedAuthors field. More ➜", + "schema": { + "type": "string" + } + }, + { + "name": "language", + "in": "query", + "description": "Language code to filter by language. If multiple parameters are passed, they will be applied as OR operations. More ➜", + "schema": { + "type": "string", + "enum": [ + "da", + "de", + "en", + "es", + "fi", + "fr", + "hu", + "it", + "nl", + "no", + "pl", + "pt", + "ru", + "sv", + "uk" + ] + } + }, + { + "name": "searchTranslation", + "in": "query", + "description": "Expand a query to search the translation, translatedTitle, and translatedDescription fields for non-English articles.", + "schema": { + "type": "boolean", + "default": false + } + }, + { + "name": "label", + "in": "query", + "description": "Labels to filter by, could be 'Opinion', 'Paid-news', 'Non-news', etc. If multiple parameters are passed, they will be applied as OR operations. More ➜", + "schema": { + "type": "string", + "enum": [ + "Opinion", + "Non-news", + "Paid News", + "Fact Check", + "Pop Culture", + "Roundup", + "Press Release", + "Low Content" + ] + } + }, + { + "name": "excludeLabel", + "in": "query", + "description": "Exclude results that include specific labels (Opinion, Non-news, Paid News, etc.). You can filter multiple by repeating the parameter.", + "schema": { + "type": "string", + "enum": [ + "Opinion", + "Non-news", + "Paid News", + "Fact Check", + "Pop Culture", + "Roundup", + "Press Release", + "Low Content" + ] + } + }, + { + "name": "category", + "in": "query", + "description": "Filter by categories. Categories are general themes that the article is about. Examples of categories: Tech, Politics, etc. If multiple parameters are passed, they will be applied as OR operations. Use 'none' to search uncategorized articles. More ➜", + "schema": { + "type": "string", + "enum": [ + "Politics", + "Tech", + "Sports", + "Business", + "Finance", + "Entertainment", + "Health", + "Weather", + "Lifestyle", + "Auto", + "Science", + "Travel", + "Environment", + "World", + "General", + "none" + ] + } + }, + { + "name": "topic", + "in": "query", + "description": "Filter by topics. Each topic is some kind of entity that the article is about. Examples of topics: Markets, Joe Biden, Green Energy, Climate Change, Cryptocurrency, etc. If multiple parameters are passed, they will be applied as OR operations. More ➜", + "schema": { + "type": "string" + } + }, + { + "name": "excludeTopic", + "in": "query", + "description": "Filter by excluding topics. Each topic is some kind of entity that the article is about. Examples of topics: Markets, Joe Biden, Green Energy, Climate Change, Cryptocurrency, etc. If multiple parameters are passed, they will be applied as OR operations. More ➜", + "schema": { + "type": "string" + } + }, + { + "name": "linkTo", + "in": "query", + "description": "Returns only articles that point to specified links (as determined by the 'links' field in the article response).", + "schema": { + "type": "string" + } + }, + { + "name": "showReprints", + "in": "query", + "description": "Whether to return reprints in the response or not. Reprints are usually wired articles from sources like AP or Reuters that are reprinted in multiple sources at the same time. By default, this parameter is 'true'.", + "schema": { + "type": "boolean", + "default": true + } + }, + { + "name": "reprintGroupId", + "in": "query", + "description": "Shows all articles belonging to the same reprint group. A reprint group includes one original article (the first one processed by the API) and all its known reprints.", + "schema": { + "type": "string" + } + }, + { + "name": "city", + "in": "query", + "description": "Filters articles where a specified city plays a central role in the content, beyond mere mentions, to ensure the results are deeply relevant to the urban area in question. If multiple parameters are passed, they will be applied as OR operations.", + "schema": { + "type": "string" + } + }, + { + "name": "area", + "in": "query", + "description": "Filters articles where a specified area, such as a neighborhood, borough, or district, plays a central role in the content, beyond mere mentions, to ensure the results are deeply relevant to the area in question. If multiple parameters are passed, they will be applied as OR operations.", + "schema": { + "type": "string" + } + }, + { + "name": "state", + "in": "query", + "description": "Filters articles where a specified state plays a central role in the content, beyond mere mentions, to ensure the results are deeply relevant to the state in question. If multiple parameters are passed, they will be applied as OR operations.", + "schema": { + "type": "string" + } + }, + { + "name": "locationsCountry", + "in": "query", + "description": "Filters articles where a specified country plays a central role in the content, beyond mere mentions, to ensure the results are deeply relevant to the country in question. If multiple parameters are passed, they will be applied as OR operations.", + "schema": { + "type": "string" + } + }, + { + "name": "excludeLocationsCountry", + "in": "query", + "description": "Excludes articles where a specified country plays a central role in the content, ensuring results are not deeply relevant to the country in question. If multiple parameters are passed, they will be applied as AND operations, excluding articles relevant to any of the specified countries.", + "schema": { + "type": "string" + } + }, + { + "name": "location", + "in": "query", + "description": "Return all articles that have the specified location. Location attributes are delimited by ':' between key and value, and '::' between attributes. Example: 'city:New York::state:NY'.", + "schema": { + "type": "string" + } + }, + { + "name": "lat", + "in": "query", + "description": "Latitude of the center point to search places", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "lon", + "in": "query", + "description": "Longitude of the center point to search places", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "maxDistance", + "in": "query", + "description": "Maximum distance (in km) from starting point to search articles by tagged places", + "schema": { + "type": "integer", + "format": "int32" + } + }, + { + "name": "sourceCity", + "in": "query", + "description": "Find articles published by sources that are located within a given city.", + "schema": { + "type": "string" + } + }, + { + "name": "sourceCounty", + "in": "query", + "description": "Find articles published by sources that are located within a given county.", + "schema": { + "type": "string" + } + }, + { + "name": "sourceCountry", + "in": "query", + "description": "Find articles published by sources that are located within a given country. Must be 2 character country code (i.e. us, gb, etc).", + "schema": { + "type": "string" + } + }, + { + "name": "country", + "in": "query", + "description": "Country code to filter by country. If multiple parameters are passed, they will be applied as OR operations.", + "schema": { + "type": "string", + "enum": [ + "us", + "gb", + "de", + "it", + "fr", + "nl", + "se", + "dk", + "fi", + "hu", + "no", + "pl", + "pt", + "ru", + "ua", + "ch", + "br", + "nz", + "mx", + "au" + ] + } + }, + { + "name": "sourceState", + "in": "query", + "description": "Find articles published by sources that are located within a given state.", + "schema": { + "type": "string" + } + }, + { + "name": "sourceLon", + "in": "query", + "description": "Latitude of the center point to search articles created by local publications.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "sourceLat", + "in": "query", + "description": "Latitude of the center point to search articles created by local publications.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "sourceMaxDistance", + "in": "query", + "description": "Maximum distance from starting point to search articles created by local publications.", + "schema": { + "type": "integer", + "format": "int32" + } + }, + { + "name": "personWikidataId", + "in": "query", + "description": "List of person Wikidata IDs for filtering.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "personName", + "in": "query", + "description": "List of person names for exact matches. Boolean and complex logic is not supported on this paramter.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "companyId", + "in": "query", + "description": "List of company IDs to filter by.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "companyName", + "in": "query", + "description": "Search by company name.", + "schema": { + "type": "string" + } + }, + { + "name": "companyDomain", + "in": "query", + "description": "Search by company domains for filtering. E.g. companyDomain=apple.com.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "companySymbol", + "in": "query", + "description": "Search by company symbols.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "page", + "in": "query", + "description": "Zero-based page number. From 0 to 10000. See the Pagination section for limitations.", + "schema": { + "type": "integer", + "format": "int32" + } + }, + { + "name": "size", + "in": "query", + "description": "Number of articles returned per page, from 0 to 100.", + "schema": { + "type": "integer", + "format": "int32" + } + }, + { + "name": "sortBy", + "in": "query", + "description": "'relevance' to sort by relevance to the query, 'date' to sort by the publication date (desc), 'pubDate' is a synonym to 'date', 'addDate' to sort by 'addDate' field (desc), 'refreshDate' to sort by 'refreshDate' field (desc).", + "schema": { + "type": "string", + "enum": [ + "date", + "relevance", + "addDate", + "pubDate", + "refreshDate" + ], + "default": "relevance" + } + }, + { + "name": "showNumResults", + "in": "query", + "description": "Whether to show the total number of all matched articles. Default value is false which makes queries a bit more efficient but also counts up to 10000 articles.", + "schema": { + "type": "boolean" + } + }, + { + "name": "positiveSentimentFrom", + "in": "query", + "description": "Filters results with a sentiment score greater than or equal to the specified value, indicating positive sentiment. See the Article Data section in Docs for an explanation of scores.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "positiveSentimentTo", + "in": "query", + "description": "Filters results with a sentiment score less than or equal to the specified value, indicating positive sentiment. See the Article Data section in Docs for an explanation of scores.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "neutralSentimentFrom", + "in": "query", + "description": "Filters results with a sentiment score greater than or equal to the specified value, indicating neutral sentiment. Explanation of sentimental values can be found in Docs under the Article Data section.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "neutralSentimentTo", + "in": "query", + "description": "Filters results with a sentiment score less than or equal to the specified value, indicating neutral sentiment. See the Article Data section in Docs for an explanation of scores.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "negativeSentimentFrom", + "in": "query", + "description": "Filters results with a sentiment score greater than or equal to the specified value, indicating negative sentiment. See the Article Data section in Docs for an explanation of scores.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "negativeSentimentTo", + "in": "query", + "description": "Filters results with a sentiment score less than or equal to the specified value, indicating negative sentiment. See the Article Data section in Docs for an explanation of scores.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "taxonomy", + "in": "query", + "description": "Filters by Google Content Categories. This field will accept 1 or more categories, must pass the full name of the category. Example: taxonomy=/Finance/Banking/Other, /Finance/Investing/Funds", + "schema": { + "type": "string" + } + }, + { + "name": "prefixTaxonomy", + "in": "query", + "description": "Filters by Google Content Categories. This field will filter by the category prefix only. Example: prefixTaxonomy=/Finance", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "200", + "content": { + "application/json": { + "examples": { + "Result": { + "value": "{\n \"status\": 200,\n \"numResults\": 1,\n \"articles\": [\n {\n \"url\": \"https://decrypt.co/301053/nft-market-hits-three-year-low-in-trading-and-sales-report\",\n \"authorsByline\": \"Vismaya V\",\n \"articleId\": \"680d7893185c4357a9047332cf38206c\",\n \"clusterId\": \"37426b0543cb45e3a547695fd63e9919\",\n \"source\": {\n \"domain\": \"decrypt.co\",\n \"paywall\": false,\n \"location\": {\n \"country\": \"us\",\n \"state\": \"NY\",\n \"city\": \"New York\",\n \"coordinates\": {\n \"lat\": 40.7127281,\n \"lon\": -74.0060152\n }\n }\n },\n \"imageUrl\": \"https://cdn.decrypt.co/resize/1024/height/512/wp-content/uploads/2021/07/The-Bored-Ape-Yacht-Club-gID_7.jpeg\",\n \"country\": \"us\",\n \"language\": \"en\",\n \"pubDate\": \"2025-01-15T09:20:34+00:00\",\n \"addDate\": \"2025-01-15T09:27:57.156032+00:00\",\n \"refreshDate\": \"2025-01-15T09:27:57.156034+00:00\",\n \"score\": 52.79721,\n \"title\": \"NFT Market Hits Three-Year Low in Trading and Sales: Report\",\n \"description\": \"Annual NFT trading volumes fell by 19%, while sales counts dipped by 18% compared to 2023, according to DappRadar.\",\n \"content\": \"The NFT market suffered a dismal 2024, with trading volumes and sales counts dropping to their weakest levels since 2020.\\n\\nAnnual trading volumes fell by 19%, while sales counts dipped by 18% compared to 2023, according to a report by blockchain analytics platform.\\n\\nDespite a surge in crypto market activity, driven by Bitcoin’s all-time highs and booming DeFi growth, NFTs appeared to struggle under the weight of their own inflated valuations.\\n\\nEarly in the year, NFT trading volumes reached $5.3 billion in Q1, a modest 4% increase compared to the same period in 2023.\\n\\nHowever, this momentum proved fleeting, as volumes plummeted to $1.5 billion in Q3 before recovering slightly to $2.6 billion in Q4.\\n\\nEven with these fluctuations, annual sales counts fell sharply, pointing to a broader trend: while individual NFTs became more expensive in line with rising crypto token prices, overall market engagement dwindled.\\n\\nYuga Labs’ flagship collections Bored Ape Yacht Club (BAYC) and Mutant Ape Yacht Club (MAYC) hit historic lows, with floor prices dropping to 15 ETH and 2.4 ETH, respectively.\\n\\nEven Otherdeeds for Yuga Labs' Otherside metaverse plummeted to 0.23 ETH, a far cry from their initial minting price, exposing cracks in Yuga’s high-priced, membership-driven model.\\n\\nThis coincided with DappRadar’s observation that “Perhaps 2024 helped us realize that NFTs don’t need to be expensive to prove their importance in the broader Web3 ecosystem,” a critique of the market’s reliance on exclusivity and inflated pricing.\\n\\nAmid this downturn, the NFT market witnessed a paradox in November when CryptoPunk #8348, a rare seven-trait collectible from the NFT collection, was collateralized for a $2.75 million loan via the NFT lending platform GONDI.\\n\\nTouted as a milestone for NFTs as financial assets, this event showed speculative excess when juxtaposed with DappRadar’s insights about affordability and utility.\\n\\nWhile high-profile transactions like this aim to affirm NFTs’ value, they also highlight a market still driven by exclusivity and inflated pricing, even as wider participation wanes.\\n\\nEven within the struggling sector, blue-chip collections like CryptoPunks defied trends, nearly doubling in USD value in 2024 with notable sales driving brief recovery periods.\\n\\nNFT platforms like Blur dominated marketplace activity, leveraging zero-fee trading and aggressive airdrop campaigns to capture the largest share of trading volumes.\\n\\nIn contrast, rival marketplace OpenSea struggled with regulatory headwinds and declining market sentiment, forcing significant layoffs by year-end.\\n\\nBy Q4, Blur and OpenSea were neck-and-neck in market share, but Blur’s ability to generate high activity from a smaller, more active user base gave it the edge, as per the report.\\n\\nWhile trading volumes in late 2024 hinted at a potential recovery—November sales hit $562 million, the highest since May—the overall trajectory suggests that affordability, accessibility, and utility will be critical for sustained growth in 2025.\",\n \"medium\": \"Article\",\n \"links\": [\n \"https://dappradar.com/blog/dapp-industry-report-2024-overview\",\n \"https://decrypt.co/resources/what-is-the-metaverse-immersive-nft-virtual-world\",\n \"https://decrypt.co/resources/non-fungible-tokens-nfts-explained-guide-learn-blockchain\",\n \"https://decrypt.co/247932/sec-coming-after-opensea-nfts-could-be-in-trouble\",\n \"https://share.flipboard.com/bookmarklet/popout?v=2&url=https://decrypt.co/301053/nft-market-hits-three-year-low-in-trading-and-sales-report\",\n \"https://decrypt.co/resources/what-are-cryptopunks-ethereum-nft-avatars\",\n \"https://decrypt.co/291710/cryptopunk-prices-surge-bitcoin-gains\",\n \"https://decrypt.co/scene\",\n \"https://decrypt.co/resources/what-is-bored-ape-yacht-club-the-celebrity-nft-of-choice\",\n \"https://decrypt.co/247930/if-you-bought-bored-ape-nfts-at-the-peak-youve-lost-93-of-your-investment\",\n \"https://decrypt.co/293754/someone-just-took-out-a-2-75-million-loan-against-this-one-of-one-cryptopunk-nft\"\n ],\n \"labels\": [\n {\n \"name\": \"Roundup\"\n }\n ],\n \"matchedAuthors\": [\n {\n \"id\": null,\n \"name\": \"Vismaya V\"\n }\n ],\n \"claim\": \"\",\n \"verdict\": \"\",\n \"keywords\": [\n {\n \"name\": \"NFT trading volumes\",\n \"weight\": 0.095650345\n },\n {\n \"name\": \"NFT Market\",\n \"weight\": 0.09479949\n },\n {\n \"name\": \"crypto market activity\",\n \"weight\": 0.09068515\n },\n {\n \"name\": \"Annual trading volumes\",\n \"weight\": 0.08782178\n },\n {\n \"name\": \"trading volumes\",\n \"weight\": 0.087688774\n },\n {\n \"name\": \"market share\",\n \"weight\": 0.08508381\n },\n {\n \"name\": \"overall market engagement\",\n \"weight\": 0.08292204\n },\n {\n \"name\": \"declining market sentiment\",\n \"weight\": 0.080258906\n },\n {\n \"name\": \"annual sales counts\",\n \"weight\": 0.07653589\n },\n {\n \"name\": \"sales counts\",\n \"weight\": 0.07410056\n }\n ],\n \"topics\": [],\n \"categories\": [],\n \"taxonomies\": [\n {\n \"name\": \"/Finance/Investing/Currencies & Foreign Exchange\"\n },\n {\n \"name\": \"/News/Business News/Financial Markets News\"\n }\n ],\n \"entities\": [\n {\n \"data\": \"Yuga Labs’\",\n \"type\": \"ORG\",\n \"mentions\": 3\n },\n {\n \"data\": \"Bored Ape Yacht Club\",\n \"type\": \"ORG\",\n \"mentions\": 1\n },\n {\n \"data\": \"BAYC\",\n \"type\": \"ORG\",\n \"mentions\": 1\n },\n {\n \"data\": \"Mutant Ape Yacht Club\",\n \"type\": \"ORG\",\n \"mentions\": 1\n },\n {\n \"data\": \"MAYC\",\n \"type\": \"ORG\",\n \"mentions\": 1\n },\n {\n \"data\": \"DappRadar\",\n \"type\": \"ORG\",\n \"mentions\": 2\n },\n {\n \"data\": \"NFT\",\n \"type\": \"ORG\",\n \"mentions\": 4\n },\n {\n \"data\": \"GONDI\",\n \"type\": \"ORG\",\n \"mentions\": 1\n },\n {\n \"data\": \"Blur\",\n \"type\": \"ORG\",\n \"mentions\": 3\n },\n {\n \"data\": \"OpenSea\",\n \"type\": \"ORG\",\n \"mentions\": 2\n },\n {\n \"data\": \"Otherside\",\n \"type\": \"PRODUCT\",\n \"mentions\": 1\n },\n {\n \"data\": \"CryptoPunks\",\n \"type\": \"PRODUCT\",\n \"mentions\": 1\n }\n ],\n \"companies\": [\n {\n \"id\": \"f0886b1323a142df88f521ba9a0bbedf\",\n \"name\": \"OpenSea Ventures\",\n \"domains\": [\n \"opensea.io\"\n ],\n \"symbols\": []\n },\n {\n \"id\": \"bee2238a04fe4f228252ea641c3403a7\",\n \"name\": \"NFT Labs\",\n \"domains\": [\n \"nftlabs.to\"\n ],\n \"symbols\": []\n }\n ],\n \"sentiment\": {\n \"positive\": 0.033333376,\n \"negative\": 0.89130986,\n \"neutral\": 0.07535672\n },\n \"summary\": \"The National Finance Finance (NFT) market experienced a three-year low in 2024, with annual trading volumes and sales counts dropping to their lowest levels since 2020. The report by blockchain analytics platform DappRadar suggests that despite a surge in crypto market activity driven by Bitcoin's all-time highs and DeFi growth, NFTs struggled under the weight of their inflated valuations. Despite early Q1 trading volumes reaching $5.3 billion, a 4% increase compared to the same period in 2023, volumes dropped to $1.5 billion in Q3 before recovering to $2.6 billion by Q4. Despite these fluctuations, overall market engagement decreased. Despite this downturn, high-profile transactions like CryptoPunk #8348, a rare seven-trait collectible from the NFT collection, were seen as a milestone for NFT's value and highlighted a market still driven by exclusivity and inflated pricing.\",\n \"translation\": \"\",\n \"translatedTitle\": \"\",\n \"translatedDescription\": \"\",\n \"translatedSummary\": \"\",\n \"locations\": [],\n \"reprint\": false,\n \"reprintGroupId\": \"3d67e5bf389b40b3895ae0708f4dd208\",\n \"places\": [],\n \"people\": []\n }\n ]\n}" + } + }, + "schema": { + "type": "object", + "properties": { + "status": { + "type": "integer", + "example": 200, + "default": 0 + }, + "numResults": { + "type": "integer", + "example": 1, + "default": 0 + }, + "articles": { + "type": "array", + "items": { + "type": "object", + "properties": { + "url": { + "type": "string", + "example": "https://decrypt.co/301053/nft-market-hits-three-year-low-in-trading-and-sales-report" + }, + "authorsByline": { + "type": "string", + "example": "Vismaya V" + }, + "articleId": { + "type": "string", + "example": "680d7893185c4357a9047332cf38206c" + }, + "clusterId": { + "type": "string", + "example": "37426b0543cb45e3a547695fd63e9919" + }, + "source": { + "type": "object", + "properties": { + "domain": { + "type": "string", + "example": "decrypt.co" + }, + "paywall": { + "type": "boolean", + "example": false, + "default": true + }, + "location": { + "type": "object", + "properties": { + "country": { + "type": "string", + "example": "us" + }, + "state": { + "type": "string", + "example": "NY" + }, + "city": { + "type": "string", + "example": "New York" + }, + "coordinates": { + "type": "object", + "properties": { + "lat": { + "type": "number", + "example": 40.7127281, + "default": 0 + }, + "lon": { + "type": "number", + "example": -74.0060152, + "default": 0 + } + } + } + } + } + } + }, + "imageUrl": { + "type": "string", + "example": "https://cdn.decrypt.co/resize/1024/height/512/wp-content/uploads/2021/07/The-Bored-Ape-Yacht-Club-gID_7.jpeg" + }, + "country": { + "type": "string", + "example": "us" + }, + "language": { + "type": "string", + "example": "en" + }, + "pubDate": { + "type": "string", + "example": "2025-01-15T09:20:34+00:00" + }, + "addDate": { + "type": "string", + "example": "2025-01-15T09:27:57.156032+00:00" + }, + "refreshDate": { + "type": "string", + "example": "2025-01-15T09:27:57.156034+00:00" + }, + "score": { + "type": "number", + "example": 52.79721, + "default": 0 + }, + "title": { + "type": "string", + "example": "NFT Market Hits Three-Year Low in Trading and Sales: Report" + }, + "description": { + "type": "string", + "example": "Annual NFT trading volumes fell by 19%, while sales counts dipped by 18% compared to 2023, according to DappRadar." + }, + "content": { + "type": "string", + "example": "The NFT market suffered a dismal 2024, with trading volumes and sales counts dropping to their weakest levels since 2020.\n\nAnnual trading volumes fell by 19%, while sales counts dipped by 18% compared to 2023, according to a report by blockchain analytics platform.\n\nDespite a surge in crypto market activity, driven by Bitcoin’s all-time highs and booming DeFi growth, NFTs appeared to struggle under the weight of their own inflated valuations.\n\nEarly in the year, NFT trading volumes reached $5.3 billion in Q1, a modest 4% increase compared to the same period in 2023.\n\nHowever, this momentum proved fleeting, as volumes plummeted to $1.5 billion in Q3 before recovering slightly to $2.6 billion in Q4.\n\nEven with these fluctuations, annual sales counts fell sharply, pointing to a broader trend: while individual NFTs became more expensive in line with rising crypto token prices, overall market engagement dwindled.\n\nYuga Labs’ flagship collections Bored Ape Yacht Club (BAYC) and Mutant Ape Yacht Club (MAYC) hit historic lows, with floor prices dropping to 15 ETH and 2.4 ETH, respectively.\n\nEven Otherdeeds for Yuga Labs' Otherside metaverse plummeted to 0.23 ETH, a far cry from their initial minting price, exposing cracks in Yuga’s high-priced, membership-driven model.\n\nThis coincided with DappRadar’s observation that “Perhaps 2024 helped us realize that NFTs don’t need to be expensive to prove their importance in the broader Web3 ecosystem,” a critique of the market’s reliance on exclusivity and inflated pricing.\n\nAmid this downturn, the NFT market witnessed a paradox in November when CryptoPunk #8348, a rare seven-trait collectible from the NFT collection, was collateralized for a $2.75 million loan via the NFT lending platform GONDI.\n\nTouted as a milestone for NFTs as financial assets, this event showed speculative excess when juxtaposed with DappRadar’s insights about affordability and utility.\n\nWhile high-profile transactions like this aim to affirm NFTs’ value, they also highlight a market still driven by exclusivity and inflated pricing, even as wider participation wanes.\n\nEven within the struggling sector, blue-chip collections like CryptoPunks defied trends, nearly doubling in USD value in 2024 with notable sales driving brief recovery periods.\n\nNFT platforms like Blur dominated marketplace activity, leveraging zero-fee trading and aggressive airdrop campaigns to capture the largest share of trading volumes.\n\nIn contrast, rival marketplace OpenSea struggled with regulatory headwinds and declining market sentiment, forcing significant layoffs by year-end.\n\nBy Q4, Blur and OpenSea were neck-and-neck in market share, but Blur’s ability to generate high activity from a smaller, more active user base gave it the edge, as per the report.\n\nWhile trading volumes in late 2024 hinted at a potential recovery—November sales hit $562 million, the highest since May—the overall trajectory suggests that affordability, accessibility, and utility will be critical for sustained growth in 2025." + }, + "medium": { + "type": "string", + "example": "Article" + }, + "links": { + "type": "array", + "items": { + "type": "string", + "example": "https://dappradar.com/blog/dapp-industry-report-2024-overview" + } + }, + "labels": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "example": "Roundup" + } + } + } + }, + "matchedAuthors": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": {}, + "name": { + "type": "string", + "example": "Vismaya V" + } + } + } + }, + "claim": { + "type": "string", + "example": "" + }, + "verdict": { + "type": "string", + "example": "" + }, + "keywords": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "example": "NFT trading volumes" + }, + "weight": { + "type": "number", + "example": 0.095650345, + "default": 0 + } + } + } + }, + "topics": { + "type": "array" + }, + "categories": { + "type": "array" + }, + "taxonomies": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "example": "/Finance/Investing/Currencies & Foreign Exchange" + } + } + } + }, + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "data": { + "type": "string", + "example": "Yuga Labs’" + }, + "type": { + "type": "string", + "example": "ORG" + }, + "mentions": { + "type": "integer", + "example": 3, + "default": 0 + } + } + } + }, + "companies": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "example": "f0886b1323a142df88f521ba9a0bbedf" + }, + "name": { + "type": "string", + "example": "OpenSea Ventures" + }, + "domains": { + "type": "array", + "items": { + "type": "string", + "example": "opensea.io" + } + }, + "symbols": { + "type": "array" + } + } + } + }, + "sentiment": { + "type": "object", + "properties": { + "positive": { + "type": "number", + "example": 0.033333376, + "default": 0 + }, + "negative": { + "type": "number", + "example": 0.89130986, + "default": 0 + }, + "neutral": { + "type": "number", + "example": 0.07535672, + "default": 0 + } + } + }, + "summary": { + "type": "string", + "example": "The National Finance Finance (NFT) market experienced a three-year low in 2024, with annual trading volumes and sales counts dropping to their lowest levels since 2020. The report by blockchain analytics platform DappRadar suggests that despite a surge in crypto market activity driven by Bitcoin's all-time highs and DeFi growth, NFTs struggled under the weight of their inflated valuations. Despite early Q1 trading volumes reaching $5.3 billion, a 4% increase compared to the same period in 2023, volumes dropped to $1.5 billion in Q3 before recovering to $2.6 billion by Q4. Despite these fluctuations, overall market engagement decreased. Despite this downturn, high-profile transactions like CryptoPunk #8348, a rare seven-trait collectible from the NFT collection, were seen as a milestone for NFT's value and highlighted a market still driven by exclusivity and inflated pricing." + }, + "translation": { + "type": "string", + "example": "" + }, + "translatedTitle": { + "type": "string", + "example": "" + }, + "translatedDescription": { + "type": "string", + "example": "" + }, + "translatedSummary": { + "type": "string", + "example": "" + }, + "locations": { + "type": "array" + }, + "reprint": { + "type": "boolean", + "example": false, + "default": true + }, + "reprintGroupId": { + "type": "string", + "example": "3d67e5bf389b40b3895ae0708f4dd208" + }, + "places": { + "type": "array" + }, + "people": { + "type": "array" + } + } + } + } + } + } + } + } + }, + "400": { + "description": "400", + "content": { + "text/plain": { + "examples": { + "Result": { + "value": "The request has bad formatting or missing parameters" + } + } + } + } + }, + "401": { + "description": "401", + "content": { + "text/plain": { + "examples": { + "Result": { + "value": "No API key was provided in the request" + } + } + } + } + }, + "403": { + "description": "403", + "content": { + "text/plain": { + "examples": { + "Result": { + "value": "Request was forbidden, likely due to plan restrictions or account status" + } + } + } + } + }, + "404": { + "description": "404", + "content": { + "text/plain": { + "examples": { + "Result": { + "value": "The requested resource was not found" + } + } + } + } + }, + "500": { + "description": "500", + "content": { + "text/plain": { + "examples": { + "Result": { + "value": "Some internal error has occurred, please contact support" + } + } + } + } + } + }, + "deprecated": false, + "security": [], + "x-readme": { + "code-samples": [ + { + "language": "curl", + "code": "$ curl 'https://api.goperigon.com/v1/all?category=Business&sourceGroup=top100&showReprints=false&apiKey=API_KEY'" + }, + { + "language": "python", + "code": "import requests\n\nAPI_KEY = \"API_KEY\"\nurl = f\"https://api.goperigon.com/v1/all?category=Business&sourceGroup=top100&showReprints=false&apiKey={API_KEY}\"\n\nresp = requests.get(url)\n\nprint(resp.json())" + }, + { + "language": "ruby", + "code": "require 'net/http'\n\napi_key = \"API_KEY\"\nurl = URI.parse(\"https://api.goperigon.com/v1/all?category=Business&sourceGroup=top100&showReprints=false&apiKey=#{api_key}\")\nres = Net::HTTP.get(URI.parse(url.to_s))\n\nputs res" + }, + { + "language": "go", + "code": "package main\n\nimport (\n \"fmt\"\n \"net/http\"\n \"io/ioutil\"\n)\n\nfunc main() {\n key := \"API_KEY\"\n url := \"https://api.goperigon.com/v1/all?category=Business&sourceGroup=top100&showReprints=false&apiKey=\" + key \n res, err := http.Get(url)\n if err != nil {\n fmt.Println(err)\n }\n \n defer res.Body.Close()\n body, err := ioutil.ReadAll(res.Body)\n if err != nil {\n fmt.Println(err)\n }\n \n fmt.Println(string(body))\n}" + }, + { + "language": "javascript", + "code": "const axios = require('axios');\nconst apiKey = \"API_KEY\"\nconst url = `https://api.goperigon.com/v1/all?category=Business&sourceGroup=top100&showReprints=false&apiKey=${apiKey}`\n\naxios.get(url)\n .then((response) => {\n console.log(response);\n })\n .catch((error) => {\n console.log(error);\n });" + } + ], + "samples-languages": [ + "curl", + "python", + "ruby", + "go", + "javascript" + ] + } + } + }, + "/v1/stories/all": { + "get": { + "summary": "Stories", + "description": "", + "operationId": "stories-1", + "parameters": [ + { + "name": "apiKey", + "in": "query", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "q", + "in": "query", + "description": "Search story by name, summary and key points. Preference is given to the name field. Supports complex query syntax, same way as **q** parameter from **/all** endpoint.", + "schema": { + "type": "string" + } + }, + { + "name": "name", + "in": "query", + "description": "Search story by name. Supports complex query syntax, same way as **q** parameter from **/all** endpoint.", + "schema": { + "type": "string" + } + }, + { + "name": "topic", + "in": "query", + "description": "Filter by topics. Each topic is some kind of entity that the article is about. Examples of topics: Markets, Joe Biden, Green Energy, Climate Change, Cryptocurrency, etc. If multiple parameters are passed, they will be applied as OR operations. More ➜", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "category", + "in": "query", + "description": "Filter by categories. Categories are general themes that the article is about. Examples of categories: Tech, Politics, etc. If multiple parameters are passed, they will be applied as OR operations. Use 'none' to search uncategorized articles. More ➜", + "schema": { + "type": "string", + "enum": [ + "Politics", + "Tech", + "Sports", + "Business", + "Finance", + "Entertainment", + "Health", + "Weather", + "Lifestyle", + "Auto", + "Science", + "Travel", + "Environment", + "World", + "General", + "none" + ] + } + }, + { + "name": "clusterId", + "in": "query", + "description": "Filter to specific story. Passing a cluster ID will filter results to only the content found within the cluster. Multiple params could be passed.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "source", + "in": "query", + "description": "Filter stories by sources that wrote articles belonging to this story. At least 1 article is required for story to match. Multiple parameters could be passed.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "sourceGroup", + "in": "query", + "description": "Filter stories by sources that wrote articles belonging to this story. Source groups are expanded into a list of sources. At least 1 article by the source is required for story to match. Multiple params could be passed.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "personWikidataId", + "in": "query", + "description": "List of person Wikidata IDs for filtering. Filter is applied on topPeople field.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "personName", + "in": "query", + "description": "List of people names. Filtering is applied on topPeople field.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "companyId", + "in": "query", + "description": "List of company IDs for filtering. Filtering is applied to topCompanies field.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "companyName", + "in": "query", + "description": "List of company names for filtering. Filtering is applied on topCompanies field.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "companyDomain", + "in": "query", + "description": "List of company domains for filtering. Filtering is applied on topCompanies field.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "companySymbol", + "in": "query", + "description": "List of company tickers for filtering. Filtering is applied on topCompanies field.", + "schema": { + "type": "string" + } + }, + { + "name": "nameExists", + "in": "query", + "description": "Returns stories with name assigned. Defaults to true.", + "schema": { + "type": "boolean", + "default": true + } + }, + { + "name": "from", + "in": "query", + "description": "'from' filter, will search stories created after the specified date, the date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2023-03-01T00:00:00", + "schema": { + "type": "string", + "format": "date-time" + } + }, + { + "name": "to", + "in": "query", + "description": "'to' filter, will search stories created before the specified date, the date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2023-03-01T23:59:59", + "schema": { + "type": "string", + "format": "date-time" + } + }, + { + "name": "initializedFrom", + "in": "query", + "description": "'initializedFrom' filter, will search stories that became available after provided date", + "schema": { + "type": "string", + "format": "date" + } + }, + { + "name": "initializedTo", + "in": "query", + "description": "'initializedTo' filter, will search stories that became available before provided date", + "schema": { + "type": "string", + "format": "date" + } + }, + { + "name": "updatedFrom", + "in": "query", + "description": "Will return stories with 'updatedAt' >= 'updatedFrom'.", + "schema": { + "type": "string", + "format": "date" + } + }, + { + "name": "updatedTo", + "in": "query", + "description": "Will return stories with 'updatedAt' <= 'updatedTo'.", + "schema": { + "type": "string", + "format": "date" + } + }, + { + "name": "minClusterSize", + "in": "query", + "description": "Filter by minimum cluster size. Minimum cluster size filter applies to number of **unique** articles.", + "schema": { + "type": "integer", + "format": "int32", + "default": 5 + } + }, + { + "name": "maxClusterSize", + "in": "query", + "description": "Filter by maximum cluster size. Maximum cluster size filter applies to number of **unique** articles in the cluster.", + "schema": { + "type": "integer", + "format": "int32" + } + }, + { + "name": "state", + "in": "query", + "description": "Filter local news by state. Applies only to local news, when this param is passed non-local news will not be returned. If multiple parameters are passed, they will be applied as OR operations.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "city", + "in": "query", + "description": "Filter local news by city. Applies only to local news, when this param is passed non-local news will not be returned. If multiple parameters are passed, they will be applied as OR operations. More ➜", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "area", + "in": "query", + "description": "Filter local news by area. Applies only to local news, when this param is passed non-local news will not be returned. If multiple parameters are passed, they will be applied as OR operations.", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "page", + "in": "query", + "description": "Zero-based page number. From 0 to 10000. See the Pagination section for limitations.", + "schema": { + "type": "integer", + "format": "int32", + "default": 0 + } + }, + { + "name": "size", + "in": "query", + "description": "Number of stories results per page, from 0 to 100.", + "schema": { + "type": "integer", + "format": "int32", + "default": 10 + } + }, + { + "name": "sortBy", + "in": "query", + "description": "Sort stories by count, creation date, last updated date. By default is sorted by created at.", + "schema": { + "type": "string", + "enum": [ + "createdAt", + "updatedAt", + "count" + ], + "default": "createdAt" + } + }, + { + "name": "showNumResults", + "in": "query", + "description": "Show total number of results. By default set to false, will cap result count at 10000.", + "schema": { + "type": "boolean", + "default": false + } + }, + { + "name": "showDuplicates", + "in": "query", + "description": "Stories are deduplicated by default. If a story is deduplicated, all future articles are merged into the original story. *duplicateOf* field contains the original cluster Id. When *showDuplicates=true*, all stories are shown.", + "schema": { + "type": "boolean", + "default": false + } + }, + { + "name": "positiveSentimentFrom", + "in": "query", + "description": "Filters results with a sentiment score greater than or equal to the specified value, indicating positive sentiment. See the Article Data section in Docs for an explanation of scores.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "positiveSentimentTo", + "in": "query", + "description": "Filters results with a sentiment score less than or equal to the specified value, indicating positive sentiment. See the Article Data section in Docs for an explanation of scores.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "neutralSentimentFrom", + "in": "query", + "description": "Filters results with a sentiment score greater than or equal to the specified value, indicating neutral sentiment. Explanation of sentimental values can be found in Docs under the Article Data section.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "neutralSentimentTo", + "in": "query", + "description": "Filters results with a sentiment score less than or equal to the specified value, indicating neutral sentiment. See the Article Data section in Docs for an explanation of scores.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "negativeSentimentFrom", + "in": "query", + "description": "Filters results with a sentiment score greater than or equal to the specified value, indicating negative sentiment. See the Article Data section in Docs for an explanation of scores.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "negativeSentimentTo", + "in": "query", + "description": "Filters results with a sentiment score less than or equal to the specified value, indicating negative sentiment. See the Article Data section in Docs for an explanation of scores.", + "schema": { + "type": "number", + "format": "float" + } + }, + { + "name": "country", + "in": "query", + "description": "Country code to filter by country. If multiple parameters are passed, they will be applied as OR operations.", + "schema": { + "type": "string", + "enum": [ + "us", + "gb", + "de", + "it", + "fr", + "nl", + "se", + "dk", + "fi", + "hu", + "no", + "pl", + "pt", + "ru", + "ua", + "ch", + "br", + "nz", + "mx", + "au" + ] + } + }, + { + "name": "taxonomy", + "in": "query", + "description": "Filters by Google Content Categories. This field will accept 1 or more categories, must pass the full name of the category. Example: taxonomy=/Finance/Banking/Other, /Finance/Investing/Funds", + "schema": { + "type": "string" + } + }, + { + "name": "topTaxonomies", + "in": "query", + "description": "Filters by Google Content Categories. Highlights the top 3 categories in a cluster, ordered by count.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "200", + "content": { + "application/json": { + "examples": { + "Result": { + "value": "{\n \"status\": 200,\n \"numResults\": 18,\n \"results\": [\n {\n \"createdAt\": \"2025-01-29T08:11:03.602007+00:00\",\n \"updatedAt\": \"2025-01-29T14:46:26.744051+00:00\",\n \"initializedAt\": \"2025-01-29T08:42:16.214884+00:00\",\n \"id\": \"dc0612a3ff094e94be93f5713db2a940\",\n \"name\": \"Norway's Wealth Fund Reports Record $222 Billion Profit\",\n \"summary\": \"Norway's $1.8 trillion sovereign wealth fund announced a record annual profit of 2.51 trillion crowns ($222 billion) for 2024, primarily driven by a strong performance in the technology sector. CEO Nicolai Tangen noted that American tech giants like Apple, Microsoft, and Nvidia played a crucial role in this success, contributing to an overall return on investment of 13%. Despite this impressive profit, state inflows into the fund were lower than previous records, and returns from fixed income and real estate investments lagged. The fund, which averages 1.5% ownership of publicly listed stocks worldwide, continues to leverage revenues from Norway's oil and gas production. This milestone underscores the fund's strategic importance in bolstering Norway's economic position globally. Overall, the tech rally significantly enhanced the fund's financial standing in 2024.\",\n \"summaryReferences\": [\n \"5e5c0b136c214f588e4bcc18d9bcc1bc\",\n \"ffe6384f9f214f3782d99f06d56af619\",\n \"ac1002cc44f44632b4a29e2152e895cb\",\n \"f3dac6be5b5d42aa8a0c49f6c4fff237\",\n \"68c97189db94453597766a8b6bb6faf0\"\n ],\n \"keyPoints\": [\n {\n \"point\": \"Nicolai Tangen noted, 'Despite the impressive profit, the return on investment was slightly below our benchmark index,' indicating a need for improvement in future results.\",\n \"references\": [\n \"5e5c0b136c214f588e4bcc18d9bcc1bc\"\n ]\n },\n {\n \"point\": \"The fund's equity investments yielded an 18% return, while fixed income investments only saw a 1% increase, showcasing a stark contrast in performance across asset classes.\",\n \"references\": [\n \"ffe6384f9f214f3782d99f06d56af619\"\n ]\n },\n {\n \"point\": \"State inflows into the fund amounted to 402 billion crowns, highlighting a decrease compared to the previous record high of 2022, which affects future investment capabilities.\",\n \"references\": [\n \"ac1002cc44f44632b4a29e2152e895cb\"\n ]\n }\n ],\n \"sentiment\": {\n \"positive\": 0.7317738,\n \"negative\": 0.11641231,\n \"neutral\": 0.15181391\n },\n \"uniqueCount\": 15,\n \"reprintCount\": 14,\n \"totalCount\": 29,\n \"countries\": [\n {\n \"name\": \"in\",\n \"count\": 6\n },\n {\n \"name\": \"us\",\n \"count\": 14\n },\n {\n \"name\": \"ca\",\n \"count\": 3\n },\n {\n \"name\": \"ie\",\n \"count\": 1\n },\n {\n \"name\": \"am\",\n \"count\": 1\n },\n {\n \"name\": \"ae\",\n \"count\": 1\n },\n {\n \"name\": \"my\",\n \"count\": 1\n },\n {\n \"name\": \"ph\",\n \"count\": 1\n }\n ],\n \"topCountries\": [\n \"us\"\n ],\n \"topics\": [\n {\n \"name\": \"Odd News\",\n \"count\": 1\n },\n {\n \"name\": \"Markets\",\n \"count\": 5\n },\n {\n \"name\": \"Economy\",\n \"count\": 1\n }\n ],\n \"topTopics\": [\n {\n \"name\": \"Markets\"\n }\n ],\n \"categories\": [\n {\n \"name\": \"Business\",\n \"count\": 7\n },\n {\n \"name\": \"Finance\",\n \"count\": 7\n },\n {\n \"name\": \"World\",\n \"count\": 1\n }\n ],\n \"topCategories\": [\n {\n \"name\": \"Business\"\n },\n {\n \"name\": \"Finance\"\n }\n ],\n \"taxonomies\": [\n {\n \"name\": \"/News/Business News/Financial Markets News\",\n \"count\": 26\n },\n {\n \"name\": \"/Finance/Investing/Other\",\n \"count\": 26\n },\n {\n \"name\": \"/News/Business News/Other\",\n \"count\": 23\n },\n {\n \"name\": \"/News/Business News/Company News\",\n \"count\": 26\n },\n {\n \"name\": \"/Finance/Investing/Funds\",\n \"count\": 21\n },\n {\n \"name\": \"/News/Business News/Economy News\",\n \"count\": 7\n },\n {\n \"name\": \"/Finance/Investing/Stocks & Bonds\",\n \"count\": 25\n },\n {\n \"name\": \"/Finance/Financial Planning & Management/Asset & Portfolio Management\",\n \"count\": 1\n },\n {\n \"name\": \"/News/Technology News\",\n \"count\": 2\n }\n ],\n \"topTaxonomies\": [\n {\n \"name\": \"/News/Business News/Financial Markets News\"\n },\n {\n \"name\": \"/Finance/Investing/Other\"\n },\n {\n \"name\": \"/News/Business News/Company News\"\n },\n {\n \"name\": \"/Finance/Investing/Stocks & Bonds\"\n },\n {\n \"name\": \"/News/Business News/Other\"\n },\n {\n \"name\": \"/Finance/Investing/Funds\"\n }\n ],\n \"people\": [\n {\n \"wikidataId\": \"Q56408252\",\n \"name\": \"Nicolai Tangen\",\n \"count\": 24\n },\n {\n \"wikidataId\": \"Q22686\",\n \"name\": \"Donald Trump\",\n \"count\": 2\n }\n ],\n \"topPeople\": [\n {\n \"wikidataId\": \"Q56408252\",\n \"name\": \"Nicolai Tangen\"\n }\n ],\n \"companies\": [\n {\n \"id\": \"4de51cf8472b4ce7a5aecdf52a1de4c0\",\n \"name\": \"Microsoft Corporation\",\n \"domains\": [\n \"microsoft.com\"\n ],\n \"symbols\": [\n \"4338.HK\",\n \"MSF.BR\",\n \"MSF.DE\",\n \"MSFT\"\n ],\n \"count\": 2\n },\n {\n \"id\": \"806457af1fd9418db78388760f52c06f\",\n \"name\": \"Alphabet Inc.\",\n \"domains\": [\n \"abc.xyz\"\n ],\n \"symbols\": [\n \"ABEA.DE\",\n \"ABEC.DE\",\n \"GOOG\",\n \"GOOGL\",\n \"GOOGL.SW\"\n ],\n \"count\": 1\n },\n {\n \"id\": \"94bbd0512cd04cc4b7041d78d9d4cf73\",\n \"name\": \"NVIDIA Corporation\",\n \"domains\": [\n \"nvidia.com\"\n ],\n \"symbols\": [\n \"NVD.DE\",\n \"NVDA\"\n ],\n \"count\": 3\n }\n ],\n \"topCompanies\": [],\n \"locations\": [\n {\n \"count\": 5\n },\n {\n \"state\": \"03\",\n \"city\": \"Oslo\",\n \"count\": 9\n }\n ],\n \"topLocations\": [\n {\n \"state\": \"03\",\n \"city\": \"Oslo\"\n },\n {}\n ]\n }," + } + } + } + } + }, + "400": { + "description": "400", + "content": { + "application/json": { + "examples": { + "Result": { + "value": "{\n \"status\": 400,\n \"message\": \"Errors during parameter validation: \\nError on parameter 'updatedFrom', invalid value 'test': Failed to convert property value of type 'java.lang.String' to required type 'java.time.OffsetDateTime' for property 'updatedFrom'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.gawq.api.formatting.DateTimeRequestParam java.time.OffsetDateTime] for value [test]; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [test]\",\n \"timestamp\": 1730827027255\n}" + } + }, + "schema": { + "type": "object", + "properties": { + "status": { + "type": "integer", + "example": 400, + "default": 0 + }, + "message": { + "type": "string", + "example": "Errors during parameter validation: \nError on parameter 'updatedFrom', invalid value 'test': Failed to convert property value of type 'java.lang.String' to required type 'java.time.OffsetDateTime' for property 'updatedFrom'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.gawq.api.formatting.DateTimeRequestParam java.time.OffsetDateTime] for value [test]; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [test]" + }, + "timestamp": { + "type": "integer", + "example": 1730827027255, + "default": 0 + } + } + } + } + } + } + }, + "deprecated": false, + "security": [], + "x-readme": { + "code-samples": [ + { + "language": "curl", + "code": "$ curl 'https://api.goperigon.com/v1/stories/all?category=Business&from=2023-03-01&apiKey=API_KEY", + "name": "curl" + }, + { + "language": "python", + "code": "import requests\n\nAPI_KEY = \"API_KEY\"\nurl = f\"https://api.goperigon.com/v1/all?category=Business&apiKey={API_KEY}\"\n\nresp = requests.get(url)\n\nprint(resp.json())", + "name": "python" + } + ], + "samples-languages": [ + "curl", + "python" + ] + } + } + } + }, + "x-readme": { + "headers": [ + { + "key": "Accept", + "value": "application/json" + } + ] + }, + "x-readme-fauxas": true +} \ No newline at end of file diff --git a/packages/perigon/package.json b/packages/perigon/package.json new file mode 100644 index 0000000..c4a7686 --- /dev/null +++ b/packages/perigon/package.json @@ -0,0 +1,12 @@ +{ + "name": "@web-agent-rs/perigon", + "version": "0.0.0", + "main": "index.ts", + "types": "./index.d.ts", + "type": "module", + "dependencies": { + "api": "^6.1.3", + "json-schema-to-ts": "^2.8.0-beta.0", + "oas": "^20.11.0" + } +} diff --git a/packages/perigon/schemas.ts b/packages/perigon/schemas.ts new file mode 100644 index 0000000..7a0dc4c --- /dev/null +++ b/packages/perigon/schemas.ts @@ -0,0 +1,5 @@ +const AllNews = {"metadata":{"allOf":[{"type":"object","properties":{"apiKey":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#"},"q":{"type":"string","default":"recall OR \"safety concern*\"","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Search query, each article will be scored and ranked against it. Articles are searched on the title, description, and content fields. More ➜"},"title":{"type":"string","default":"tesla OR TSLA OR \"General Motors\" OR GM","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Search article headlines/title field. Semantic similar to q parameter."},"desc":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Search query on the description field. Semantic similar to q parameter."},"content":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Search query on the article's body of content field. Semantic similar to q parameter."},"url":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Search query on the url field. Semantic similar to q parameter. E.g. could be used for querying certain website sections, e.g. source=cnn.com&url=travel."},"articleId":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Article ID will search for a news article by the ID of the article. If several parameters are passed, all matched articles will be returned."},"clusterId":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Search for related content using a cluster ID. Passing a cluster ID will filter results to only the content found within the cluster."},"from":{"type":"string","format":"date-time","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"'from' filter, will search articles published after the specified date, the date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2023-03-01T00:00:00"},"to":{"type":"string","format":"date-time","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"'to' filter, will search articles published before the specified date, the date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2022-02-01T23:59:59"},"addDateFrom":{"type":"string","format":"date-time","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"'addDateFrom' filter, will search articles added after the specified date, the date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2022-02-01T00:00:00"},"addDateTo":{"type":"string","format":"date-time","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"'addDateTo' filter, will search articles added before the specified date, the date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2022-02-01T23:59:59"},"refreshDateFrom":{"type":"string","format":"date-time","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Will search articles that were refreshed after the specified date. The date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2022-02-01T00:00:00"},"refreshDateTo":{"type":"string","format":"date-time","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Will search articles that were refreshed before the specified date. The date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2022-02-01T23:59:59"},"medium":{"type":"string","enum":["Article","Video"],"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Medium will filter out news articles medium, which could be 'Video' or 'Article'. If several parameters are passed, all matched articles will be returned."},"source":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Publisher's domain can include a subdomain. If multiple parameters are passed, they will be applied as OR operations. Wildcards (\\* and ?) are suported (e.g. \\*.cnn.com). More ➜"},"sourceGroup":{"type":"string","enum":["top10","top100","top25crypto","top25finance","top50tech","top100sports","top100leftUS","top100rightUS","top100centerUS"],"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"One of the supported source groups. Find Source Groups in the guided part of our documentation... More ➜"},"excludeSource":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"The domain of the website, which should be excluded from the search. Multiple parameters could be provided. Wildcards (\\* and ?) are suported (e.g. \\*.cnn.com)."},"paywall":{"type":"boolean","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter to show only results where the source has a paywall (true) or does not have a paywall (false)."},"byline":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Author names to filter by. Article author bylines are used as a source field. If multiple parameters are passed, they will be applied as OR operations."},"journalistId":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter by journalist ID. Journalist IDs are unique journalist identifiers which can be found through the Journalist API, or in the matchedAuthors field. More ➜"},"language":{"type":"string","enum":["da","de","en","es","fi","fr","hu","it","nl","no","pl","pt","ru","sv","uk"],"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Language code to filter by language. If multiple parameters are passed, they will be applied as OR operations. More ➜"},"searchTranslation":{"type":"boolean","default":false,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Expand a query to search the translation, translatedTitle, and translatedDescription fields for non-English articles."},"label":{"type":"string","enum":["Opinion","Non-news","Paid News","Fact Check","Pop Culture","Roundup","Press Release","Low Content"],"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Labels to filter by, could be 'Opinion', 'Paid-news', 'Non-news', etc. If multiple parameters are passed, they will be applied as OR operations. More ➜"},"excludeLabel":{"type":"string","enum":["Opinion","Non-news","Paid News","Fact Check","Pop Culture","Roundup","Press Release","Low Content"],"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Exclude results that include specific labels (Opinion, Non-news, Paid News, etc.). You can filter multiple by repeating the parameter."},"category":{"type":"string","enum":["Politics","Tech","Sports","Business","Finance","Entertainment","Health","Weather","Lifestyle","Auto","Science","Travel","Environment","World","General","none"],"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter by categories. Categories are general themes that the article is about. Examples of categories: Tech, Politics, etc. If multiple parameters are passed, they will be applied as OR operations. Use 'none' to search uncategorized articles. More ➜"},"topic":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter by topics. Each topic is some kind of entity that the article is about. Examples of topics: Markets, Joe Biden, Green Energy, Climate Change, Cryptocurrency, etc. If multiple parameters are passed, they will be applied as OR operations. More ➜"},"excludeTopic":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter by excluding topics. Each topic is some kind of entity that the article is about. Examples of topics: Markets, Joe Biden, Green Energy, Climate Change, Cryptocurrency, etc. If multiple parameters are passed, they will be applied as OR operations. More ➜"},"linkTo":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Returns only articles that point to specified links (as determined by the 'links' field in the article response)."},"showReprints":{"type":"boolean","default":true,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Whether to return reprints in the response or not. Reprints are usually wired articles from sources like AP or Reuters that are reprinted in multiple sources at the same time. By default, this parameter is 'true'."},"reprintGroupId":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Shows all articles belonging to the same reprint group. A reprint group includes one original article (the first one processed by the API) and all its known reprints."},"city":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters articles where a specified city plays a central role in the content, beyond mere mentions, to ensure the results are deeply relevant to the urban area in question. If multiple parameters are passed, they will be applied as OR operations."},"area":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters articles where a specified area, such as a neighborhood, borough, or district, plays a central role in the content, beyond mere mentions, to ensure the results are deeply relevant to the area in question. If multiple parameters are passed, they will be applied as OR operations."},"state":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters articles where a specified state plays a central role in the content, beyond mere mentions, to ensure the results are deeply relevant to the state in question. If multiple parameters are passed, they will be applied as OR operations."},"locationsCountry":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters articles where a specified country plays a central role in the content, beyond mere mentions, to ensure the results are deeply relevant to the country in question. If multiple parameters are passed, they will be applied as OR operations."},"excludeLocationsCountry":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Excludes articles where a specified country plays a central role in the content, ensuring results are not deeply relevant to the country in question. If multiple parameters are passed, they will be applied as AND operations, excluding articles relevant to any of the specified countries."},"location":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Return all articles that have the specified location. Location attributes are delimited by ':' between key and value, and '::' between attributes. Example: 'city:New York::state:NY'."},"lat":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Latitude of the center point to search places"},"lon":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Longitude of the center point to search places"},"maxDistance":{"type":"integer","format":"int32","minimum":-2147483648,"maximum":2147483647,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Maximum distance (in km) from starting point to search articles by tagged places"},"sourceCity":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Find articles published by sources that are located within a given city."},"sourceCounty":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Find articles published by sources that are located within a given county."},"sourceCountry":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Find articles published by sources that are located within a given country. Must be 2 character country code (i.e. us, gb, etc)."},"country":{"type":"string","enum":["us","gb","de","it","fr","nl","se","dk","fi","hu","no","pl","pt","ru","ua","ch","br","nz","mx","au"],"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Country code to filter by country. If multiple parameters are passed, they will be applied as OR operations."},"sourceState":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Find articles published by sources that are located within a given state."},"sourceLon":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Latitude of the center point to search articles created by local publications."},"sourceLat":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Latitude of the center point to search articles created by local publications."},"sourceMaxDistance":{"type":"integer","format":"int32","minimum":-2147483648,"maximum":2147483647,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Maximum distance from starting point to search articles created by local publications."},"personWikidataId":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"List of person Wikidata IDs for filtering."},"personName":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"List of person names for exact matches. Boolean and complex logic is not supported on this paramter."},"companyId":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"List of company IDs to filter by."},"companyName":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Search by company name."},"companyDomain":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Search by company domains for filtering. E.g. companyDomain=apple.com."},"companySymbol":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Search by company symbols."},"page":{"type":"integer","format":"int32","minimum":-2147483648,"maximum":2147483647,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Zero-based page number. From 0 to 10000. See the Pagination section for limitations."},"size":{"type":"integer","format":"int32","minimum":-2147483648,"maximum":2147483647,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Number of articles returned per page, from 0 to 100."},"sortBy":{"type":"string","enum":["date","relevance","addDate","pubDate","refreshDate"],"default":"relevance","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"'relevance' to sort by relevance to the query, 'date' to sort by the publication date (desc), 'pubDate' is a synonym to 'date', 'addDate' to sort by 'addDate' field (desc), 'refreshDate' to sort by 'refreshDate' field (desc)."},"showNumResults":{"type":"boolean","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Whether to show the total number of all matched articles. Default value is false which makes queries a bit more efficient but also counts up to 10000 articles."},"positiveSentimentFrom":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters results with a sentiment score greater than or equal to the specified value, indicating positive sentiment. See the Article Data section in Docs for an explanation of scores."},"positiveSentimentTo":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters results with a sentiment score less than or equal to the specified value, indicating positive sentiment. See the Article Data section in Docs for an explanation of scores."},"neutralSentimentFrom":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters results with a sentiment score greater than or equal to the specified value, indicating neutral sentiment. Explanation of sentimental values can be found in Docs under the Article Data section."},"neutralSentimentTo":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters results with a sentiment score less than or equal to the specified value, indicating neutral sentiment. See the Article Data section in Docs for an explanation of scores."},"negativeSentimentFrom":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters results with a sentiment score greater than or equal to the specified value, indicating negative sentiment. See the Article Data section in Docs for an explanation of scores."},"negativeSentimentTo":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters results with a sentiment score less than or equal to the specified value, indicating negative sentiment. See the Article Data section in Docs for an explanation of scores."},"taxonomy":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters by Google Content Categories. This field will accept 1 or more categories, must pass the full name of the category. Example: taxonomy=/Finance/Banking/Other, /Finance/Investing/Funds"},"prefixTaxonomy":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters by Google Content Categories. This field will filter by the category prefix only. Example: prefixTaxonomy=/Finance"}},"required":["apiKey"]}]},"response":{"200":{"type":"object","properties":{"status":{"type":"integer","default":0,"examples":[200]},"numResults":{"type":"integer","default":0,"examples":[1]},"articles":{"type":"array","items":{"type":"object","properties":{"url":{"type":"string","examples":["https://decrypt.co/301053/nft-market-hits-three-year-low-in-trading-and-sales-report"]},"authorsByline":{"type":"string","examples":["Vismaya V"]},"articleId":{"type":"string","examples":["680d7893185c4357a9047332cf38206c"]},"clusterId":{"type":"string","examples":["37426b0543cb45e3a547695fd63e9919"]},"source":{"type":"object","properties":{"domain":{"type":"string","examples":["decrypt.co"]},"paywall":{"type":"boolean","default":true,"examples":[false]},"location":{"type":"object","properties":{"country":{"type":"string","examples":["us"]},"state":{"type":"string","examples":["NY"]},"city":{"type":"string","examples":["New York"]},"coordinates":{"type":"object","properties":{"lat":{"type":"number","default":0,"examples":[40.7127281]},"lon":{"type":"number","default":0,"examples":[-74.0060152]}}}}}}},"imageUrl":{"type":"string","examples":["https://cdn.decrypt.co/resize/1024/height/512/wp-content/uploads/2021/07/The-Bored-Ape-Yacht-Club-gID_7.jpeg"]},"country":{"type":"string","examples":["us"]},"language":{"type":"string","examples":["en"]},"pubDate":{"type":"string","examples":["2025-01-15T09:20:34+00:00"]},"addDate":{"type":"string","examples":["2025-01-15T09:27:57.156032+00:00"]},"refreshDate":{"type":"string","examples":["2025-01-15T09:27:57.156034+00:00"]},"score":{"type":"number","default":0,"examples":[52.79721]},"title":{"type":"string","examples":["NFT Market Hits Three-Year Low in Trading and Sales: Report"]},"description":{"type":"string","examples":["Annual NFT trading volumes fell by 19%, while sales counts dipped by 18% compared to 2023, according to DappRadar."]},"content":{"type":"string","examples":["The NFT market suffered a dismal 2024, with trading volumes and sales counts dropping to their weakest levels since 2020.\n\nAnnual trading volumes fell by 19%, while sales counts dipped by 18% compared to 2023, according to a report by blockchain analytics platform.\n\nDespite a surge in crypto market activity, driven by Bitcoin’s all-time highs and booming DeFi growth, NFTs appeared to struggle under the weight of their own inflated valuations.\n\nEarly in the year, NFT trading volumes reached $5.3 billion in Q1, a modest 4% increase compared to the same period in 2023.\n\nHowever, this momentum proved fleeting, as volumes plummeted to $1.5 billion in Q3 before recovering slightly to $2.6 billion in Q4.\n\nEven with these fluctuations, annual sales counts fell sharply, pointing to a broader trend: while individual NFTs became more expensive in line with rising crypto token prices, overall market engagement dwindled.\n\nYuga Labs’ flagship collections Bored Ape Yacht Club (BAYC) and Mutant Ape Yacht Club (MAYC) hit historic lows, with floor prices dropping to 15 ETH and 2.4 ETH, respectively.\n\nEven Otherdeeds for Yuga Labs' Otherside metaverse plummeted to 0.23 ETH, a far cry from their initial minting price, exposing cracks in Yuga’s high-priced, membership-driven model.\n\nThis coincided with DappRadar’s observation that “Perhaps 2024 helped us realize that NFTs don’t need to be expensive to prove their importance in the broader Web3 ecosystem,” a critique of the market’s reliance on exclusivity and inflated pricing.\n\nAmid this downturn, the NFT market witnessed a paradox in November when CryptoPunk #8348, a rare seven-trait collectible from the NFT collection, was collateralized for a $2.75 million loan via the NFT lending platform GONDI.\n\nTouted as a milestone for NFTs as financial assets, this event showed speculative excess when juxtaposed with DappRadar’s insights about affordability and utility.\n\nWhile high-profile transactions like this aim to affirm NFTs’ value, they also highlight a market still driven by exclusivity and inflated pricing, even as wider participation wanes.\n\nEven within the struggling sector, blue-chip collections like CryptoPunks defied trends, nearly doubling in USD value in 2024 with notable sales driving brief recovery periods.\n\nNFT platforms like Blur dominated marketplace activity, leveraging zero-fee trading and aggressive airdrop campaigns to capture the largest share of trading volumes.\n\nIn contrast, rival marketplace OpenSea struggled with regulatory headwinds and declining market sentiment, forcing significant layoffs by year-end.\n\nBy Q4, Blur and OpenSea were neck-and-neck in market share, but Blur’s ability to generate high activity from a smaller, more active user base gave it the edge, as per the report.\n\nWhile trading volumes in late 2024 hinted at a potential recovery—November sales hit $562 million, the highest since May—the overall trajectory suggests that affordability, accessibility, and utility will be critical for sustained growth in 2025."]},"medium":{"type":"string","examples":["Article"]},"links":{"type":"array","items":{"type":"string","examples":["https://dappradar.com/blog/dapp-industry-report-2024-overview"]}},"labels":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string","examples":["Roundup"]}}}},"matchedAuthors":{"type":"array","items":{"type":"object","properties":{"id":{},"name":{"type":"string","examples":["Vismaya V"]}}}},"claim":{"type":"string","examples":[""]},"verdict":{"type":"string","examples":[""]},"keywords":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string","examples":["NFT trading volumes"]},"weight":{"type":"number","default":0,"examples":[0.095650345]}}}},"topics":{"type":"array","items":{}},"categories":{"type":"array","items":{}},"taxonomies":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string","examples":["/Finance/Investing/Currencies & Foreign Exchange"]}}}},"entities":{"type":"array","items":{"type":"object","properties":{"data":{"type":"string","examples":["Yuga Labs’"]},"type":{"type":"string","examples":["ORG"]},"mentions":{"type":"integer","default":0,"examples":[3]}}}},"companies":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","examples":["f0886b1323a142df88f521ba9a0bbedf"]},"name":{"type":"string","examples":["OpenSea Ventures"]},"domains":{"type":"array","items":{"type":"string","examples":["opensea.io"]}},"symbols":{"type":"array","items":{}}}}},"sentiment":{"type":"object","properties":{"positive":{"type":"number","default":0,"examples":[0.033333376]},"negative":{"type":"number","default":0,"examples":[0.89130986]},"neutral":{"type":"number","default":0,"examples":[0.07535672]}}},"summary":{"type":"string","examples":["The National Finance Finance (NFT) market experienced a three-year low in 2024, with annual trading volumes and sales counts dropping to their lowest levels since 2020. The report by blockchain analytics platform DappRadar suggests that despite a surge in crypto market activity driven by Bitcoin's all-time highs and DeFi growth, NFTs struggled under the weight of their inflated valuations. Despite early Q1 trading volumes reaching $5.3 billion, a 4% increase compared to the same period in 2023, volumes dropped to $1.5 billion in Q3 before recovering to $2.6 billion by Q4. Despite these fluctuations, overall market engagement decreased. Despite this downturn, high-profile transactions like CryptoPunk #8348, a rare seven-trait collectible from the NFT collection, were seen as a milestone for NFT's value and highlighted a market still driven by exclusivity and inflated pricing."]},"translation":{"type":"string","examples":[""]},"translatedTitle":{"type":"string","examples":[""]},"translatedDescription":{"type":"string","examples":[""]},"translatedSummary":{"type":"string","examples":[""]},"locations":{"type":"array","items":{}},"reprint":{"type":"boolean","default":true,"examples":[false]},"reprintGroupId":{"type":"string","examples":["3d67e5bf389b40b3895ae0708f4dd208"]},"places":{"type":"array","items":{}},"people":{"type":"array","items":{}}}}}},"$schema":"https://json-schema.org/draft/2020-12/schema#"},"400":{"$schema":"https://json-schema.org/draft/2020-12/schema#"},"401":{"$schema":"https://json-schema.org/draft/2020-12/schema#"},"403":{"$schema":"https://json-schema.org/draft/2020-12/schema#"},"404":{"$schema":"https://json-schema.org/draft/2020-12/schema#"},"500":{"$schema":"https://json-schema.org/draft/2020-12/schema#"}}} as const +; +const Stories1 = {"metadata":{"allOf":[{"type":"object","properties":{"apiKey":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#"},"q":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Search story by name, summary and key points. Preference is given to the name field. Supports complex query syntax, same way as **q** parameter from **/all** endpoint."},"name":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Search story by name. Supports complex query syntax, same way as **q** parameter from **/all** endpoint."},"topic":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter by topics. Each topic is some kind of entity that the article is about. Examples of topics: Markets, Joe Biden, Green Energy, Climate Change, Cryptocurrency, etc. If multiple parameters are passed, they will be applied as OR operations. More ➜"},"category":{"type":"string","enum":["Politics","Tech","Sports","Business","Finance","Entertainment","Health","Weather","Lifestyle","Auto","Science","Travel","Environment","World","General","none"],"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter by categories. Categories are general themes that the article is about. Examples of categories: Tech, Politics, etc. If multiple parameters are passed, they will be applied as OR operations. Use 'none' to search uncategorized articles. More ➜"},"clusterId":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter to specific story. Passing a cluster ID will filter results to only the content found within the cluster. Multiple params could be passed."},"source":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter stories by sources that wrote articles belonging to this story. At least 1 article is required for story to match. Multiple parameters could be passed."},"sourceGroup":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter stories by sources that wrote articles belonging to this story. Source groups are expanded into a list of sources. At least 1 article by the source is required for story to match. Multiple params could be passed."},"personWikidataId":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"List of person Wikidata IDs for filtering. Filter is applied on topPeople field."},"personName":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"List of people names. Filtering is applied on topPeople field."},"companyId":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"List of company IDs for filtering. Filtering is applied to topCompanies field."},"companyName":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"List of company names for filtering. Filtering is applied on topCompanies field."},"companyDomain":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"List of company domains for filtering. Filtering is applied on topCompanies field."},"companySymbol":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"List of company tickers for filtering. Filtering is applied on topCompanies field."},"nameExists":{"type":"boolean","default":true,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Returns stories with name assigned. Defaults to true."},"from":{"type":"string","format":"date-time","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"'from' filter, will search stories created after the specified date, the date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2023-03-01T00:00:00"},"to":{"type":"string","format":"date-time","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"'to' filter, will search stories created before the specified date, the date could be passed as ISO or 'yyyy-mm-dd'. Add time in ISO format, ie. 2023-03-01T23:59:59"},"initializedFrom":{"type":"string","format":"date","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"'initializedFrom' filter, will search stories that became available after provided date"},"initializedTo":{"type":"string","format":"date","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"'initializedTo' filter, will search stories that became available before provided date"},"updatedFrom":{"type":"string","format":"date","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Will return stories with 'updatedAt' >= 'updatedFrom'."},"updatedTo":{"type":"string","format":"date","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Will return stories with 'updatedAt' <= 'updatedTo'."},"minClusterSize":{"type":"integer","format":"int32","default":5,"minimum":-2147483648,"maximum":2147483647,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter by minimum cluster size. Minimum cluster size filter applies to number of **unique** articles."},"maxClusterSize":{"type":"integer","format":"int32","minimum":-2147483648,"maximum":2147483647,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter by maximum cluster size. Maximum cluster size filter applies to number of **unique** articles in the cluster."},"state":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter local news by state. Applies only to local news, when this param is passed non-local news will not be returned. If multiple parameters are passed, they will be applied as OR operations."},"city":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter local news by city. Applies only to local news, when this param is passed non-local news will not be returned. If multiple parameters are passed, they will be applied as OR operations. More ➜"},"area":{"type":"array","items":{"type":"string"},"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filter local news by area. Applies only to local news, when this param is passed non-local news will not be returned. If multiple parameters are passed, they will be applied as OR operations."},"page":{"type":"integer","format":"int32","default":0,"minimum":-2147483648,"maximum":2147483647,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Zero-based page number. From 0 to 10000. See the Pagination section for limitations."},"size":{"type":"integer","format":"int32","default":10,"minimum":-2147483648,"maximum":2147483647,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Number of stories results per page, from 0 to 100."},"sortBy":{"type":"string","enum":["createdAt","updatedAt","count"],"default":"createdAt","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Sort stories by count, creation date, last updated date. By default is sorted by created at."},"showNumResults":{"type":"boolean","default":false,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Show total number of results. By default set to false, will cap result count at 10000."},"showDuplicates":{"type":"boolean","default":false,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Stories are deduplicated by default. If a story is deduplicated, all future articles are merged into the original story. *duplicateOf* field contains the original cluster Id. When *showDuplicates=true*, all stories are shown."},"positiveSentimentFrom":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters results with a sentiment score greater than or equal to the specified value, indicating positive sentiment. See the Article Data section in Docs for an explanation of scores."},"positiveSentimentTo":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters results with a sentiment score less than or equal to the specified value, indicating positive sentiment. See the Article Data section in Docs for an explanation of scores."},"neutralSentimentFrom":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters results with a sentiment score greater than or equal to the specified value, indicating neutral sentiment. Explanation of sentimental values can be found in Docs under the Article Data section."},"neutralSentimentTo":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters results with a sentiment score less than or equal to the specified value, indicating neutral sentiment. See the Article Data section in Docs for an explanation of scores."},"negativeSentimentFrom":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters results with a sentiment score greater than or equal to the specified value, indicating negative sentiment. See the Article Data section in Docs for an explanation of scores."},"negativeSentimentTo":{"type":"number","format":"float","minimum":-3.402823669209385e+38,"maximum":3.402823669209385e+38,"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters results with a sentiment score less than or equal to the specified value, indicating negative sentiment. See the Article Data section in Docs for an explanation of scores."},"country":{"type":"string","enum":["us","gb","de","it","fr","nl","se","dk","fi","hu","no","pl","pt","ru","ua","ch","br","nz","mx","au"],"$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Country code to filter by country. If multiple parameters are passed, they will be applied as OR operations."},"taxonomy":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters by Google Content Categories. This field will accept 1 or more categories, must pass the full name of the category. Example: taxonomy=/Finance/Banking/Other, /Finance/Investing/Funds"},"topTaxonomies":{"type":"string","$schema":"https://json-schema.org/draft/2020-12/schema#","description":"Filters by Google Content Categories. Highlights the top 3 categories in a cluster, ordered by count."}},"required":["apiKey"]}]},"response":{"200":{"$schema":"https://json-schema.org/draft/2020-12/schema#"},"400":{"type":"object","properties":{"status":{"type":"integer","default":0,"examples":[400]},"message":{"type":"string","examples":["Errors during parameter validation: \nError on parameter 'updatedFrom', invalid value 'test': Failed to convert property value of type 'java.lang.String' to required type 'java.time.OffsetDateTime' for property 'updatedFrom'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.gawq.api.formatting.DateTimeRequestParam java.time.OffsetDateTime] for value [test]; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [test]"]},"timestamp":{"type":"integer","default":0,"examples":[1730827027255]}},"$schema":"https://json-schema.org/draft/2020-12/schema#"}}} as const +; +export { AllNews, Stories1 } diff --git a/packages/perigon/types.ts b/packages/perigon/types.ts new file mode 100644 index 0000000..83c1620 --- /dev/null +++ b/packages/perigon/types.ts @@ -0,0 +1,13 @@ +import type { FromSchema } from 'json-schema-to-ts'; +import * as schemas from './schemas'; + +export type AllNewsMetadataParam = FromSchema; +export type AllNewsResponse200 = FromSchema; +export type AllNewsResponse400 = FromSchema; +export type AllNewsResponse401 = FromSchema; +export type AllNewsResponse403 = FromSchema; +export type AllNewsResponse404 = FromSchema; +export type AllNewsResponse500 = FromSchema; +export type Stories1MetadataParam = FromSchema; +export type Stories1Response200 = FromSchema; +export type Stories1Response400 = FromSchema; diff --git a/searxng_tester.mts b/searxng_tester.mts new file mode 100644 index 0000000..a5553a3 --- /dev/null +++ b/searxng_tester.mts @@ -0,0 +1,29 @@ +import { SearxngService, type SearxngServiceConfig, type SearxngSearchResult } from 'searxng'; + +const config: SearxngServiceConfig = { + baseURL: 'https://search-engine-gsio.fly.dev', + defaultSearchParams: { + format: 'json', + lang: 'auto', + }, + defaultRequestHeaders: { + 'Content-Type': 'application/json', + }, +}; + +const searxngService = new SearxngService(config); + +async function performSearch(query) { + try { + const results = await searxngService.search(query); + console.log(results); + return results; + } catch (error) { + console.error('Search failed:', error); + } +} + + +const results = await performSearch('dogs'); + +console.log(JSON.stringify(results)); \ No newline at end of file diff --git a/src/agents/crypto_market.rs b/src/agents/crypto_market.rs new file mode 100644 index 0000000..989dfb6 --- /dev/null +++ b/src/agents/crypto_market.rs @@ -0,0 +1,28 @@ +use tokio::process::Child; +use tracing; + +use crate::utils::utils::run_agent; + +pub async fn finance_query_agent(stream_id: &str, input: &str) -> Result { + run_agent(stream_id, input, "./packages/genaiscript/genaisrc/finance-query.genai.mts").await +} + + +// #[cfg(test)] +// mod tests { +// use std::fmt::Debug; +// use crate::agents::search::search_agent; +// +// #[tokio::test] // Mark the test function as async +// async fn test_search_execution() { +// let input = "Who won the 2024 presidential election?"; +// +// let mut command = search_agent("test-stream", input).await.unwrap(); +// +// // command.stdout.take().unwrap().read_to_string(&mut String::new()).await.unwrap(); +// // Optionally, you can capture and inspect stdout if needed: +// let output = command.wait_with_output().await.expect("Failed to wait for output"); +// println!("Stdout: {}", String::from_utf8_lossy(&output.stdout)); +// println!("Stderr: {}", String::from_utf8_lossy(&output.stderr)); +// } +// } diff --git a/src/agents/image_generator.rs b/src/agents/image_generator.rs new file mode 100644 index 0000000..a3502fc --- /dev/null +++ b/src/agents/image_generator.rs @@ -0,0 +1,10 @@ +use crate::utils::utils::run_agent; +use tokio::process::Child; + +pub async fn image_generator(stream_id: &str, input: &str) -> Result { + tracing::debug!( + "Running image generator, \ninput: {}", + input + ); + run_agent(stream_id, input, "./packages/genaiscript/genaisrc/image-generator.genai.mts").await +} diff --git a/src/agents/mod.rs b/src/agents/mod.rs new file mode 100644 index 0000000..a7ff97d --- /dev/null +++ b/src/agents/mod.rs @@ -0,0 +1,5 @@ +pub mod news; +pub mod scrape; +pub mod search; +pub mod image_generator; +pub mod crypto_market; diff --git a/src/agents/news.rs b/src/agents/news.rs new file mode 100644 index 0000000..74cb0cb --- /dev/null +++ b/src/agents/news.rs @@ -0,0 +1,6 @@ +use crate::utils::utils::run_agent; +use tokio::process::Child; + +pub async fn news_agent(stream_id: &str, input: &str) -> Result { + run_agent(stream_id, input, "./packages/genaiscript/genaisrc/news-search.genai.mts").await +} diff --git a/src/agents/scrape.rs b/src/agents/scrape.rs new file mode 100644 index 0000000..ecd16ac --- /dev/null +++ b/src/agents/scrape.rs @@ -0,0 +1,6 @@ +use crate::utils::utils::run_agent; +use tokio::process::Child; + +pub async fn scrape_agent(stream_id: &str, input: &str) -> Result { + run_agent(stream_id, input, "./packages/genaiscript/genaisrc/web-scrape.genai.mts").await +} diff --git a/src/agents/search.rs b/src/agents/search.rs new file mode 100644 index 0000000..de385c8 --- /dev/null +++ b/src/agents/search.rs @@ -0,0 +1,28 @@ +use tokio::process::Child; +use tracing; + +use crate::utils::utils::run_agent; + +pub async fn search_agent(stream_id: &str, input: &str) -> Result { + run_agent(stream_id, input, "./packages/genaiscript/genaisrc/web-search.genai.mts").await +} + + +#[cfg(test)] +mod tests { + use std::fmt::Debug; + use crate::agents::search::search_agent; + + #[tokio::test] + async fn test_search_execution() { + let input = "Who won the 2024 presidential election?"; + + let mut command = search_agent("test-stream", input).await.unwrap(); + + // command.stdout.take().unwrap().read_to_string(&mut String::new()).await.unwrap(); + // Optionally, you can capture and inspect stdout if needed: + let output = command.wait_with_output().await.expect("Failed to wait for output"); + println!("Stdout: {}", String::from_utf8_lossy(&output.stdout)); + println!("Stderr: {}", String::from_utf8_lossy(&output.stderr)); + } +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..6349d06 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,30 @@ +// src/config.rs +pub struct AppConfig { + pub env_vars: Vec, +} + + +impl AppConfig { + pub fn new() -> Self { + // Load .env file if it exists + match dotenv::dotenv() { + Ok(_) => tracing::debug!("Loaded .env file successfully"), + Err(e) => tracing::debug!("No .env file found or error loading it: {}", e), + } + + Self { + env_vars: vec![ + "OPENAI_API_KEY".to_string(), + "BING_SEARCH_API_KEY".to_string(), + "TAVILY_API_KEY".to_string(), + "GENAISCRIPT_MODEL_LARGE".to_string(), + "GENAISCRIPT_MODEL_SMALL".to_string(), + "SEARXNG_API_BASE_URL".to_string(), + ], + } + } + + pub fn get_env_var(&self, key: &str) -> String { + std::env::var(key).unwrap_or_default() + } +} \ No newline at end of file diff --git a/src/genaiscript.rs b/src/genaiscript.rs new file mode 100644 index 0000000..dd9cdfa --- /dev/null +++ b/src/genaiscript.rs @@ -0,0 +1,90 @@ +use std::collections::HashMap; +use std::path::PathBuf; +use tokio::process::{Child, Command}; +use tracing; + +const DEFAULT_ENV_VARS: [&str; 4] = [ + "OPENAI_API_KEY", + "OPENAI_API_BASE", + "GENAISCRIPT_MODEL_LARGE", + "GENAISCRIPT_MODEL_SMALL", +]; + +pub struct GenAIScriptConfig { + script_path: PathBuf, + output_dir: PathBuf, + stream_id: String, + user_input: String, + retry_count: u32, + env_vars: HashMap, +} + +impl GenAIScriptConfig { + pub fn new(script_path: impl Into, stream_id: impl Into, user_input: impl Into) -> Self { + let mut env_vars = HashMap::new(); + + // Initialize with default environment variables + for var in DEFAULT_ENV_VARS { + if let Ok(value) = std::env::var(var) { + env_vars.insert(var.to_string(), value); + } + } + + Self { + script_path: script_path.into(), + output_dir: PathBuf::from("./web-agent-rs/output"), + stream_id: stream_id.into(), + user_input: user_input.into(), + retry_count: 0, + env_vars, + } + } + + pub fn with_output_dir(mut self, dir: impl Into) -> Self { + self.output_dir = dir.into(); + self + } + + pub fn with_retry_count(mut self, count: u32) -> Self { + self.retry_count = count; + self + } + + pub fn with_additional_env_vars(mut self, vars: HashMap) -> Self { + self.env_vars.extend(vars); + self + } +} + +pub async fn run_genaiscript(config: GenAIScriptConfig) -> Result { + tracing::debug!("Initiating GenAIScript for stream {}", config.stream_id); + + let output_path = config.output_dir.join(&config.stream_id); + + let mut command = Command::new("bunx"); + command + .arg("genaiscript") + .arg("run") + .arg(&config.script_path) + // .arg("--fail-on-errors") + .arg("—out-trace") + .arg(output_path) + .arg("--retry") + .arg(config.retry_count.to_string()) + .arg("--vars") + .arg(format!("USER_INPUT='{}'", config.user_input)); + + // Add environment variables + for (key, value) in config.env_vars { + command.env(key, value); + } + + command + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::inherit()) + .spawn() + .map_err(|e| { + tracing::error!("Failed to spawn genaiscript process: {}", e); + e.to_string() + }) +} \ No newline at end of file diff --git a/src/handlers/error.rs b/src/handlers/error.rs new file mode 100644 index 0000000..8b08792 --- /dev/null +++ b/src/handlers/error.rs @@ -0,0 +1,17 @@ +// src/handlers/error.rs +use axum::{ + http::StatusCode, + Json, + response::IntoResponse, +}; + +pub async fn handle_not_found() -> impl IntoResponse { + tracing::warn!("404 Not Found error occurred"); + + let error_response = serde_json::json!({ + "error": "Route Not Found", + "status": 404 + }); + + (StatusCode::NOT_FOUND, Json(error_response)) +} \ No newline at end of file diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs new file mode 100644 index 0000000..506514d --- /dev/null +++ b/src/handlers/mod.rs @@ -0,0 +1,7 @@ + +// src/handlers/mod.rs +pub mod error; +pub mod status; +pub mod stream; +pub mod ui; +pub mod webhooks; \ No newline at end of file diff --git a/src/handlers/status.rs b/src/handlers/status.rs new file mode 100644 index 0000000..1bb1b56 --- /dev/null +++ b/src/handlers/status.rs @@ -0,0 +1,5 @@ +// src/handlers/status.rs +pub async fn handle_status() -> &'static str { + tracing::debug!("Status check requested"); + "Server is running" +} \ No newline at end of file diff --git a/src/handlers/stream.rs b/src/handlers/stream.rs new file mode 100644 index 0000000..c01cddd --- /dev/null +++ b/src/handlers/stream.rs @@ -0,0 +1,82 @@ +use axum::{ + body::Body, + http::StatusCode, + response::{IntoResponse, Response}, +}; +use futures::StreamExt; +use tokio_util::io::ReaderStream; + +pub async fn handle_stream() -> impl IntoResponse { + use tokio::process::Command; + + let user_input = "Who won the 2024 election?"; + tracing::debug!("Handling stream request with input: {}", user_input); + + // Check environment variables + for env_var in ["OPENAI_API_KEY", "BING_SEARCH_API_KEY", "TAVILY_API_KEY"] { + if std::env::var(env_var).is_ok() { + tracing::debug!("{} is set", env_var); + } else { + tracing::warn!("{} is not set", env_var); + } + } + + let mut cmd = match Command::new("genaiscript") + .arg("run") + .arg("genaisrc/web-search.genai.mts") + .arg("--vars") + .arg(format!("USER_INPUT='{}'", user_input)) + .env("OPENAI_API_KEY", std::env::var("OPENAI_API_KEY").unwrap_or_default()) + .env("BING_SEARCH_API_KEY", std::env::var("BING_SEARCH_API_KEY").unwrap_or_default()) + .env("TAVILY_API_KEY", std::env::var("TAVILY_API_KEY").unwrap_or_default()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .spawn() { + Ok(cmd) => { + tracing::debug!("Successfully spawned genaiscript process"); + cmd + } + Err(e) => { + tracing::error!("Failed to spawn genaiscript process: {}", e); + return Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from("Failed to start process")) + .unwrap(); + } + }; + + let stdout = match cmd.stdout.take() { + Some(stdout) => { + tracing::debug!("Successfully captured stdout from process"); + stdout + } + None => { + tracing::error!("Failed to capture stdout from process"); + return Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from("Failed to capture process output")) + .unwrap(); + } + }; + + let reader = tokio::io::BufReader::new(stdout); + let stream = ReaderStream::new(reader); + let mapped_stream = stream.map(|r| { + match r { + Ok(bytes) => { + tracing::trace!("Received {} bytes from stream", bytes.len()); + Ok(bytes) + } + Err(e) => { + tracing::error!("Error reading from stream: {}", e); + Err(e) + } + } + }); + + tracing::debug!("Setting up SSE response"); + Response::builder() + .header("Content-Type", "text/event-stream") + .body(Body::from_stream(mapped_stream)) + .unwrap() +} \ No newline at end of file diff --git a/src/handlers/ui.rs b/src/handlers/ui.rs new file mode 100644 index 0000000..bcf5967 --- /dev/null +++ b/src/handlers/ui.rs @@ -0,0 +1,34 @@ +use axum::{ + body::Body, + http::{StatusCode, header::CONTENT_TYPE}, + response::{IntoResponse, Response}, +}; +use rust_embed::RustEmbed; +use tracing::{debug, error}; + +#[derive(RustEmbed)] +#[folder = "assets/"] +struct Asset; + +pub async fn serve_ui() -> impl IntoResponse { + debug!("Serving UI request"); + + // Attempt to retrieve the embedded "index.html" + match Asset::get("index.html") { + Some(content) => { + debug!("Successfully retrieved index.html"); + Response::builder() + .status(StatusCode::OK) + .header(CONTENT_TYPE, "text/html") + .body(Body::from(content.data)) + .unwrap() + } + None => { + error!("index.html not found in embedded assets"); + Response::builder() + .status(StatusCode::NOT_FOUND) + .body(Body::from("404 Not Found")) + .unwrap() + } + } +} \ No newline at end of file diff --git a/src/handlers/webhooks.rs b/src/handlers/webhooks.rs new file mode 100644 index 0000000..88fbd91 --- /dev/null +++ b/src/handlers/webhooks.rs @@ -0,0 +1,261 @@ +use crate::agents; +use crate::agents::news::news_agent; +use crate::agents::scrape::scrape_agent; +use crate::agents::search::search_agent; +use axum::response::Response; +use axum::{ + body::Body, extract::Path, extract::Query, http::StatusCode, response::IntoResponse, Json, +}; +use bytes::Bytes; +use futures::stream::{Stream, StreamExt}; +use lazy_static::lazy_static; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sled; +use std::pin::Pin; +use std::sync::Arc; +use std::time::Duration; +use tokio::io::{AsyncBufReadExt, BufReader}; +use tokio::process::Command; +use tokio::sync::Mutex; +use crate::agents::crypto_market::finance_query_agent; +use crate::agents::image_generator::image_generator; + +// init sled +lazy_static! { + static ref DB: Arc> = Arc::new(Mutex::new( + sled::open("./web-agent-rs/db/stream_store").expect("Failed to open sled database") + )); +} + +pub async fn handle_webhooks(Path(stream_id): Path) -> impl IntoResponse { + let db = DB.lock().await; + match db.get(&stream_id) { + Ok(Some(data)) => { + + let mut info: StreamInfo = match serde_json::from_slice(&data) { + Ok(info) => info, + Err(e) => { + tracing::error!("Failed to deserialize StreamInfo: {}", e); + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } + }; + + + // Increment the call_count in the database + info.call_count += 1; + let updated_info_bytes = match serde_json::to_vec(&info) { + Ok(data) => data, + Err(e) => { + tracing::error!("Failed to serialize updated StreamInfo: {}", e); + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } + }; + + match db.insert(&stream_id, updated_info_bytes) { + Ok(_) => { + if let Err(e) = db.flush_async().await { + tracing::error!("Failed to persist updated call_count to the database: {}", e); + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } + } + Err(e) => { + tracing::error!("Failed to update call_count in the database: {}", e); + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } + }; + + let info: StreamInfo = match db.get(&stream_id) { + Ok(Some(updated_data)) => match serde_json::from_slice(&updated_data) { + Ok(info) => info, + Err(e) => { + tracing::error!("Failed to deserialize updated StreamInfo: {}", e); + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } + }, + Ok(None) => { + tracing::error!("Stream ID not found after update: {}", stream_id); + return StatusCode::NOT_FOUND.into_response(); + } + Err(e) => { + tracing::error!("Failed to fetch updated record from DB: {}", e); + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } + }; + + if(info.call_count > 1) { + return StatusCode::OK.into_response(); + } + + let resource = info.resource; + let input = serde_json::to_string(&info.payload.input).unwrap_or_default(); + + tracing::debug!( + "Processing webhook - Resource: {}, Stream ID: {}", + resource, + stream_id + ); + + let cmd = match resource.as_str() { + "web-search" => search_agent(stream_id.as_str(), &*input).await, + "news-search" => news_agent(stream_id.as_str(), &*input).await, + "image-generator" => image_generator(stream_id.as_str(), &*input).await, + "finance-query" => finance_query_agent(stream_id.as_str(), &*input).await, + "web-scrape" => scrape_agent(stream_id.as_str(), &*input).await, + _ => { + tracing::error!("Unsupported resource type: {}", resource); + return StatusCode::BAD_REQUEST.into_response(); + } + }; + + let mut cmd = match cmd { + Ok(cmd) => cmd, + Err(e) => { + tracing::error!("Agent execution failed: {}", e); + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } + }; + + let stdout = match cmd.stdout.take() { + Some(stdout) => stdout, + None => { + tracing::error!("No stdout available for the command."); + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } + }; + + let reader = BufReader::new(stdout); + let sse_stream = reader_to_stream(reader, stream_id.clone()); + + return Response::builder() + .header("Content-Type", "text/event-stream") + .header("Cache-Control", "no-cache, no-transform") + .header("Connection", "keep-alive") + .header("X-Accel-Buffering", "yes") + .body(Body::from_stream(sse_stream)) + .unwrap() + } + Ok(None) => { + tracing::error!("Stream ID not found: {}", stream_id); + StatusCode::NOT_FOUND.into_response() + } + Err(e) => { + tracing::error!("Failed to fetch from DB: {}", e); + StatusCode::INTERNAL_SERVER_ERROR.into_response() + } + } +} + +fn reader_to_stream( + reader: BufReader, + stream_id: String, +) -> Pin> + Send>> +where + R: tokio::io::AsyncRead + Unpin + Send + 'static, +{ + let stream = futures::stream::unfold(reader, move |mut reader| async move { + let mut line = String::new(); + match reader.read_line(&mut line).await { + Ok(0) => None, + Ok(_) => Some(( + Ok(Bytes::from(format!("data: {}\n\n", line.trim()))), + reader, + )), + Err(e) => Some((Err(e), reader)), + } + }); + + let stream_with_done = stream.chain(futures::stream::once(async { + Ok(Bytes::from("data: [DONE]\n\n")) + })); + + Box::pin(stream_with_done) +} + +#[derive(Deserialize, Serialize, Debug)] +struct Payload { + input: Value, +} + +#[derive(Serialize, Deserialize, Debug)] +struct StreamInfo { + resource: String, + payload: Payload, + parent: String, + call_count: i32, +} + + +#[derive(Deserialize, Serialize, Debug)] +pub struct WebhookPostRequest { + id: String, + resource: String, + payload: Payload, + parent: String, +} + +#[derive(Deserialize, Serialize, Debug)] +struct WebhookPostResponse { + stream_url: String, +} + +pub async fn handle_webhooks_post(Json(payload): Json) -> impl IntoResponse { + let db = DB.lock().await; + + tracing::info!("Received webhook post request with ID: {}", payload.id); + + let stream_id = payload.id.clone(); + let info = StreamInfo { + resource: payload.resource.clone(), + payload: payload.payload, + parent: payload.parent.clone(), + call_count: 0 + }; + + let info_bytes = match serde_json::to_vec(&info) { + Ok(data) => data, + Err(e) => { + tracing::error!("Failed to serialize StreamInfo: {}", e); + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } + }; + + // Use atomic compare_and_swap operation + match db.compare_and_swap( + &stream_id, + None as Option<&[u8]>, + Some(info_bytes.as_slice()), + ) { + Ok(_) => { + // Force an immediate sync to disk + match db.flush_async().await { + Ok(_) => { + // Verify the write by attempting to read it back + match db.get(&stream_id) { + Ok(Some(_)) => { + let stream_url = format!("/webhooks/{}", stream_id); + tracing::info!("Successfully created and verified stream URL: {}", stream_url); + Json(WebhookPostResponse { stream_url }).into_response() + }, + Ok(None) => { + tracing::error!("Failed to verify stream creation: {}", stream_id); + StatusCode::INTERNAL_SERVER_ERROR.into_response() + }, + Err(e) => { + tracing::error!("Error verifying stream creation: {}", e); + StatusCode::INTERNAL_SERVER_ERROR.into_response() + } + } + }, + Err(e) => { + tracing::error!("Failed to flush DB: {}", e); + StatusCode::INTERNAL_SERVER_ERROR.into_response() + } + } + } + Err(e) => { + tracing::error!("Failed to insert stream info: {}", e); + StatusCode::INTERNAL_SERVER_ERROR.into_response() + } + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..18c3a5c --- /dev/null +++ b/src/main.rs @@ -0,0 +1,43 @@ +// src/main.rs +use crate::config::AppConfig; +use crate::routes::create_router; +use crate::setup::init_logging; + +mod config; +mod routes; +mod setup; +mod handlers; +mod agents; +mod genaiscript; +mod utils; +mod session_identify; + +#[tokio::main] +async fn main() { + // Initialize logging + init_logging(); + + // Load configuration + let config = AppConfig::new(); + + // Create router with all routes + let app = create_router(); + + // Start core + let addr = "0.0.0.0:3006"; + tracing::info!("Attempting to bind core to {}", addr); + + let listener = match tokio::net::TcpListener::bind(addr).await { + Ok(l) => { + tracing::info!("Successfully bound to {}", l.local_addr().unwrap()); + l + } + Err(e) => { + tracing::error!("Failed to bind to {}: {}", addr, e); + panic!("Server failed to start"); + } + }; + + tracing::info!("Server starting on {}", listener.local_addr().unwrap()); + axum::serve(listener, app.into_make_service()).await.unwrap(); +} diff --git a/src/routes.rs b/src/routes.rs new file mode 100644 index 0000000..b6dc988 --- /dev/null +++ b/src/routes.rs @@ -0,0 +1,105 @@ +use crate::handlers::webhooks::handle_webhooks_post; +use crate::handlers::{ + error::handle_not_found, + ui::serve_ui + , + webhooks::handle_webhooks, +}; +use crate::session_identify::session_identify; +use axum::extract::Request; +use axum::response::Response; +use axum::routing::post; +// src/routes.rs +use axum::routing::{get, Router}; +use http::header::AUTHORIZATION; +use http::StatusCode; +use serde::{Deserialize, Serialize}; +use serde_json::Number; +use std::fmt; +use tower_http::trace::{self, TraceLayer}; +use tracing::Level; + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct CurrentUser { + pub(crate) sub: String, + pub name: String, + pub email: String, + pub exp: Number, + pub id: String, + pub aud: String, +} + +impl fmt::Display for CurrentUser { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "CurrentUser {{ id: {}, name: {}, email: {}, sub: {}, aud: {}, exp: {} }}", + self.id, self.name, self.email, self.sub, self.aud, self.exp + ) + } +} + +pub fn create_router() -> Router { + + Router::new() + .route("/", get(serve_ui)) + // request a stream resource + .route("/api/webhooks", post(handle_webhooks_post)) + // consume a stream resource + .route("/webhooks/:stream_id", get(handle_webhooks)) + .route_layer(axum::middleware::from_fn(auth)) + .route("/health", get(health)) + .layer( + TraceLayer::new_for_http() + .make_span_with(trace::DefaultMakeSpan::new().level(Level::INFO)) + .on_response(trace::DefaultOnResponse::new().level(Level::INFO)), + ) + // left for smoke testing + // .route("/api/status", get(handle_status)) + .fallback(handle_not_found) +} + +async fn health() -> String { + return "ok".to_string(); +} + +async fn auth(mut req: Request, next: axum::middleware::Next) -> Result { + let session_token_header = req + .headers() + .get(AUTHORIZATION) + .and_then(|header_value| header_value.to_str().ok()); + + let session_token_parts= session_token_header.expect("No credentials").split(" ").collect::>(); + + let session_token = session_token_parts.get(1); + + + // log::info!("session_token: {:?}", session_token); + + let session_token = session_token.expect("Unauthorized: No credentials supplied"); + + let result = + if let Some(current_user) = authorize_current_user(&*session_token).await { + // info!("current user: {}", current_user); + // insert the current user into a request extension so the handler can + // extract it + req.extensions_mut().insert(current_user); + Ok(next.run(req).await) + } else { + Err(StatusCode::UNAUTHORIZED) + }; + result +} + + +async fn authorize_current_user( + session_token: &str, +) -> Option { + let session_identity = session_identify(session_token) + .await + .unwrap(); + + // println!("current_user: {:?}", session_identity.user); + + Some(serde_json::from_value::(session_identity.user).unwrap()) +} \ No newline at end of file diff --git a/src/session_identify.rs b/src/session_identify.rs new file mode 100644 index 0000000..a70a8fd --- /dev/null +++ b/src/session_identify.rs @@ -0,0 +1,55 @@ +use anyhow::Result; +use serde_json::Value; +use serde_json::json; +use base64::Engine; +use fips204::ml_dsa_44::{PrivateKey, PublicKey}; +use fips204::traits::{SerDes, Signer, Verifier}; +use crate::utils::base64::B64_ENCODER; + +pub struct SessionIdentity { + pub message: String, + pub signature: String, + pub target: String, + pub session_id: String, + pub user: Value +} + +pub async fn session_identify(session_token: &str) -> Result { + let session_data_base64 = session_token.split('.').nth(0).ok_or_else(|| anyhow::anyhow!("Invalid session data format"))?; + // println!("session_data_base64: {}", session_data_base64); + let session_data: Value = serde_json::de::from_slice(&*B64_ENCODER.b64_decode_payload(session_data_base64).map_err(|e| anyhow::anyhow!("Failed to decode session data: {}", e))?).map_err(|e| anyhow::anyhow!("Failed to parse session data: {}", e))?; + // println!("session_data: {:?}", session_data); + + + let signature_base64 = session_token.split('.').nth(1).ok_or_else(|| anyhow::anyhow!("Invalid session token format"))?; + // println!("signature_base64: {}", signature_base64); + + let target = session_data.get("aud") + .and_then(|e| e.as_str()) + .ok_or_else(|| anyhow::anyhow!("Session data missing audience"))?; + + let target = target.parse::().map_err(|e| anyhow::anyhow!("Failed to parse target to String: {}", e))?; + + let session_id = session_data.get("id") + .and_then(|e| e.as_str()) + .ok_or_else(|| anyhow::anyhow!("Session data missing id"))?; + + let session_id = session_id.parse::().map_err(|e| anyhow::anyhow!("Failed to parse session_id to String: {}", e))?; + + // let request_payload: Value = json!({ + // "message": session_data_base64, + // "signature": signature_base64, + // "target": target, + // "session_id": session_id, + // }); + + let result = SessionIdentity { + message: session_data_base64.to_string(), + signature: signature_base64.to_string(), + target, + session_id, + user: session_data.clone() + }; + + Ok(result) +} \ No newline at end of file diff --git a/src/setup.rs b/src/setup.rs new file mode 100644 index 0000000..ddc7ad8 --- /dev/null +++ b/src/setup.rs @@ -0,0 +1,10 @@ +// src/setup.rs +pub fn init_logging() { + tracing_subscriber::fmt() + .with_max_level(tracing::Level::DEBUG) + .with_target(true) + .with_thread_ids(true) + .with_file(true) + .with_line_number(true) + .init(); +} \ No newline at end of file diff --git a/src/utils/base64.rs b/src/utils/base64.rs new file mode 100644 index 0000000..518db8a --- /dev/null +++ b/src/utils/base64.rs @@ -0,0 +1,65 @@ +use base64::Engine; +use base64::engine::GeneralPurpose; +use base64::engine::general_purpose::STANDARD; +use base64::engine::general_purpose::STANDARD_NO_PAD; + +pub struct Base64Encoder { + payload_engine: GeneralPurpose, + signature_engine: GeneralPurpose, + public_key_engine: GeneralPurpose, + secret_key_engine: GeneralPurpose, +} + +impl Base64Encoder { + pub(crate) fn b64_encode(&self, p0: &[u8]) -> String { + self.payload_engine.encode(p0) + } + pub(crate) fn b64_decode(&self, p0: String) -> Result, base64::DecodeError> { + self.payload_engine.decode(p0) + } +} + +pub const B64_ENCODER: &Base64Encoder = &Base64Encoder::new(); + +impl Base64Encoder { + pub const fn new() -> Self { // Made new() a const fn + Base64Encoder { + payload_engine: STANDARD, + signature_engine: STANDARD, + public_key_engine: STANDARD, + secret_key_engine: STANDARD, + } + } + + pub fn b64_encode_payload>(&self, input: T) -> String { // Added trait bound + self.payload_engine.encode(input) + } + + pub fn b64_decode_payload>(&self, input: T) -> Result, base64::DecodeError> { // Added trait bound + self.payload_engine.decode(input) + } + + pub fn b64_decode_signature>(&self, input: T) -> Result, base64::DecodeError> { // Added trait bound + self.signature_engine.decode(input) + } + + pub fn b64_encode_signature>(&self, input: T) -> String { // Added trait bound + self.signature_engine.encode(input) + } + + pub fn b64_encode_public_key>(&self, input: T) -> String { // Added trait bound + self.public_key_engine.encode(input) + } + + pub fn b64_decode_public_key>(&self, input: T) -> Result, base64::DecodeError> { // Added trait bound + self.public_key_engine.decode(input) + } + + pub fn b64_encode_secret_key>(&self, input: T) -> String { // Added trait bound + self.secret_key_engine.encode(input) + } + + pub fn b64_decode_secret_key>(&self, input: T) -> Result, base64::DecodeError> { // Added trait bound + self.secret_key_engine.decode(input) + } +} diff --git a/src/utils/mod.rs b/src/utils/mod.rs new file mode 100644 index 0000000..021524b --- /dev/null +++ b/src/utils/mod.rs @@ -0,0 +1,2 @@ +pub mod utils; +pub mod base64; diff --git a/src/utils/utils.rs b/src/utils/utils.rs new file mode 100644 index 0000000..5e2b2ab --- /dev/null +++ b/src/utils/utils.rs @@ -0,0 +1,80 @@ +// utils.rs +use tokio::process::{Child, Command}; // Use tokio::process::Child and Command +use std::env; +use tokio::time::{timeout, Duration}; +use tracing; + + +pub struct ShimBinding { + user_input: String, + file_path: String, // Add new field for the file path + openai_api_key: String, + openai_api_base: String, + bing_search_api_key: String, + perigon_api_key: String, + tavily_api_key: String, + genaiscript_model_large: String, + genaiscript_model_small: String, + searxng_api_base_url: String, + searxng_password: String, +} + +impl ShimBinding { + pub fn new(user_input: String, file_path: String) -> Self { // Update constructor to take file path + Self { + user_input, + file_path, // Initialize the new field + openai_api_key: env::var("OPENAI_API_KEY").unwrap_or_default(), + openai_api_base: env::var("OPENAI_API_BASE").unwrap_or_default(), + bing_search_api_key: env::var("BING_SEARCH_API_KEY").unwrap_or_default(), + tavily_api_key: env::var("TAVILY_API_KEY").unwrap_or_default(), + genaiscript_model_large: env::var("GENAISCRIPT_MODEL_LARGE").unwrap_or_default(), + genaiscript_model_small: env::var("GENAISCRIPT_MODEL_SMALL").unwrap_or_default(), + perigon_api_key: env::var("PERIGON_API_KEY").unwrap_or_default(), + searxng_api_base_url: env::var("SEARXNG_API_BASE_URL").unwrap_or_default(), + searxng_password: env::var("SEARXNG_PASSWORD").unwrap_or_default(), + } + } + + pub fn execute(&self) -> std::io::Result { + let mut command = Command::new("./dist/genaiscript-rust-shim.js"); + command + .arg("--file") + .arg(&self.file_path) // Use the file_path field instead of hardcoded value + .arg(format!("USER_INPUT={}", self.user_input)) + .env("OPENAI_API_KEY", &self.openai_api_key) + .env("OPENAI_API_BASE", &self.openai_api_base) + .env("BING_SEARCH_API_KEY", &self.bing_search_api_key) + .env("TAVILY_API_KEY", &self.tavily_api_key) + .env("GENAISCRIPT_MODEL_LARGE", &self.genaiscript_model_large) + .env("GENAISCRIPT_MODEL_SMALL", &self.genaiscript_model_small) + .env("PERIGON_API_KEY", &self.perigon_api_key) + .env("SEARXNG_API_BASE_URL", &self.searxng_api_base_url) + .env("SEARXNG_PASSWORD", &self.searxng_password) + .stdout(std::process::Stdio::piped()) // Use tokio::io::Stdio::piped() + .stderr(std::process::Stdio::inherit()); // Use tokio::io::Stdio::piped() + + command.spawn() + } +} + + + /// Generic helper to execute a ShimBinding-based agent with a timeout +pub async fn run_agent(stream_id: &str, input: &str, file_path: &str) -> Result { + tracing::debug!("Initiating agent for stream {} with file path {}", stream_id, file_path); + + let shim_binding = ShimBinding::new(input.to_string(), file_path.to_string()); + let spawn_future = async move { + match shim_binding.execute() { + Ok(child) => Ok(child), + Err(e) => { + tracing::error!("Failed to spawn shim process: {}", e); + Err(e.to_string()) + } + } + }; + + timeout(Duration::from_secs(10), spawn_future) + .await + .unwrap_or_else(|_| Err("Command timed out after 10 seconds".to_string())) +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..54f4023 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + // Enable latest features + "lib": ["ESNext", "DOM"], + "target": "ESNext", + "module": "ESNext", + "moduleDetection": "force", +// "jsx": "react-jsx", + "allowJs": true, + + // Bundler mode + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "noEmit": true, + + // Best practices + "strict": true, + "skipLibCheck": true, + "noFallthroughCasesInSwitch": true, + + // Some stricter flags (disabled by default) + "noUnusedLocals": false, + "noUnusedParameters": false, + "noPropertyAccessFromIndexSignature": false + }, + "include": [ + "./packages/genaiscript/genaisrc/genaiscript.d.ts" + ] +}