### Start Shared Session Example Source: https://hexdocs.pm/req_cassette/ReqCassette.Session.html An example demonstrating how to start a shared session, use it with `with_cassette/3`, and ensure it's ended properly. ```elixir session = ReqCassette.Session.start_shared_session() try do with_cassette("test", [session: session], fn plug -> Task.async(fn -> Req.post!(..., plug: plug) end) |> Task.await() end) after ReqCassette.Session.end_shared_session(session) end ``` -------------------------------- ### Install Req with Mix.install Source: https://hexdocs.pm/req/index.html Install the Req library using Mix.install for quick setup in Elixir projects. This example also shows a basic GET request to fetch repository description. ```elixir Mix.install([ {:req, ">= 0.5.0"} ]) Req.get!("https://api.github.com/repos/wojtekmach/req").body["description"] #=> "Req is a batteries-included HTTP client for Elixir." ``` -------------------------------- ### ReqToggl Development Setup Source: https://hexdocs.pm/req_toggl/readme.html Commands for setting up the development environment, including installing dependencies, compiling, and running tests. ```bash # Install dependencies mix deps.get # Compile mix compile # Run tests mix test ``` -------------------------------- ### Setup ReqS3 Source: https://hexdocs.pm/req_s3/mnist.html Installs the ReqS3 library and initializes a Req client with S3 capabilities. ```APIDOC ## Setup Install the necessary library: ```elixir Mix.install([ {:req_s3, "~> 0.2.3"} ]) ``` Initialize a Req client with S3 support: ```elixir req = Req.new() |> ReqS3.attach() ``` ``` -------------------------------- ### Direct Mint Request Examples Source: https://hexdocs.pm/req_client/ReqClient.Adapter.Mint.html Examples demonstrating direct use of the Mint adapter for GET requests. Use `wrap: :mint` to ensure the request is handled by the Mint adapter. ```elixir Rc.get! :l, debug: true, wrap: :mint ``` ```elixir Rc.get! :x, debug: true, wrap: :mint ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://hexdocs.pm/req_llm/contributing.html Initial setup steps for the ReqLLM project, including cloning the repository and fetching project dependencies. ```bash git clone https://github.com/agentjido/req_llm.git cd req_llm mix deps.get ``` -------------------------------- ### Quick Start with ReqToggl Source: https://hexdocs.pm/req_toggl/readme.html Demonstrates creating a client, fetching user info to get the workspace ID, listing projects, and creating a time entry. ```elixir # Create a client with your API token client = ReqToggl.new(api_token: System.fetch_env!("TOGGL_API_TOKEN")) # Get your workspace ID {:ok, %{body: user}} = ReqToggl.get_me(client) workspace_id = user["default_workspace_id"] # List all projects {:ok, %{body: projects}} = ReqToggl.list_projects(client, workspace_id) # Create a time entry {:ok, %{body: entry}} = ReqToggl.create_time_entry(client, workspace_id: workspace_id, project_id: 12345, date: "2024-01-15", start_time: "09:00", end_time: "17:00", description: "Working on features" ) ``` -------------------------------- ### Example HTTP GET Request Source: https://hexdocs.pm/req_client/ReqClient.Channel.Httpc.html Demonstrates a basic GET request to a specified URL. No special setup is required beyond importing the module. ```elixir Hc.get "https://slink.fly.dev/api/ping" ``` -------------------------------- ### Install and Use Req Plugins Source: https://hexdocs.pm/req/changelog.html Shows how to install and attach multiple Req plugins like `req_easyhtml`, `req_s3`, `req_hex`, and `req_github_oauth` to extend Req's functionality. Examples demonstrate fetching data from different sources using these plugins. ```elixir Mix.install([ {:req, "~> 0.3.0"}, {:req_easyhtml, github: "wojtekmach/req_easyhtml"}, {:req_s3, github: "wojtekmach/req_s3"}, {:req_hex, github: "wojtekmach/req_hex"}, {:req_github_oauth, github: "wojtekmach/req_github_oauth"} ]) req = (Req.new(http_errors: :raise) |> ReqEasyHTML.attach() |> ReqS3.attach() |> ReqHex.attach() |> ReqGitHubOAuth.attach()) Req.get!(req, url: "https://elixir-lang.org").body[".entry-summary h5"] #=> # #EasyHTML[
# Elixir is a dynamic, functional language for building scalable and maintainable applications. #
] Req.get!(req, url: "s3://ossci-datasets").body #=> # [ # "mnist/", # "mnist/t10k-images-idx3-ubyte.gz", # "mnist/t10k-labels-idx1-ubyte.gz", # "mnist/train-images-idx3-ubyte.gz", # "mnist/train-labels-idx1-ubyte.gz" # ] Req.get!(req, url: "https://repo.hex.pm/tarballs/req-0.1.0.tar").body["metadata.config"]["links"] #=> %{"GitHub" => "https://github.com/wojtekmach/req"} Req.get!(req, url: "https://api.github.com/user").body["login"] ``` -------------------------------- ### Basic Cassette Templating Setup Source: https://hexdocs.pm/req_cassette/templating.html Use this basic setup to start with parameterized cassettes. It defines a pattern to extract numerical IDs for templating. ```Elixir with_cassette "my_test", [template: [patterns: [id: ~r/\d+/]]], fn plug -> # Your test here end ``` -------------------------------- ### Create App and Wait, Create Machine and Wait Examples Source: https://hexdocs.pm/req_fly/ReqFly.Orchestrator.html Demonstrates creating a Fly.io app and waiting for it to become active, and creating a machine and waiting for it to start. Requires Req.new() with ReqFly attached. ```elixir req = Req.new() |> ReqFly.attach(token: "fly_token") # Create app and wait for it to become active {:ok, app} = ReqFly.Orchestrator.create_app_and_wait(req, app_name: "my-app", org_slug: "my-org", timeout: 120 ) # Create machine and wait for it to start config = %{ image: "flyio/hellofly:latest", guest: %{cpus: 1, memory_mb: 256} } {:ok, machine} = ReqFly.Orchestrator.create_machine_and_wait(req, app_name: "my-app", config: config, state: "started", timeout: 90 ) ``` -------------------------------- ### Database Creation and Migration Setup Source: https://hexdocs.pm/req_sandbox/usage.html Code to create the database if it doesn't exist, configure migrations, start the Ecto Repo and Phoenix Endpoint, and run migrations. ```elixir # Creates the guide's database. # It may already exist and that's okay. {:ok, pgx} = Postgrex.start_link( hostname: pg_host, username: pg_user, password: pg_pass, database: "" ) Postgrex.query(pgx, "CREATE DATABASE #{pg_db}", []) Process.unlink(pgx) Process.exit(pgx, :shutdown) # Configures migrations _ = Repo.__adapter__().storage_down(Repo.config()) :ok = Repo.__adapter__().storage_up(Repo.config()) # Starts the Repo and the Endpoint {:ok, _} = Supervisor.start_link([Repo, ReqSandboxGuide.Endpoint], strategy: :one_for_one) # Runs migrations Ecto.Migrator.run(Repo, [{0, Migration0}], :up, all: true, log_migrations_sql: :debug) ``` -------------------------------- ### Solution: Configure Cassette Path Builder and Set Context Source: https://hexdocs.pm/reqord/macro_support.html This example shows how to configure Reqord's `:cassette_path_builder` to use macro context and set the context in the `setup` block for each iteration. This ensures each model gets its own unique cassette file. ```elixir defmodule MyLLMTest do use Reqord.Case # 1. Configure path builder to use macro context setup_all do Application.put_env(:reqord, :cassette_path_builder, fn context -> model = get_in(context, [:macro_context, :model]) || "default" test = context.test |> Atom.to_string() "models/#{model}/#{test}" end) on_exit(fn -> Application.delete_env(:reqord, :cassette_path_builder) end) end # 2. Set context in setup for each iteration for model <- ["gpt-4", "gemini-flash"] do @model model describe "#{model}" do setup do Reqord.Case.set_cassette_context(%{model: @model}) :ok end test "generates text" do # Now each model gets its own cassette: # models/gpt-4/test_generates_text.jsonl # models/gemini-flash/test_generates_text.jsonl end end end end ``` -------------------------------- ### Install Reqord with Default Options Source: https://hexdocs.pm/reqord/Reqord.html Install the Reqord VCR stub using default matching (method + uri) and the `:once` record mode. This is the most common setup for strict replay. ```elixir Reqord.install!( name: MyApp.ReqStub, cassette: "my_test", mode: :once ) ``` -------------------------------- ### Create Machine and Wait Example Source: https://hexdocs.pm/req_fly/ReqFly.Orchestrator.html Creates a machine and waits for it to reach a desired state, defaulting to 'started'. Requires a Req.Request with ReqFly attached, app name, and machine configuration. Supports specifying region, state, and timeout. ```elixir req = Req.new() |> ReqFly.attach(token: "fly_token") config = %{ image: "flyio/hellofly:latest", guest: %{cpus: 1, memory_mb: 256} } # Create and wait for machine to start {:ok, machine} = ReqFly.Orchestrator.create_machine_and_wait(req, app_name: "my-app", config: config ) # Create and wait for specific state {:ok, machine} = ReqFly.Orchestrator.create_machine_and_wait(req, app_name: "my-app", config: config, state: "stopped", timeout: 90 ) ``` -------------------------------- ### Example Usage of ReqToggl Functions Source: https://hexdocs.pm/req_toggl/ReqToggl.html Demonstrates creating a client, getting user info, listing projects, and creating a time entry. Ensure your TOGGL_API_TOKEN environment variable is set. ```elixir # Create a client client = ReqToggl.new(api_token: System.fetch_env!("TOGGL_API_TOKEN")) # Get current user info and workspace {:ok, %{body: user}} = Req.get(client, url: "/me") # List projects for a workspace {:ok, %{body: projects}} = ReqToggl.list_projects(client, workspace_id) # Create a time entry {:ok, %{body: entry}} = ReqToggl.create_time_entry(client, workspace_id: workspace_id, project_id: project_id, start: ~U[2024-01-15 09:00:00Z], stop: ~U[2024-01-15 17:00:00Z], description: "Working on features" ) ``` -------------------------------- ### Use ExUnit Setup for Shared Sessions Source: https://hexdocs.pm/req_cassette/migration_v0-4_to_v0-5.html For cleaner tests, ExUnit's `setup` block can be used to manage shared sessions. The session is started before the test and cleaned up afterwards using `on_exit`. ```elixir defmodule MyApp.ParallelAPITest do use ExUnit.Case, async: true import ReqCassette setup do session = ReqCassette.start_shared_session() on_exit(fn -> ReqCassette.end_shared_session(session) end) %{session: session} end test "parallel API calls", %{session: session} do with_cassette "parallel_test", [session: session, sequential: true], fn plug -> tasks = Enum.map(1..3, fn i -> Task.async(fn -> make_request(plug, i) end) end) Task.await_many(tasks) end end end ``` -------------------------------- ### Configuration and Usage Example Source: https://hexdocs.pm/req_llm/google_vertex.html Example of how to configure and use a Google Vertex AI model with ReqLLM, specifying provider options. ```APIDOC ## Configuration Vertex AI uses Google Cloud OAuth2 authentication with service accounts. ### Service Account (Recommended) **Environment Variables:** ``` GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json" GOOGLE_CLOUD_PROJECT="your-project-id" GOOGLE_CLOUD_REGION="global" ``` **Provider Options:** ```elixir ReqLLM.generate_text( "google_vertex:claude-sonnet-4-5@20250929", "Hello", provider_options: [ service_account_json: "/path/to/service-account.json", project_id: "your-project-id", region: "global" ] ) ``` ``` -------------------------------- ### Example Usage of ReqClient.Channel.Mint Source: https://hexdocs.pm/req_client/ReqClient.Channel.Mint.html Demonstrates a basic example of using the ReqClient.Channel.Mint module. ```elixir eg. M.get :x ``` -------------------------------- ### Create User Message Examples Source: https://hexdocs.pm/req_llm/ReqLLM.Context.html Examples demonstrating how to use the `user/2` function with different argument types for content and metadata. ```elixir user("Hello") user("Hello", %{source: "api"}) user("Hello", metadata: %{source: "api"}) user([ContentPart.text("Hello")], metadata: %{}) ``` -------------------------------- ### start_profile! Source: https://hexdocs.pm/req_client/ReqClient.Channel.Httpc.html Starts a profile, which can be used to manage request options. A manager process for the default profile is started when the Inets application starts. ```APIDOC ## start_profile!(profile \\ random_profile_name()) ### Description When starting the Inets application, a manager process for the default profile is started. The functions in this API that do not explicitly use a profile accesses the default profile. ``` -------------------------------- ### Example Development Configuration Source: https://hexdocs.pm/req_llm/configuration.html Example configuration for a development environment, including shorter timeouts, debug mode, and enabling .env loading. ```elixir # config/dev.exs config :req_llm, receive_timeout: 60_000, debug: true, load_dotenv: true ``` -------------------------------- ### Install ReqLLM and Kino Source: https://hexdocs.pm/req_llm/getting-started-3.html Install the ReqLLM library and Kino for interactive Livebook features. This is the first step to using ReqLLM. ```elixir Mix.install([ {:req_llm, github: "agentjido/req_llm"}, {:kino, "~> 0.14.2"} ]) ``` -------------------------------- ### Initial Setup Workflow Source: https://hexdocs.pm/req_llm/mix-tasks.html For initial setup, first validate sample models by running `mix mc --sample`. Then, perform a quick generation test using `mix req_llm.gen "Hello, world!" --model openai:gpt-4o-mini`. ```shell # 1. Validate sample models mix mc --sample # 2. Test a quick generation mix req_llm.gen "Hello, world!" --model openai:gpt-4o-mini ``` -------------------------------- ### Install Dependencies with Mix Source: https://hexdocs.pm/req_llm/index.html Install project dependencies using the Mix build tool. ```bash # Install dependencies mix deps.get ``` -------------------------------- ### Start Machine with ReqFly Source: https://hexdocs.pm/req_fly/readme.html Start a previously created machine. The machine ID is required. ```elixir machine_id = machine["id"] # Start the machine {:ok, _} = ReqFly.Machines.start(req, app_name: "my-app", machine_id: machine_id) ``` -------------------------------- ### start(req, opts) Source: https://hexdocs.pm/req_fly/ReqFly.Machines.html Starts a stopped machine. This function is used to bring a machine back online after it has been stopped. ```APIDOC ## start(req, opts) ### Description Starts a stopped machine. ### Parameters #### Path Parameters * `req` (Req.Request.t()) - A Req.Request with ReqFly attached * `opts` (keyword()) - Options keyword list * `:app_name` (string()) - Name of the app (required) * `:machine_id` (string()) - ID of the machine (required) ### Returns * `{:ok, term()}` - Start confirmation * `{:error, ReqFly.Error.t()}` - Error details ### Examples ```elixir req = Req.new() |> ReqFly.attach(token: "fly_token") {:ok, _} = ReqFly.Machines.start(req, app_name: "my-app", machine_id: "148ed123456789" ) ``` ``` -------------------------------- ### Install ReqLLM and Kino Source: https://hexdocs.pm/req_llm/image-generation-4.html Install the necessary libraries for ReqLLM and Kino. This is typically done at the beginning of a Livebook session. ```elixir Mix.install([ {:req_llm, "~> 1.4"}, {:kino, "~> 0.14.2"} ]) ``` -------------------------------- ### Start ReqClinet.MintWs with Supervisor Source: https://hexdocs.pm/req_client/ReqClinet.MintWs.html Provides a module specification to start ReqClinet.MintWs under a supervisor. See `Supervisor` for more details. ```elixir child_spec(init_arg) ``` -------------------------------- ### Configure API Keys Source: https://hexdocs.pm/req_llm/contributing.html Set up your local environment by copying the example .env file and editing it with your specific API keys. ```bash cp .env.example .env # Edit .env with your API keys ``` -------------------------------- ### Caching GET Request Example Source: https://hexdocs.pm/req_client/ReqClient.html Demonstrates how to enable caching for a GET request. After execution, you can inspect the cache directory. ```elixir iex> url = "https://elixir-lang.org" iex> Req.get!(url, cache: true) $> ls -al ~/Library/Caches/req ``` -------------------------------- ### GET Request with Base URL Source: https://hexdocs.pm/req/Req.Steps.html Examples of making GET requests using a Req client configured with a base URL. ```elixir iex> Req.get!(req, url: "/status/200").status 200 iex> Req.get!(req, url: "/status/201").status 201 ``` -------------------------------- ### Example: Create App and Machine Source: https://hexdocs.pm/req_fly/ReqFly.html Shows how to create a Fly.io application and then deploy a machine using an Nginx image. ```elixir # Create app and machine req = Req.new() |> ReqFly.attach(token: System.get_env("FLY_API_TOKEN")) {:ok, app} = ReqFly.Apps.create(req, app_name: "my-app", org_slug: "personal") config = %{ image: "nginx:latest", guest: %{cpus: 1, memory_mb: 256} } {:ok, machine} = ReqFly.Machines.create(req, app_name: "my-app", config: config) ``` -------------------------------- ### GET Request and Body Retrieval Source: https://hexdocs.pm/req/Req.Steps.html Example of performing a GET request and retrieving the response body. Assumes a pre-configured Req client. ```elixir iex> resp = Req.get!(req, url: "/bucket1/key1").body "Hello, World!" ``` -------------------------------- ### Install ReqLLM Source: https://hexdocs.pm/req_llm/Mix.Tasks.ReqLlm.Install.html Run this command to install and configure ReqLLM. Ensure you have ReqLLM v1.11.0 or compatible version. ```bash mix req_llm.install ``` -------------------------------- ### Install and Initialize ReqS3 Source: https://hexdocs.pm/req_s3/index.html Shows how to install the req and req_s3 dependencies using Mix.install and how to initialize a Req client with the ReqS3 attachment. ```elixir Mix.install([ {:req, "~> 0.5.0"}, {:req_s3, "~> 0.2.3"} ]) req = Req.new() |> ReqS3.attach() ``` -------------------------------- ### Manual Reqord Installation Source: https://hexdocs.pm/reqord/Reqord.html Manually install Reqord for more control over setup, including setting Req.Test modes and specifying cassette names and modes. ```elixir defmodule MyApp.CustomTest do use ExUnit.Case setup do Req.Test.set_req_test_to_private() Req.Test.set_req_test_from_context(%{async: true}) Reqord.install!( name: MyApp.ReqStub, cassette: "my_custom_cassette", mode: :replay ) :ok end test "custom setup" do client = Req.new(plug: {Req.Test, MyApp.ReqStub}) {:ok, response} = Req.get(client, url: "https://api.example.com/data") assert response.status == 200 end end ``` -------------------------------- ### Create and Execute a Simple Tool Source: https://hexdocs.pm/req_llm/ReqLLM.Tool.html Demonstrates how to create a basic tool with a name, description, parameter schema, and callback, and then execute it with input parameters. Input validation is handled automatically. ```elixir {:ok, tool} = ReqLLM.Tool.new( name: "get_weather", description: "Get current weather for a location", parameter_schema: [ location: [type: :string, required: true, doc: "City name"] ], callback: {WeatherService, :get_current_weather} ) # Execute the tool {:ok, result} = ReqLLM.Tool.execute(tool, %{location: "San Francisco"}) # Get provider-specific schema anthropic_schema = ReqLLM.Tool.to_schema(tool, :anthropic) ``` -------------------------------- ### Quick Start: List Apps and Create Machine Source: https://hexdocs.pm/req_fly/ReqFly.html Initialize Req with your Fly.io API token and use ReqFly to list applications or create a new machine. ```elixir req = Req.new() |> ReqFly.attach(token: "your_fly_token") # List apps {:ok, apps} = ReqFly.Apps.list(req, org_slug: "personal") # Create a machine {:ok, machine} = ReqFly.Machines.create(req, app_name: "my-app", config: %{image: "nginx:latest"} ) ``` -------------------------------- ### Telemetry Handler Example Source: https://hexdocs.pm/req_fly/ReqFly.html Attach a handler to monitor ReqFly telemetry events like request start, stop, and exceptions. This example logs events using Elixir's Logger. ```elixir :telemetry.attach_many( "req-fly-handler", [ [:req_fly, :request, :start], [:req_fly, :request, :stop], [:req_fly, :request, :exception] ], fn event_name, measurements, metadata, _config -> # Handle telemetry event Logger.info("Fly.io API call", event: event_name, metadata: metadata) end, nil ) ``` -------------------------------- ### Install ReqFuse and Attach to Request Source: https://hexdocs.pm/req_fuse/ReqFuse.html Demonstrates how to install ReqFuse and attach it as a step to a Req request. The example shows firing requests repeatedly to trigger the circuit breaker and the resulting error when the fuse is open. ```elixir Mix.install([ {:req, "~> 0.3"}, {:req_fuse, "~> 0.2"} ]) req_fuse_opts = [fuse_name: My.Example.Fuse] req = [url: "https://httpstat.us/500", retry: :never] |> Req.new() |> ReqFuse.attach(req_fuse_opts) # Fire the request enough times to melt the fuse Enum.each(0..10, fn _ -> Req.request(req) end) => :ok Req.request(req) => 08:45:42.518 [warning] :fuse circuit breaker is open; fuse = Elixir.My.Example.Fuse => {:error, %RuntimeError{message: "circuit breaker is open"}} ``` -------------------------------- ### Verify Development Setup Source: https://hexdocs.pm/req_llm/contributing.html Run tests and quality checks to ensure the development environment is set up correctly and all initial checks pass. ```bash mix test mix quality ``` -------------------------------- ### Get Request with Options Adapter Source: https://hexdocs.pm/req_client/ReqClient.Adapter.Options.html Example of using the options adapter to wrap a request. Useful for debugging requests. ```elixir Rc.get! :x, wrap: :options, debug: true ``` -------------------------------- ### start/5 Source: https://hexdocs.pm/requiem/Requiem.QUIC.Socket-function-start.html Starts a QUIC socket connection with the specified parameters. ```APIDOC ## start/5 ### Description Initiates a QUIC socket connection. ### Function Signature `start(socket_ptr, host, port, pid, target_pids)` ### Parameters - **socket_ptr** (integer()) - Represents the socket pointer. - **host** (binary()) - The hostname or IP address to connect to. - **port** (non_neg_integer()) - The port number for the connection. - **pid** (pid()) - The process ID initiating the connection. - **target_pids** ([pid()]) - A list of target process IDs. ### Returns - `:ok` on successful connection. - `{:error, :system_error | :socket_error}` on failure. ``` -------------------------------- ### Install and Configure ReqBigQuery Source: https://hexdocs.pm/req_bigquery/index.html Install the necessary dependencies and configure Goth for authentication. Ensure you have a `credentials.json` file and the `PROJECT_ID` environment variable set. ```elixir Mix.install([ {:goth, "~> 1.3.0"}, {:req, "~> 0.3.5"}, {:req_bigquery, "~> 0.1.5"} ]) credentials = File.read!("credentials.json") |> Jason.decode!() source = {:service_account, credentials, []} {:ok, _} = Goth.start_link(name: MyGoth, source: source, http_client: &Req.request/1) project_id = System.fetch_env!("PROJECT_ID") ``` -------------------------------- ### Example: Get Custom Dimensions Source: https://hexdocs.pm/req_ga/req_ga_demo.html Demonstrates how to retrieve a list of custom dimensions for a given GA4 property using ReqGA. ```APIDOC ## Get Custom Dimensions for a GA4 Property ### Description This example shows how to fetch custom dimensions associated with a specific GA4 property using the ReqGA library. ### Method `Req.get!` ### Endpoint Implicitly handled by ReqGA based on the `:custom_dimensions` atom. ### Parameters #### Query Parameters - **`ga`** (atom) - Required - Must be `:custom_dimensions` to specify the API call. - **`property_id`** (string) - Required - The ID of the GA4 property (e.g., `"properties/264264328"`). ### Request Example ```elixir property_id = "properties/264264328" res = Req.get!(req, ga: :custom_dimensions, property_id: property_id) ``` ### Response #### Success Response (200) - **`body`** (map) - The response body contains the data returned from the GA4 API, typically a list of custom dimensions. ``` -------------------------------- ### Get Supervisor Child Specification Source: https://hexdocs.pm/req_llm/ReqLLM.Providers.GoogleVertex.TokenCache.html Returns a specification to start this module under a supervisor. This is part of the standard Elixir supervision tree pattern. ```elixir child_spec(init_arg) ``` ```elixir Returns a specification to start this module under a supervisor. See `Supervisor`. ``` -------------------------------- ### Usage Example: List and Create Apps Source: https://hexdocs.pm/req_fly/readme.html Demonstrates listing all apps in an organization and creating a new app using the API token from an environment variable. ```elixir req = Req.new() |> ReqFly.attach(token: System.get_env("FLY_API_TOKEN")) # List all apps in your organization {:ok, apps} = ReqFly.Apps.list(req, org_slug: "personal") IO.inspect(apps, label: "Apps") # Create a new app {:ok, app} = ReqFly.Apps.create(req, app_name: "my-new-app", org_slug: "personal" ) ``` -------------------------------- ### Create and Manage Machines with ReqFly Source: https://hexdocs.pm/req_fly/getting_started.html Shows how to define a machine configuration, create a new machine, start it, and wait for it to be ready. ```elixir req = Req.new() |> ReqFly.attach(token: System.get_env("FLY_API_TOKEN")) # Define machine configuration config = %{ image: "flyio/hellofly:latest", env: %{ "PORT" => "8080" }, guest: %{ cpus: 1, memory_mb: 256 } } # Create a machine {:ok, machine} = ReqFly.Machines.create(req, app_name: "my-test-app", config: config, region: "ewr" ) machine_id = machine["id"] IO.puts("Created machine: #{machine_id}") # Start the machine {:ok, _} = ReqFly.Machines.start(req, app_name: "my-test-app", machine_id: machine_id ) # Wait for it to be ready {:ok, ready_machine} = ReqFly.Machines.wait(req, app_name: "my-test-app", machine_id: machine_id, instance_id: machine["instance_id"], state: "started", timeout: 60 ) IO.puts("Machine is ready!") ``` -------------------------------- ### Get Object Body and Decode Source: https://hexdocs.pm/req_s3/ReqS3.html Retrieve the body of an S3 object and demonstrate decoding its content, for example, to extract image metadata. ```elixir Req.get!(req, url: "s3://ossci-datasets").body #=> # %{ # "ListBucketResult" => %{ # "Contents" => [ # %{"Key" => "mnist/", ...}, # %{"Key" => "mnist/t10k-images-idx3-ubyte.gz", ...}, # ... # ], # "Name" => "ossci-datasets", # ... # } # } body = Req.get!(req, url: "s3://ossci-datasets/mnist/t10k-images-idx3-ubyte.gz").body <<_::32, n_images::32, n_rows::32, n_cols::32, _body::binary>> = body {n_images, n_rows, n_cols} #=> {10_000, 28, 28} ``` -------------------------------- ### Basic Configuration with Patterns Source: https://hexdocs.pm/req_cassette/templating.html Sets up basic templating with defined patterns for 'sku' and 'order_id'. ```elixir template: [ patterns: [ sku: ~r/\d{4}-\d{4}/, order_id: ~r/ORD-\d+/ ] ] ``` -------------------------------- ### GET Request with Range Header Source: https://hexdocs.pm/req/Req.Steps.html Example of setting the 'Range' header for partial content retrieval using a `first..last` range. ```elixir iex> response = Req.get!("https://httpbin.org/range/100", range: 0..3) iex> response.status 206 iex> response.body "abcd" iex> Req.Response.get_header(response, "content-range") ["bytes 0-3/100"] ``` -------------------------------- ### Basic Templating Example with ReqCassette Source: https://hexdocs.pm/req_cassette/templating.html Demonstrates a basic product lookup using ReqCassette with templating. The first run records the API call, and subsequent runs replay from the cassette, substituting a different SKU. ```elixir import ReqCassette test "product lookup with templates" do with_cassette "product_lookup", [ template: [ patterns: [sku: ~r/\d{4}-\d{4}/] ] ], fn plug -> # First run: Records real API call response = Req.get!( "https://api.example.com/products/1234-5678", plug: plug ) assert response.body["sku"] == "1234-5678" assert response.body["name"] == "Widget" # Second run: Replays from cassette with different SKU! response2 = Req.get!( "https://api.example.com/products/5555-6666", plug: plug ) assert response2.body["sku"] == "5555-6666" # ✅ Substituted! assert response2.body["name"] == "Widget" # ✅ Same static data end end ``` -------------------------------- ### Install Reqord with Custom Matcher Source: https://hexdocs.pm/reqord/Reqord.html Register and use a custom matcher function with Reqord. This example demonstrates matching on method, URI, and a custom `:api_version` header. ```elixir Reqord.register_matcher(:api_version, fn conn, entry -> Plug.Conn.get_req_header(conn, "x-api-version") == [get_in(entry, ["req", "headers", "x-api-version"])] end) Reqord.install!( name: MyApp.ReqStub, cassette: "my_test", match_on: [:method, :uri, :api_version] ) ``` -------------------------------- ### start_link(opts \\ []) Source: https://hexdocs.pm/reqord/Reqord.CassetteWriter.html Starts the CassetteWriter GenServer. ```APIDOC ## start_link(opts \\ []) ### Description Starts the CassetteWriter GenServer. ### Parameters #### Path Parameters - **opts** (keyword()) - Optional - Options for starting the GenServer. ``` -------------------------------- ### start_link/1 Source: https://hexdocs.pm/requiem/Requiem.ConnectionSupervisor-function-start_link.html Starts the ConnectionSupervisor. ```APIDOC ## start_link/1 ### Description Starts the ConnectionSupervisor. ### Function Signature `start_link(handler)` ### Parameters #### Path Parameters - **handler** (module()) - Required - The module to be supervised. ``` -------------------------------- ### Structured Geocoding Example Source: https://hexdocs.pm/req_photon_geocoding/ReqPhotonGeocoding.html Performs structured forward geocoding using address components like city and country. The `limit` option is used to get a single result. ```elixir iex> {:ok, result} = ReqPhotonGeocoding.structured(city: "Berlin", country: "Germany", limit: 1) iex> [feature | _] = result["features"] iex> feature["properties"]["country"] "Germany" ``` -------------------------------- ### Load Cassette Example Source: https://hexdocs.pm/req_cassette/ReqCassette.Cassette.html Demonstrates how to load a cassette from a JSON file on disk. ```elixir # Load from disk {:ok, cassette} = load("test/cassettes/my_api.json") ``` -------------------------------- ### Raw HTML Generation Source: https://hexdocs.pm/req_embed/ReqEmbed.html Example of using ReqEmbed.html/2 to get the oEmbed content directly as an HTML string. This can be rendered in Phoenix templates using `{:safe, html}` or `Phoenix.HTML.raw/1`. ```APIDOC ## Raw HTML Or alternatively use ReqEmbed.html/2 to get the oEmbed content as HTML: ```elixir ReqEmbed.html("https://www.youtube.com/watch?v=XfELJU1mRMg") # ``` Wrap it in a `{:safe, html}` tuple or call `Phoenix.HTML.raw/1` to render it in Phoenix templates. ``` -------------------------------- ### Install and Authenticate ReqBigQuery Source: https://hexdocs.pm/req_bigquery/readme.html Install the necessary dependencies and set up Goth for authentication. Ensure you have a 'credentials.json' file and the PROJECT_ID environment variable set. ```elixir Mix.install([ {:goth, "~> 1.3.0"}, {:req, "~> 0.3.5"}, {:req_bigquery, "~> 0.1.5"} ]) # We use Goth to authenticate to Google Cloud API. # See: https://hexdocs.pm/goth/1.3.0-rc.4/Goth.Token.html#fetch/1-source for more information. credentials = File.read!("credentials.json") |> Jason.decode!() source = {:service_account, credentials, []} {:ok, _} = Goth.start_link(name: MyGoth, source: source, http_client: &Req.request/1) project_id = System.fetch_env!("PROJECT_ID") ``` -------------------------------- ### Full Handler implementation with various callbacks Source: https://hexdocs.pm/requiem/Requiem.html A comprehensive example demonstrating initialization, stream handling, and various message handling callbacks (info, cast, call, terminate). ```elixir defmodule MyApp.MyHandler do use Requiem, otp_app: :my_app @impl Requiem def init(conn, client) do {:ok, conn, %{}} end @impl Requiem def handle_stream(stream_id, data, conn, state) do stream_send(stream_id, data, false) {:ok, conn, state} end @impl Requiem def handle_info(request, conn, state) do {:noreply, conn, state} end @impl Requiem def handle_cast(request, conn, state) do {:noreply, conn, state} end @impl Requiem def handle_call(request, from, conn, state) do {:reply, :ok, conn, state} end @impl Requiem def terminate(_reason, _conn, _state) do :ok end end ``` -------------------------------- ### Quick Start: Create a Machine Source: https://hexdocs.pm/req_fly/readme.html Create a new machine for an app in a specific region with a given configuration. ```elixir {:ok, machine} = ReqFly.Machines.create(req, app_name: "my-app", config: %{ image: "nginx:latest", env: %{"PORT" => "8080"}, guest: %{cpus: 1, memory_mb: 256} }, region: "ewr" ) ``` -------------------------------- ### Define an HTTP Client with ReqClientBase Source: https://hexdocs.pm/req_client_base/index.html Use the ReqClientBase macro to define a custom HTTP client module. Configure the service name for telemetry. This example shows how to define a client that can make GET requests. ```elixir defmodule Some.Http.Client do use ReqClientBase, service_name: :some_client def client_call do get(url: "https://some.url") end end ``` -------------------------------- ### Fetch oEmbed Rich Content Source: https://hexdocs.pm/req_embed/ReqEmbed.html Fetches oEmbed rich content from a given URL using ReqEmbed. This example shows how to attach the ReqEmbed module and make a GET request to retrieve the body, which is parsed into a `ReqEmbed.Rich` struct. ```elixir iex> req = Req.new() |> ReqEmbed.attach() iex> Req.get!(req, url: "https://x.com/ThinkingElixir/status/1848702455313318251").body %ReqEmbed.Rich{ type: "rich", version: "1.0", author_name: "ThinkingElixir", author_url: "https://twitter.com/ThinkingElixir", html: "

