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

# Get User Personalized Context

Return a string of the user's personalized context you can directly insert it into your prompt.

Format:

```
# Memory
Unless the user has relevant queries, do not actively mention those memories in the conversation.
## User Background:
{profile}

## Latest Events:
{event}
```


## OpenAPI

````yaml get /api/v1/users/context/{user_id}
openapi: 3.1.0
info:
  title: Memobase API
  summary: APIs for Memobase, a user memory system for LLM Apps
  version: 0.0.40
servers:
  - url: https://api.memobase.dev
  - url: https://api.memobase.cn
security:
  - BearerAuth: []
paths:
  /api/v1/users/context/{user_id}:
    get:
      tags:
        - context
      summary: Get User Context
      operationId: get_user_context_api_v1_users_context__user_id__get
      parameters:
        - name: user_id
          in: path
          required: true
          schema:
            anyOf:
              - type: string
                format: uuid4
              - type: string
                format: uuid5
            description: The ID of the user
            title: User Id
          description: The ID of the user
        - name: max_token_size
          in: query
          required: false
          schema:
            type: integer
            description: Max token size of returned Context
            default: 1000
            title: Max Token Size
          description: Max token size of returned Context
        - name: prefer_topics
          in: query
          required: false
          schema:
            type: array
            items:
              type: string
            description: >-
              Rank prefer topics at first to try to keep them in filtering,
              default order is by updated time
            title: Prefer Topics
          description: >-
            Rank prefer topics at first to try to keep them in filtering,
            default order is by updated time
        - name: only_topics
          in: query
          required: false
          schema:
            type: array
            items:
              type: string
            description: Only return profiles with these topics, default is all
            title: Only Topics
          description: Only return profiles with these topics, default is all
        - name: max_subtopic_size
          in: query
          required: false
          schema:
            type: integer
            description: Max subtopic size of the same topic in returned Context
            title: Max Subtopic Size
          description: Max subtopic size of the same topic in returned Context
        - name: topic_limits_json
          in: query
          required: false
          schema:
            type: string
            description: >-
              Set specific subtopic limits for topics in JSON, for example
              {"topic1": 3, "topic2": 5}. The limits in this param will override
              `max_subtopic_size`.
            title: Topic Limits Json
          description: >-
            Set specific subtopic limits for topics in JSON, for example
            {"topic1": 3, "topic2": 5}. The limits in this param will override
            `max_subtopic_size`.
        - name: profile_event_ratio
          in: query
          required: false
          schema:
            type: number
            description: Profile event ratio of returned Context
            default: 0.6
            title: Profile Event Ratio
          description: Profile event ratio of returned Context
        - name: require_event_summary
          in: query
          required: false
          schema:
            type: boolean
            description: Whether to require event summary in returned Context
            default: false
            title: Require Event Summary
          description: Whether to require event summary in returned Context
        - name: chats_str
          in: query
          required: false
          schema:
            type: string
            description: >
              Pass the recent chats to enable context search. 

              Memobase will use those chats to search for relevant events.

              It's a list of chats in OpenAI Message format, for example:
              [{"role": "user", "content": "Hello"}, {"role": "assistant",
              "content": "Hi"}].


              **NOTICE**

              - It will increase your latency by 0.1-1 seconds, because Memobase
              will use Embedding to search for relevant profiles and events.

              - It will cost your Memobase tokens, roughly 100~200 tokens per
              chat based on the profile size.

              - The profiles in the context will not be searched by the
              `chats_str`.

              - If you want also search profiles, see
              `full_profile_and_only_search_event` query parameter.
            title: Chats Str
          description: >
            Pass the recent chats to enable context search. 

            Memobase will use those chats to search for relevant events.

            It's a list of chats in OpenAI Message format, for example:
            [{"role": "user", "content": "Hello"}, {"role": "assistant",
            "content": "Hi"}].


            **NOTICE**

            - It will increase your latency by 0.1-1 seconds, because Memobase
            will use Embedding to search for relevant profiles and events.

            - It will cost your Memobase tokens, roughly 100~200 tokens per chat
            based on the profile size.

            - The profiles in the context will not be searched by the
            `chats_str`.

            - If you want also search profiles, see
            `full_profile_and_only_search_event` query parameter.
        - name: event_similarity_threshold
          in: query
          required: false
          schema:
            type: number
            description: Event similarity threshold of returned Context
            default: 0.2
            title: Event Similarity Threshold
          description: Event similarity threshold of returned Context
        - name: time_range_in_days
          in: query
          required: false
          schema:
            type: integer
            description: Only allow events within the past few days, default is 180
            default: 180
            title: Time Range In Days
          description: Only allow events within the past few days, default is 180
        - name: customize_context_prompt
          in: query
          required: false
          schema:
            type: string
            description: >
              Customize context prompt template.

              - use `{profile_section}` to refer to the profile section

              - use `{event_section}` to refer to the event section


              For example:

              ```

              # Memory

              Unless the user has relevant queries, do not actively mention
              those memories in the conversation.

              ## User Background:

              {profile_section}


              ## Latest Events:

              {event_section}

              ```
            title: Customize Context Prompt
          description: >
            Customize context prompt template.

            - use `{profile_section}` to refer to the profile section

            - use `{event_section}` to refer to the event section


            For example:

            ```

            # Memory

            Unless the user has relevant queries, do not actively mention those
            memories in the conversation.

            ## User Background:

            {profile_section}


            ## Latest Events:

            {event_section}

            ```
        - name: full_profile_and_only_search_event
          in: query
          required: false
          schema:
            type: boolean
            description: >
              If you pass `chats_str` and set this to `False`, Memobase will
              search for relevant profiles and events at the same time.

              **NOTICE**

              - It will increase your latency by 2-5(based on the profile size)
              seconds, because Memobase will use LLM and Embedding to search for
              relevant profiles and events.

              - It will cost your Memobase tokens, roughly 100~1000 tokens per
              chat based on the profile size.
            default: true
            title: Full Profile And Only Search Event
          description: >
            If you pass `chats_str` and set this to `False`, Memobase will
            search for relevant profiles and events at the same time.

            **NOTICE**

            - It will increase your latency by 2-5(based on the profile size)
            seconds, because Memobase will use LLM and Embedding to search for
            relevant profiles and events.

            - It will cost your Memobase tokens, roughly 100~1000 tokens per
            chat based on the profile size.
        - name: fill_window_with_events
          in: query
          required: false
          schema:
            type: boolean
            description: >-
              If set to `True`, Memobase will fill the token window with the
              rest events.
            default: false
            title: Fill Window With Events
          description: >-
            If set to `True`, Memobase will fill the token window with the rest
            events.
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserContextDataResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      x-code-samples:
        - lang: python
          source: >+
            # To use the Python SDK, install the package:

            # pip install memobase


            from memobase import MemoBaseClient


            client = MemoBaseClient(project_url='PROJECT_URL',
            api_key='PROJECT_TOKEN')


            context = u.context()

          label: Python
        - lang: javascript
          source: >+
            // To use the JavaScript SDK, install the package:

            // npm install @memobase/memobase


            import { MemoBaseClient } from '@memobase/memobase';


            const client = new MemoBaseClient(process.env.MEMOBASE_PROJECT_URL,
            process.env.MEMOBASE_API_KEY);

            const user = await client.getUser(userId);


            const context = await user.context();

          label: JavaScript
        - lang: go
          source: >+
            // To use the Go SDK, install the package:

            // go get
            github.com/memodb-io/memobase/src/client/memobase-go@latest


            import (
                "fmt"
                "log"

                "github.com/memodb-io/memobase/src/client/memobase-go/core"
            )


            func main() {
                projectURL := "YOUR_PROJECT_URL"
                apiKey := "YOUR_API_KEY"
                // Initialize the client
                client, err := core.NewMemoBaseClient(
                    projectURL,
                    apiKey,
                )
                if err != nil {
                    log.Fatalf("Failed to create client: %v", err)
                }

                // Get user context
                userID := "EXISTING_USER_ID" // Replace with an actual user ID
                user, err := client.GetUser(userID, false)
                if err != nil {
                    log.Fatalf("Failed to get user: %v", err)
                }

                context, err := user.Context(nil)
                if err != nil {
                    log.Fatalf("Failed to get context: %v", err)
                }
                fmt.Printf("User context: %s
            ", context)

            }

          label: Go
components:
  schemas:
    UserContextDataResponse:
      properties:
        data:
          anyOf:
            - $ref: '#/components/schemas/ContextData'
            - type: 'null'
          description: Response containing user context
        errno:
          $ref: '#/components/schemas/CODE'
          description: Error code, 0 means success
          default: 0
        errmsg:
          type: string
          title: Errmsg
          description: Error message, empty when success
          default: ''
      type: object
      title: UserContextDataResponse
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    ContextData:
      properties:
        context:
          type: string
          title: Context
          description: Context string
      type: object
      required:
        - context
      title: ContextData
    CODE:
      type: integer
      enum:
        - 0
        - 400
        - 401
        - 403
        - 404
        - 405
        - 409
        - 422
        - 500
        - 501
        - 502
        - 503
        - 504
        - 520
      title: CODE
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer

````