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

# Sessions & Chat

> Create sessions, send messages, and stream responses

Sessions represent a conversation between a user and an agent. Each session maintains its own message history and context window. This guide covers creating sessions, sending messages (synchronously or via streaming), and retrieving conversation history.

## Create a session

Start a new conversation by creating a session tied to a specific agent.

<CodeGroup>
  ```python Python theme={null}
  import os
  from meibel import MeibelClient
  from meibel.models import CreateSessionRequest

  client = MeibelClient(api_key=os.environ["MEIBEL_API_KEY"])

  session = client.agents.sessions.create(
      agent_id="agent_123",
      body=CreateSessionRequest(),
  )

  print(session.session_id)
  ```

  ```typescript TypeScript theme={null}
  import { MeibelClient } from 'meibel';

  const client = new MeibelClient({ apiKey: process.env.MEIBEL_API_KEY });

  const session = await client.agents.sessions.create('agent_123');

  console.log(session.sessionId);
  ```

  ```go Go theme={null}
  import (
      "context"
      "fmt"
      "os"

      meibel "github.com/meibel-ai/meibel-go"
  )

  client := meibel.NewClient(meibel.WithAPIKey(os.Getenv("MEIBEL_API_KEY")))
  ctx := context.Background()

  session, err := client.Agents.CreateSession(ctx, "agent_123", nil)
  if err != nil {
      log.Fatal(err)
  }

  fmt.Println(session.ID)
  fmt.Println(session.AgentID)
  ```

  ```bash CLI theme={null}
  meibel agents create-session agent_123
  ```
</CodeGroup>

The response includes the session `session_id`. Store it to send messages and retrieve history.

## Send a chat message (synchronous)

Send a message and wait for the complete response. This is the simplest approach and works well when you do not need to display partial results.

<CodeGroup>
  ```python Python theme={null}
  from meibel.models import ChatMessageRequest

  response = client.agents.sessions.send_chat_message(
      session_id=session.session_id,
      body=ChatMessageRequest(
          user_message="What are the key findings in the Q4 report?",
      ),
  )

  print(response.assistant_response)
  print(response.response.sources)
  ```

  ```typescript TypeScript theme={null}
  const response = await client.agents.sessions.sendChatMessage(session.sessionId, {
    userMessage: 'What are the key findings in the Q4 report?',
  });

  console.log(response.assistantResponse);
  console.log(response.response.sources);
  ```

  ```go Go theme={null}
  response, err := client.Sessions.SendChatMessage(ctx, session.ID, meibel.ChatMessageRequest{
      UserMessage: "What are the key findings in the Q4 report?",
  })
  if err != nil {
      log.Fatal(err)
  }

  fmt.Println(response.Message)
  fmt.Println(response.Citations)
  ```

  ```bash CLI theme={null}
  meibel sessions send-chat-message "$SESSION_ID" --data '{
    "user_message": "What are the key findings in the Q4 report?"
  }'
  ```
</CodeGroup>

The response includes the assistant's reply in `assistant_response`, any `sources` (under `response.sources`) referencing datasource content, and metadata such as token usage.

## Stream a chat response (SSE)

For a more responsive user experience, stream the response as Server-Sent Events. Each event delivers a chunk of the assistant's reply as it is generated.

<CodeGroup>
  ```python Python theme={null}
  import io

  stream = client.agents.sessions.send_chat_message_stream(
      session_id=session.session_id,
      file=io.BytesIO(b""),
      file_name="empty.txt",
      user_message="Summarize the revenue trends over the last 3 quarters.",
  )

  shown = 0
  for event in stream:
      if event.event == "partial_response":
          message = event.json()["data"]["message"]
          print(message[shown:], end="", flush=True)
          shown = len(message)
      elif event.event == "completion":
          print("\n\n[Stream complete]")
  ```

  ```typescript TypeScript theme={null}
  const stream = client.agents.sessions.sendChatMessageStream(
    session.sessionId,
    undefined,
    undefined,
    { userMessage: 'Summarize the revenue trends over the last 3 quarters.' },
  );

  let shown = 0;
  for await (const event of stream) {
    const e = event as { type?: string; data?: { message?: string } };
    if (e.type === 'partial_response') {
      const message = e.data?.message ?? '';
      process.stdout.write(message.slice(shown));
      shown = message.length;
    } else if (e.type === 'completion') {
      console.log('\n\n[Stream complete]');
    }
  }
  ```

  ```go Go theme={null}
  stream, err := client.Sessions.SendChatMessageStream(ctx, session.ID, meibel.ChatMessageRequest{
      UserMessage: "Summarize the revenue trends over the last 3 quarters.",
  })
  if err != nil {
      log.Fatal(err)
  }

  for event := range stream.Events {
      switch e := event.(type) {
      case *meibel.ContentEvent:
          fmt.Print(e.Delta)
      case *meibel.CitationsEvent:
          fmt.Println("\n\nCitations:", e.Citations)
      case *meibel.DoneEvent:
          fmt.Println("\n\n[Stream complete]")
      }
  }
  if err := stream.Err(); err != nil {
      log.Fatal(err)
  }
  ```

  ```bash CLI theme={null}
  meibel sessions send-chat-message-stream "$SESSION_ID" --data '{
    "user_message": "Summarize the revenue trends over the last 3 quarters."
  }'
  ```
</CodeGroup>

<Note>
  The streaming endpoint uses Server-Sent Events (SSE). In Python each event is an `SSEEvent` (read `event.event` for the name and `event.json()` for the payload); in TypeScript each event is the already-parsed payload. Common event names are `partial_response` (the cumulative reply so far) and `completion` (stream finished), with `connected` and `status` events along the way.
</Note>

## Get session message history

Retrieve all messages exchanged in a session, in chronological order.

<CodeGroup>
  ```python Python theme={null}
  messages = client.sessions.get_messages(session_id=session.session_id)

  for msg in messages.messages:
      print(f"[{msg.type}] {msg.message}")
  ```

  ```typescript TypeScript theme={null}
  const messages = await client.sessions.getMessages(session.sessionId);

  for (const msg of messages.messages) {
    console.log(`[${msg.type}] ${msg.message}`);
  }
  ```

  ```go Go theme={null}
  messages, err := client.Sessions.GetSessionMessages(ctx, session.ID)
  if err != nil {
      log.Fatal(err)
  }

  for _, msg := range messages {
      fmt.Printf("[%s] %s\n", msg.Role, msg.Message)
  }
  ```

  ```bash CLI theme={null}
  meibel sessions get-session-messages "$SESSION_ID"
  ```
</CodeGroup>

Each message includes `type` (either `"user"` or `"assistant"`), the `message` content, and a timestamp.

## Get session details

Retrieve metadata about a session, including its agent and status.

<CodeGroup>
  ```python Python theme={null}
  session = client.sessions.get(session_id="session_456")

  print(session.agent_id)
  print(session.agent_name)
  print(session.status)
  ```

  ```typescript TypeScript theme={null}
  const session = await client.sessions.get('session_456');

  console.log(session.agentId);
  console.log(session.agentName);
  console.log(session.status);
  ```

  ```go Go theme={null}
  session, err := client.Sessions.GetSession(ctx, "session_456")
  if err != nil {
      log.Fatal(err)
  }

  fmt.Println(session.ID)
  fmt.Println(session.AgentID)
  fmt.Println(session.CreatedAt)
  ```

  ```bash CLI theme={null}
  meibel sessions get-session session_456
  ```
</CodeGroup>
