# `PostHog.Integrations.LLMAnalytics.Req`
[🔗](https://github.com/posthog/posthog-elixir/blob/v2.23.4/lib/posthog/integrations/llm_analytics/req.ex#L1)

Req plugin that automatically captures
[`$ai_generation`](https://posthog.com/docs/llm-analytics/manual-capture?tab=Generation)
events for LLMs.

It tries to extract as much information as possible from both requests and
responses. Currently, it works best with the following APIs:
* OpenAI (Responses)
* OpenAI (Chat Completions)
* Anthropic (Create Message)
* Gemini (generateContent)

## Usage

Just add it to your `Req` client before making a call:

```
Req.new()
|> PostHog.Integrations.LLMAnalytics.Req.attach()
|> Req.post!(url: "https://api.openai.com/v1/responses", json: %{model: "gpt-5-mini", input: "Who are you?"})
```

Optionally, start a new span beforehand to add additional properties to the event:

```
PostHog.LLMAnalytics.start_span(%{"$ai_span_name": "OpenAI Request"})
Req.post!(client, url: "https://api.openai.com/v1/responses", json: ...)
```

## Integrating with InstructorLite

InstructorLite built-in adapters allow customizing the HTTP client using the
[`http_client`
option](https://hexdocs.pm/instructor_lite/InstructorLite.Adapters.OpenAI.html#send_request/2).
Define a wrapper module like this:

```
defmodule ReqWithLLMAnalytics do
  def post(url, opts) do
    Req.new(url: url)
    |> PostHog.Integrations.LLMAnalytics.Req.attach()
    |> Req.post(opts)
  end
end
```

Then pass this module as the `http_client` option in `adapter_context`.
Optionally, start a span beforehand!

```
PostHog.LLMAnalytics.start_span(%{"$ai_span_name": "LLM Call"})

InstructorLite.instruct(%{
    input: [%{role: "user", content: "John is 25yo"}],
    model: "gpt-4o-mini"
  },
  response_model: %{name: :string, age: :integer},
  adapter: InstructorLite.Adapters.OpenAI,
  adapter_context: [
    api_key: "my-secret-key",
    http_client: ReqWithLLMAnalytics
  ]
)
{:ok, %{name: "John", age: 25}}
```

# `attach`
*since 2.2.0* 

```elixir
@spec attach(Req.Request.t(), keyword()) :: Req.Request.t()
```

Attaches the LLM Analytics plugin to a `Req.Request` struct.

## Parameters

- `request` - the `Req.Request` to instrument.
- `options` - plugin options merged into the request.

## Options

- `:posthog_supervisor` - PostHog supervisor name to capture through. Use this
  if you run a [custom PostHog instance](https://posthog.com/docs/libraries/elixir#advanced-configuration).

## Returns

Returns the updated `Req.Request` with request, response, and error steps
installed.

## Examples

    iex> Req.new() |> PostHog.Integrations.LLMAnalytics.Req.attach()
    iex> Req.new() |> PostHog.Integrations.LLMAnalytics.Req.attach(posthog_supervisor: MyPostHog)

---

*Consult [api-reference.md](api-reference.md) for complete listing*