News includes upcoming Elixir v1.18 ... ... } ``` -------------------------------- ### start/5 Source: https://hexdocs.pm/requiem/Requiem.NIF.Socket-function-start.html Initiates a socket connection with the provided parameters. It returns :ok on success or an error tuple on failure. ```APIDOC ## start/5 ### Description Initiates a socket connection. ### Function Signature ```elixir start(socket_ptr, host, port, pid, target_pids) ``` ### Parameters - **socket_ptr** (integer()) - An integer representing the socket pointer. - **host** (binary()) - The hostname or IP address to connect to. - **port** (non_neg_integer()) - The port number to connect to. - **pid** (pid()) - The process identifier of the calling process. - **target_pids** ([pid()]) - A list of process identifiers to target. ### Return Value - `:ok` - If the socket connection is successfully started. - `{:error, :system_error | :socket_error}` - If an error occurs during socket startup. ``` -------------------------------- ### Basic S3 Operations with ReqS3 Source: https://hexdocs.pm/req_s3/readme.html Demonstrates basic operations like listing buckets, listing objects, getting an object, and putting an object using the s3:// URL scheme. Ensure you have the `req` and `req_s3` dependencies installed. ```elixir Req.get!(req, url: "s3://") # list objects Req.get!(req, url: "s3://#{bucket}") # get object Req.get!(req, url: "s3://#{bucket}/#{key}") # put object Req.put!(req, url: "s3://#{bucket}/#{key}") ``` -------------------------------- ### Custom OpenTelemetry Mapper with ReqLLM Source: https://hexdocs.pm/req_llm/telemetry.html Implement a custom telemetry handler to map ReqLLM events to OpenTelemetry spans. This example shows how to attach to specific ReqLLM events and use the OpenTelemetry mapper for request start, stop, and exception events. ```elixir defmodule MyApp.ReqLLMOpenTelemetry do alias ReqLLM.Telemetry.OpenTelemetry @events [ [:req_llm, :request, :start], [:req_llm, :request, :stop], [:req_llm, :request, :exception] ] def attach do :telemetry.attach_many("my-app-req-llm-otel", @events, &__MODULE__.handle_event/4, %{}) end def handle_event([:req_llm, :request, :start], _measurements, metadata, _config) do stub = OpenTelemetry.request_start(metadata, content: :attributes) MyApp.Tracing.start_gen_ai_span(metadata.request_id, stub) end def handle_event([:req_llm, :request, :stop], _measurements, metadata, _config) do stub = OpenTelemetry.request_stop(metadata, content: :attributes) MyApp.Tracing.finish_gen_ai_span(metadata.request_id, stub) end def handle_event([:req_llm, :request, :exception], _measurements, metadata, _config) do stub = OpenTelemetry.request_exception(metadata, content: :attributes) MyApp.Tracing.finish_gen_ai_span(metadata.request_id, stub) end end ``` -------------------------------- ### Example: Basic Text Generation Source: https://hexdocs.pm/req_llm/Mix.Tasks.ReqLlm.Gen.html Performs basic text generation using the default settings, streaming output in real-time. ```bash # Basic text generation (streams by default) mix req_llm.gen "Explain how neural networks work" ``` -------------------------------- ### Configure Ecto Sandbox Environment Source: https://hexdocs.pm/req_sandbox/usage.html Configures the Ecto repository environment for the ReqSandbox guide. Adjust the database connection details (user, password, host, database name) and port to match your local setup. This configuration is essential for the application to connect to the database. ```elixir # Modify these values to suit your environment pg_host = "127.0.0.1" pg_user = "postgres" pg_pass = "postgres" pg_db = "req_sandbox_guide" port = 5001 # END: user values Application.put_env(:req_sandbox_guide, Repo, url: "ecto://#{pg_user}:#{pg_pass}@#{pg_host}/#{pg_db}", pool: Ecto.Adapters.SQL.Sandbox, ownership_timeout: :timer.hours(24) ) Application.put_env(:req_sandbox_guide, ReqSandboxGuide.Endpoint, adapter: Bandit.PhoenixAdapter, render_errors: [formats: [json: ReqSandboxGuide.ErrorJSON], layout: false], http: [ip: {127, 0, 0, 1}, port: port], server: true, secret_key_base: String.duplicate("a", 64) ) Application.put_env(:phoenix, :json_library, Jason) ``` -------------------------------- ### start_link/1 - Start Supervisor Link Source: https://hexdocs.pm/requiem/Requiem.DispatcherSupervisor.html Starts the supervisor link with the given options. This function is typically used when starting the supervisor as part of an application. ```elixir start_link(opts) ``` -------------------------------- ### ExUnit Setup for Shared Sessions Source: https://hexdocs.pm/req_cassette/ReqCassette.html Use ExUnit's setup function to manage shared sessions for multiple tests requiring the same cassette session. This ensures efficient resource utilization. ```elixir defmodule MyApp.ParallelAPITest do use ExUnit.Case, async: true import ReqCassette setup do session = ReqCassette.start_shared_session() on_exit(fn -> ReqCassette.end_shared_session(session) end) %{session: session} end test "parallel API calls", %{session: session} do with_cassette "parallel_test", [session: session], fn plug -> tasks = for i <- 1..3 do Task.async(fn -> Req.get!("https://api.example.com/#{i}", plug: plug) end) end Task.await_many(tasks) end end end ``` -------------------------------- ### Create Tool with Options Source: https://hexdocs.pm/req_llm/ReqLLM.Tool.html Shows how to create a new tool using the `new/1` function, specifying required options like name, description, and callback, along with optional parameter schema. ```elixir opts = [ name: "get_weather", description: "Get current weather for a location", parameter_schema: [ location: [type: :string, required: true, doc: "City name"] ], callback: {WeatherService, :get_current_weather} ] {:ok, tool} = ReqLLM.Tool.new(opts) ``` -------------------------------- ### get Source: https://hexdocs.pm/req_client/ReqClient.Channel.Mint.html Sends a GET request to the specified URL. ```APIDOC ## get(url, opts \\ []) ### Description get request ### Method GET ### Endpoint [url] ### Parameters #### Query Parameters - **opts** (map) - Optional - Additional options for the request. ``` -------------------------------- ### new() Source: https://hexdocs.pm/requiem/Requiem.QUIC.Config-function-new.html Initializes a new QUIC configuration. Returns `{:ok, integer()}` on success or `{:error, :system_error | :not_found}` on failure. ```APIDOC ## new() ### Description Initializes a new QUIC configuration. ### Specs ```elixir new() :: {:ok, integer()} | {:error, :system_error | :not_found} ``` ``` -------------------------------- ### ReqLLM.Transcription.Result Example Source: https://hexdocs.pm/req_llm/ReqLLM.Transcription.Result.html An example of the ReqLLM Transcription Result structure. ```APIDOC ## Examples ```elixir %ReqLLM.Transcription.Result{ text: "Hello, how are you?", segments: [ %{text: "Hello,", start_second: 0.0, end_second: 0.5}, %{text: " how are you?", start_second: 0.5, end_second: 1.2} ], language: "en", duration_in_seconds: 1.2 } ``` ``` -------------------------------- ### ReqLLM.Transcription.Result Struct Example Source: https://hexdocs.pm/req_llm/ReqLLM.Transcription.Result.html Example of how to construct a ReqLLM.Transcription.Result struct. ```elixir %ReqLLM.Transcription.Result{ text: "Hello, how are you?", segments: [ %{text: "Hello,", start_second: 0.0, end_second: 0.5}, %{text: " how are you?", start_second: 0.5, end_second: 1.2} ], language: "en", duration_in_seconds: 1.2 } ```