> ## 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 & Chat

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

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

  session = client.agents.create_session(agent_id="agent_123")

  print(session.id)
  print(session.agent_id)
  ```

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

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

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

  console.log(session.id);
  console.log(session.agentId);
  ```

  ```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 `id`, the `agent_id` it belongs to, and creation timestamps. Store the session `id` 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.sessions.send_chat_message(
      session_id=session.id,
      body=ChatMessageRequest(
          user_message="What are the key findings in the Q4 report?",
      ),
  )

  print(response.message)
  print(response.citations)
  ```

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

  console.log(response.message);
  console.log(response.citations);
  ```

  ```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 `message`, any `citations` 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}
  from meibel.models import ChatMessageRequest

  stream = client.sessions.send_chat_message_stream(
      session_id=session.id,
      body=ChatMessageRequest(
          user_message="Summarize the revenue trends over the last 3 quarters.",
      ),
  )

  for event in stream:
      if event.type == "content":
          print(event.delta, end="", flush=True)
      elif event.type == "citations":
          print("\n\nCitations:", event.citations)
      elif event.type == "done":
          print("\n\n[Stream complete]")
  ```

  ```typescript TypeScript theme={null}
  // Note: sendChatMessageStream has a known multipart signature issue in the
  // current TypeScript SDK. Use the synchronous sendChatMessage method above
  // until streaming support is stabilized.
  const stream = await client.sessions.sendChatMessageStream(session.id, {
    userMessage: 'Summarize the revenue trends over the last 3 quarters.',
  });

  for await (const event of stream) {
    if (event.type === 'content') {
      process.stdout.write(event.delta);
    } else if (event.type === 'citations') {
      console.log('\n\nCitations:', event.citations);
    } else if (event.type === 'done') {
      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). Each event has a `type` field — common types include `content` (text chunks), `citations` (source references), and `done` (stream finished).
</Note>

## Get session message history

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

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

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

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

  for (const msg of messages) {
    console.log(`[${msg.role}] ${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 `role` (either `"user"` or `"assistant"`), the `message` content, and a timestamp.

## Get session details

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

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

  print(session.id)
  print(session.agent_id)
  print(session.created_at)
  ```

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

  console.log(session.id);
  console.log(session.agentId);
  console.log(session.createdAt);
  ```

  ```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>
