> ## Documentation Index
> Fetch the complete documentation index at: https://www.algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Compact Context

> Summarize the older part of a conversation into a single user message via the caller's LLM.

**Required ACL:** `search`

Everything except the trailing `keepLastMessages` messages is summarized; the summary is
returned as a user-role message followed by the kept tail verbatim. Your provider runs the
summary, so the provider adds the cost to your account.

A conversation too large for the summarizer's context window is split into chunks that each fit,
summarized concurrently, then merged in a reduce pass - so payload size alone does not fail the
request. When the conversation still cannot be summarized (it needs more chunks than the server
allows, or the chunk summaries will not converge), the response is a `400`, not a `500`.

Two optional controls shape the output. `instructions` adds caller guidance inside the
server-owned prompt frame, so it steers the summary without the model echoing the wording back.
`targetTokensEstimate` sets a desired summary size, translated into word-count guidance.

The `compaction` block reports what happened: `compacted` is `false` when the payload passed
through untouched (nothing older than the kept tail), alongside chunk/pass counts and the
summarizer's own token usage.

## Usage

<CodeGroup>
  ```cs C# theme={"system"}
  // Initialize the client
  var client = new AgentStudioClient(
    new AgentStudioConfig("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
  );

  // Call the API
  var response = await client.CompactContextAsync(
    new ContextCompactRequest
    {
      ProviderID = "c2905529-b933-4b69-87ec-75f9829d5f59",
      Model = "gpt-4o-mini",
      Messages = new MessagesUnion(
        new List<MessageV4>
        {
          new MessageV4(new UserMessageV4 { Role = "user", Content = "Hello, how are you?" }),
        }
      ),
    }
  );

  // print the response
  Console.WriteLine(response);
  ```

  ```dart Dart theme={"system"}
  // Initialize the client
  final client = AgentStudioClient(
      appId: 'ALGOLIA_APPLICATION_ID', apiKey: 'ALGOLIA_API_KEY');

  // Call the API
  final response = await client.compactContext(
    contextCompactRequest: ContextCompactRequest(
      providerID: "c2905529-b933-4b69-87ec-75f9829d5f59",
      model: "gpt-4o-mini",
      messages: [
        UserMessageV4(
          role: "user",
          content: "Hello, how are you?",
        ),
      ],
    ),
  );

  // print the response
  print(response);
  ```

  ```go Go theme={"system"}
  // Initialize the client
  client, err := agentStudio.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
  if err != nil {
    // The client can fail to initialize if you pass an invalid parameter.
    panic(err)
  }

  // Call the API
  response, err := client.CompactContext(client.NewApiCompactContextRequest(
    agentStudio.NewEmptyContextCompactRequest().
      SetProviderID("c2905529-b933-4b69-87ec-75f9829d5f59").
      SetModel("gpt-4o-mini").
      SetMessages(agentStudio.ArrayOfMessageV4AsMessagesUnion(
        []agentStudio.MessageV4{*agentStudio.UserMessageV4AsMessageV4(
          agentStudio.NewEmptyUserMessageV4().SetRole("user").SetContent("Hello, how are you?"))})),
  ))
  if err != nil {
    // handle the eventual error
    panic(err)
  }


  // print the response
  print(response)
  ```

  ```java Java theme={"system"}
  // Initialize the client
  AgentStudioClient client = new AgentStudioClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY");

  // Call the API
  ContextResponse response = client.compactContext(
    new ContextCompactRequest()
      .setProviderID("c2905529-b933-4b69-87ec-75f9829d5f59")
      .setModel("gpt-4o-mini")
      .setMessages(MessagesUnion.ofListOfMessageV4(Arrays.asList(new UserMessageV4().setRole("user").setContent("Hello, how are you?"))))
  );

  // print the response
  System.out.println(response);
  ```

  ```js JavaScript theme={"system"}
  // Initialize the client
  const client = agentStudioClient('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');

  // Call the API
  const response = await client.compactContext({
    providerID: 'c2905529-b933-4b69-87ec-75f9829d5f59',
    model: 'gpt-4o-mini',
    messages: [{ role: 'user', content: 'Hello, how are you?' }],
  });


  // print the response
  console.log(response);
  ```

  ```kotlin Kotlin theme={"system"}
  // Initialize the client
  val client = AgentStudioClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")

  // Call the API
  var response =
    client.compactContext(
      contextCompactRequest =
        ContextCompactRequest(
          providerID = "c2905529-b933-4b69-87ec-75f9829d5f59",
          model = "gpt-4o-mini",
          messages =
            MessagesUnion.ofListOfMessageV4(
              listOf(UserMessageV4(role = "user", content = "Hello, how are you?"))
            ),
        )
    )


  // print the response
  println(response)
  ```

  ```php PHP theme={"system"}
  // Initialize the client
  $client = AgentStudioClient::create('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');

  // Call the API
  $response = $client->compactContext(
      ['providerID' => 'c2905529-b933-4b69-87ec-75f9829d5f59',
          'model' => 'gpt-4o-mini',
          'messages' => [
              ['role' => 'user',
                  'content' => 'Hello, how are you?',
              ],
          ],
      ],
  );


  // print the response
  var_dump($response);
  ```

  ```python Python theme={"system"}
  # Initialize the client
  # In an asynchronous context, you can use AgentStudioClient instead, which exposes the exact same methods.
  client = AgentStudioClientSync("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")

  # Call the API
  response = client.compact_context(
      context_compact_request={
          "providerID": "c2905529-b933-4b69-87ec-75f9829d5f59",
          "model": "gpt-4o-mini",
          "messages": [
              {
                  "role": "user",
                  "content": "Hello, how are you?",
              },
          ],
      },
  )


  # print the response
  print(response)
  ```

  ```ruby Ruby theme={"system"}
  # Initialize the client
  client = Algolia::AgentStudioClient.create("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")

  # Call the API
  response = client.compact_context(
    Algolia::AgentStudio::ContextCompactRequest.new(
      provider_id: "c2905529-b933-4b69-87ec-75f9829d5f59",
      model: "gpt-4o-mini",
      messages: [Algolia::AgentStudio::UserMessageV4.new(role: "user", content: "Hello, how are you?")]
    )
  )


  # print the response
  puts(response)
  ```

  ```scala Scala theme={"system"}
  // Initialize the client
  val client = AgentStudioClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")

  // Call the API
  val response = Await.result(
    client.compactContext(
      contextCompactRequest = ContextCompactRequest(
        providerID = "c2905529-b933-4b69-87ec-75f9829d5f59",
        model = "gpt-4o-mini",
        messages = MessagesUnion(
          Seq(
            UserMessageV4(
              role = "user",
              content = "Hello, how are you?"
            )
          )
        )
      )
    ),
    Duration(100, "sec")
  )

  // print the response
  println(response)
  ```

  ```swift Swift theme={"system"}
  // Initialize the client
  let client = try AgentStudioClient(appID: "ALGOLIA_APPLICATION_ID", apiKey: "ALGOLIA_API_KEY")

  // Call the API
  let response = try await client.compactContext(contextCompactRequest: ContextCompactRequest(
      providerID: "c2905529-b933-4b69-87ec-75f9829d5f59",
      model: "gpt-4o-mini",
      messages: MessagesUnion.arrayOfMessageV4([MessageV4.userMessageV4(UserMessageV4(
          role: "user",
          content: "Hello, how are you?"
      ))])
  ))

  // print the response
  print(response)
  ```
</CodeGroup>

<Card icon="folder-code" horizontal="true" title="See the full API reference" arrow="true" href="/doc/rest-api/agent-studio/compact-context">
  For more details about input parameters
  and response fields.
</Card>
