Skip to content

LangMem Client Reference

LangMem provides async and sync implementations of a client to interact with the service.

To install:

pip install -U langmem

You can either manually provide the api_url and api_key when initializing the client, or set the environment variables.

export LANGMEM_API_URL=<your-instance>
export LANGMEM_API_KEY=<your-api-key>

AsyncClient

The Async Langmem client.

Examples:

Basic usage:

    >>> from langmem import AsyncClient
    >>> from pydantic import BaseModel, Field
    >>> client = AsyncClient()
    >>> class UserProfile(BaseModel):
    ...     name: str = Field(description="The user's name")
    ...     age: int = Field(description="The user's age")
    ...     interests: List[str] = Field(description="The user's interests")
    ...     relationships: Dict[str, str] = Field(
    ...         description="The user's friends, family, pets,and other relationships."
    ...     )
    >>> memory_function = await client.create_memory_function(
    ...     UserProfile,
    ...     target_type="user_state",
    ...     name="User Profile",
    ... )
    >>> user_id = uuid.uuid4()
    >>> user_name = "Will"
    >>> messages = [
    ...     {
    ...         "role": "user",
    ...         "content": "Did you know pikas make their own haypiles?",
    ...         "name": "Will",
    ...         "metadata": {"user_id": user_id},
    ...     },
    ...     {
    ...         "role": "assistant",
    ...         "content": "Yes! And did you know they're actually related to rabbits?",
    ...     },
    ...     {
    ...         "role": "user",
    ...         "content": "I did! More people should know this important knowledge.",
    ...         "name": "Will",
    ...         "metadata": {"user_id": user_id},
    ...     },
    ... ]
    >>> thread_id = uuid.uuid4()
    >>> await client.add_messages(thread_id, messages)
    >>> await client.trigger_all_for_thread(thread_id)
    >>> await client.get_user_memory(user_id, memory_function_id=memory_function["id"])
    >>> # Or query the unstructured memory
    >>> await client.query_user_memory(user_id, "pikas", k=1)

    Query user memories semantically:

    >>> await client.query_user_memory(
    ...     user_id=user_id,
    ...     text="What does the user think about rabbits?",
    ...     memory_function_ids=[belief_function["id"]],
    ...     k=3,
    ... )

    Create a thread summary memory function:

    >>> class ConversationSummary(BaseModel):
    ...     title: str = Field(description="Distinct for the conversation.")
    ...     summary: str = Field(description="High level summary of the interactions.")
    ...     topic: List[str] = Field(
    ...         description="Tags for topics discussed in this conversation."
    ...     )
    >>> thread_summary_function = await client.create_memory_function(
    ...     ConversationSummary, target_type="thread_summary"
    ... )

    Fetch thread messages:

    >>> messages = client.list_messages(thread_id=thread_id)
    >>> async for message in messages:
    ...     print(message)
Source code in langmem/client.py
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
class AsyncClient:
    """The Async Langmem client.

    Examples:

        Basic usage:

            >>> from langmem import AsyncClient
            >>> from pydantic import BaseModel, Field
            >>> client = AsyncClient()
            >>> class UserProfile(BaseModel):
            ...     name: str = Field(description="The user's name")
            ...     age: int = Field(description="The user's age")
            ...     interests: List[str] = Field(description="The user's interests")
            ...     relationships: Dict[str, str] = Field(
            ...         description="The user's friends, family, pets,and other relationships."
            ...     )
            >>> memory_function = await client.create_memory_function(
            ...     UserProfile,
            ...     target_type="user_state",
            ...     name="User Profile",
            ... )
            >>> user_id = uuid.uuid4()
            >>> user_name = "Will"
            >>> messages = [
            ...     {
            ...         "role": "user",
            ...         "content": "Did you know pikas make their own haypiles?",
            ...         "name": "Will",
            ...         "metadata": {"user_id": user_id},
            ...     },
            ...     {
            ...         "role": "assistant",
            ...         "content": "Yes! And did you know they're actually related to rabbits?",
            ...     },
            ...     {
            ...         "role": "user",
            ...         "content": "I did! More people should know this important knowledge.",
            ...         "name": "Will",
            ...         "metadata": {"user_id": user_id},
            ...     },
            ... ]
            >>> thread_id = uuid.uuid4()
            >>> await client.add_messages(thread_id, messages)
            >>> await client.trigger_all_for_thread(thread_id)
            >>> await client.get_user_memory(user_id, memory_function_id=memory_function["id"])
            >>> # Or query the unstructured memory
            >>> await client.query_user_memory(user_id, "pikas", k=1)

            Query user memories semantically:

            >>> await client.query_user_memory(
            ...     user_id=user_id,
            ...     text="What does the user think about rabbits?",
            ...     memory_function_ids=[belief_function["id"]],
            ...     k=3,
            ... )

            Create a thread summary memory function:

            >>> class ConversationSummary(BaseModel):
            ...     title: str = Field(description="Distinct for the conversation.")
            ...     summary: str = Field(description="High level summary of the interactions.")
            ...     topic: List[str] = Field(
            ...         description="Tags for topics discussed in this conversation."
            ...     )
            >>> thread_summary_function = await client.create_memory_function(
            ...     ConversationSummary, target_type="thread_summary"
            ... )

            Fetch thread messages:

            >>> messages = client.list_messages(thread_id=thread_id)
            >>> async for message in messages:
            ...     print(message)
    """

    __slots__ = ["api_key", "client"]

    def __init__(self, api_url: Optional[str] = None, api_key: Optional[str] = None):
        self.api_key = api_key or os.environ.get("LANGMEM_API_KEY")
        base_url = _ensure_url(api_url)
        self.client = httpx.AsyncClient(
            base_url=base_url,
            headers=self._headers,
            timeout=DEFAULT_TIMEOUT,
        )

    @property
    def _headers(self):
        if self.api_key is None:
            return {}
        return {
            "x-api-key": self.api_key,
        }

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
        await self.client.aclose()

    async def create_user(
        self,
        *,
        user_id: ID_T,
        name: str,
        tags: Optional[Sequence[str]] = None,
        metadata: Dict[str, str] = {},
    ) -> Dict[str, Any]:
        """Create a user.

        Args:
            user_id (ID_T): The user's ID.
            name (str): The user's name.
            tags (Optional[Sequence[str]], optional): The user's tags. Defaults to None.
            metadata (Dict[str, str], optional): The user's metadata. Defaults to {}.

        Returns:
            Dict[str, Any]: The user's data.
        """

        data = {
            "id": user_id,
            "name": name,
            "tags": tags,
            "metadata": metadata,
        }
        response = await self.client.post("/users", json=data)

        return response.json()

    async def get_user(self, user_id: ID_T) -> Dict[str, Any]:
        """Get a user.

        Args:
            user_id (ID_T): The user's ID.

        Returns:
            Dict[str, Any]: The user's data.
        """

        response = await self.client.get(f"/users/{_as_uuid(user_id)}")
        raise_for_status_with_text(response)
        return response.json()

    async def update_user(
        self,
        user_id: ID_T,
        *,
        name: Optional[str] = None,
        tags: Optional[Sequence[str]] = None,
        metadata: Optional[Dict[str, str]] = None,
    ) -> Dict[str, Any]:
        """Update a user.

        Args:
            user_id (ID_T): The user's ID.
            name (Optional[str], optional): The user's name. Defaults to None.
            tags (Optional[Sequence[str]], optional): The user's tags. Defaults to None.
            metadata (Optional[Dict[str, str]], optional): The user's metadata. Defaults to None.

        Returns:
            Dict[str, Any]: The user's data.
        """

        data: Dict[str, Any] = {}
        if name is not None:
            data["name"] = name
        if tags is not None:
            data["tags"] = tags
        if metadata is not None:
            data["metadata"] = metadata
        response = await self.client.patch(f"/users/{_as_uuid(user_id)}", json=data)
        raise_for_status_with_text(response)
        return response.json()

    async def list_users(
        self,
        *,
        name: Optional[Sequence[str]] = None,
        id: Optional[Sequence[ID_T]] = None,
    ) -> List[Dict[str, Any]]:
        """List users.

        Args:
            name (Optional[Sequence[str]], optional): The user's name. Defaults to None.
            id (Optional[Sequence[ID_T]], optional): The user's ID. Defaults to None.

        Returns:
            List[Dict[str, Any]]: The users' data.
        """

        params = {
            "name": name,
            "id": id,
        }

        response = await self.client.post(
            "/users/query",
            json=params,
            headers={"Content-Type": "application/json"},
        )
        raise_for_status_with_text(response)
        return response.json()["users"]

    async def list_user_memory(self, user_id: ID_T) -> List[Dict[str, Any]]:
        """List a user's memory.

        Args:
            user_id (ID_T): The user's ID.

        Returns:
            List[Dict[str, Any]]: The user's memory.
        """

        response = await self.client.get(f"/users/{_as_uuid(user_id)}/memory")
        raise_for_status_with_text(response)
        return response.json()

    async def trigger_all_for_user(self, user_id: ID_T) -> None:
        """Trigger all memory functions for a user.

        Args:
            user_id (ID_T): The user's ID.
        """

        response = await self.client.post(f"/users/{_as_uuid(user_id)}/trigger-all")
        raise_for_status_with_text(response)
        return response.json()

    async def delete_user_memory(
        self,
        *,
        user_id: ID_T,
        memory_function_id: ID_T,
    ) -> None:
        """Delete a user's memory.

        Args:
            user_id (ID_T): The user's ID.
            memory_function_id (ID_T): The memory function's ID.
        """

        response = await self.client.delete(
            f"/users/{_as_uuid(user_id)}/memory/{_as_uuid(memory_function_id)}/state"
        )
        raise_for_status_with_text(response)
        return response.json()

    async def update_user_memory(
        self,
        user_id: ID_T,
        *,
        memory_function_id: ID_T,
        state: dict,
    ) -> None:
        """Update a user's memory.

        Args:
            user_id (ID_T): The user's ID.
            memory_function_id (ID_T): The memory function's ID.
            state (dict): The memory state.
        """
        response = await self.client.put(
            f"/users/{_as_uuid(user_id)}/memory/{_as_uuid(memory_function_id)}/state",
            data=json.dumps(  # type: ignore[arg-type]
                {"state": state},
                default=_default_serializer,
            ),
        )
        raise_for_status_with_text(response)
        return response.json()

    async def get_user_memory(
        self,
        user_id: ID_T,
        *,
        memory_function_id: ID_T,
    ) -> dict:
        """Get a user's memory state.

        This method retrieves the current memory state for a specific user and memory function.
        It is faster than querying and useful for "user_state" type memories.

        Args:
            user_id (ID_T): The user's ID.
            memory_function_id (ID_T): The memory function's ID.

        Returns:
            dict: The memory state.

        Examples:

            >>> from langmem import AsyncClient
            >>> client = AsyncClient()
            >>> user_id = "2d1a8daf-2319-4e3e-9fd0-6d7981ceb8a6"
            >>> memory_function_id = "cb217ff7-963e-44fc-b222-01f01058d64b"
            >>> await client.get_user_memory(user_id, memory_function_id=memory_function_id)
        """
        response = await self.client.get(
            f"/users/{_as_uuid(user_id)}/memory/{_as_uuid(memory_function_id)}/state"
        )
        raise_for_status_with_text(response)
        return response.json()

    async def query_user_memory(
        self,
        user_id: ID_T,
        text: str,
        k: int = 200,
        memory_function_ids: Optional[Sequence[ID_T]] = None,
        weights: Optional[dict] = None,
        states_to_return: Optional[Sequence[ID_T]] = None,
        thread_summaries: Optional[Sequence[ID_T]] = None,
        thread_summaries_k: Optional[int] = None,
    ) -> List:
        """Query a user's memory.

        Args:
            user_id (ID_T): The user's ID.
            text (str): The query text.
            k (int, optional): The number of results to return. Defaults to 200.
            memory_function_ids (Optional[Sequence[ID_T]], optional): Semantic memory outputs
                    to include. Defaults to None, meaning just the unstructured memories.
            weights (Optional[dict], optional): Weights for the different memory types.
                    Backend default equally weights relevance, recency, and importance.
                    Defaults to None.
            states_to_return (Optional[Sequence[ID_T]], optional): The user state
                    memory function IDs to include in the response.
            thread_summaries (Optional[Sequence[ID_T]], optional): The thread
                    summary memory function IDs to include in the response, if any.
            thread_summaries_k (Optional[int], optional): If you include thread summaries,
                this controls the number of threads whose summaries you wish to return per
                thread summary memory function. Defaults to None.

        Returns:
            List: The query results.


        Examples:

            Query a user's semantic memory:
                >>> from langmem import AsyncClient
                >>> client = AsyncClient()
                >>> user_id = uuid.uuid4()
                >>> await client.query_user_memory(user_id, text="pikas", k=10)

            Query the memory, ignoring recency or perceived importance:

                >>> await client.query_user_memory(
                ...     user_id,
                ...     text="pikas",
                ...     k=10,
                ...     weights={"relevance": 1.0, "recency": 0.0, "importance": 0.0},
                ... )

            Include user state memories in the response (to save the number of API calls):
                >>> mem_functions_ = client.list_memory_functions(target_type="user")
                >>> mem_functions = []
                >>> async for mem_function in mem_functions_:
                ...     if mem_function["type"] == "user_state":
                ...         mem_functions.append(mem_function["id"])
                >>> await client.query_user_memory(
                ...     user_id,
                ...     text="pikas",
                ...     k=10,
                ...     states_to_return=mem_functions,
                ... )

            Query over user_append_state memories:
                >>> mem_functions_ = client.list_memory_functions(target_type="user")
                >>> mem_functions = []
                >>> async for mem_function in mem_functions_:
                ...     if mem_function["type"] == "user_append_state":
                ...         mem_functions.append(mem_function["id"])
                >>> await client.query_user_memory(
                ...     user_id,
                ...     text="pikas",
                ...     k=10,
                ...     memory_function_ids=mem_functions,
                ... )

            Include thread summaries for the most recent threads:
                >>> mem_functions_ = client.list_memory_functions(target_type="thread")
                >>> mem_functions = []
                >>> async for mem_function in mem_functions_:
                ...     mem_functions.append(mem_function["id"])
                >>> await client.query_user_memory(
                ...     user_id,
                ...     text="pikas",
                ...     k=10,
                ...     thread_summaries=mem_functions,
                ...     thread_summaries_k=5,
                ... )

        """
        thread_query: Optional[dict] = None
        if thread_summaries is not None:
            thread_query = {
                "memory_function_ids": thread_summaries,
            }
            if thread_summaries_k is not None:
                thread_query["k"] = thread_summaries_k

        response = await self.client.post(
            f"/users/{_as_uuid(user_id)}/memory/query",
            data=json.dumps(  # type: ignore[arg-type]
                {
                    "text": text,
                    "k": k,
                    "memory_function_ids": memory_function_ids,
                    "weights": weights,
                    "state": states_to_return,
                },
                default=_default_serializer,
            ),
        )
        raise_for_status_with_text(response)
        return response.json()

    async def create_memory_function(
        self,
        parameters: Union[BaseModel, dict],
        *,
        target_type: str = "user_state",
        name: Optional[str] = None,
        description: Optional[str] = None,
        custom_instructions: Optional[str] = None,
        function_id: Optional[ID_T] = None,
    ) -> Dict[str, Any]:
        """Create a memory function.

        Args:
            parameters (Union[BaseModel, dict]): The memory function's parameters.
            target_type (str, optional): The memory function's target type. Defaults to "user_state".
            name (Optional[str], optional): The memory function's name. Defaults to None.
            description (Optional[str], optional): The memory function's description. Defaults to None.
            custom_instructions (Optional[str], optional): The memory function's custom instructions. Defaults to None.
            function_id (Optional[ID_T], optional): The memory function's ID. Defaults to None.

        Returns:
            Dict[str, Any]: The memory function's data.

        Examples:

            Create a user profile memory function:

                >>> from pydantic import BaseModel, Field
                >>> from langmem import Client
                >>> client = AsyncClient()
                >>> class UserProfile(BaseModel):
                ...     name: str = Field(description="The user's name")
                ...     age: int = Field(description="The user's age")
                ...     interests: List[str] = Field(description="The user's interests")
                ...     relationships: Dict[str, str] = Field(
                ...         description="The user's friends, family, pets,and other relationships."
                ...     )
                >>> memory_function = await client.create_memory_function(
                ...     UserProfile,
                ...     target_type="user_state",
                ...     name="User Profile",
                ... )

            Create an append-only user memory function:

                >>> class FormativeEvent(BaseModel):
                ...     event: str = Field(description="The formative event that occurred.")
                ...     impact: str = Field(description="How this event impacted the user.")
                >>> event_function = await client.create_memory_function(
                ...     FormativeEvent, target_type="user_append_state"
                ... )

        """
        if isinstance(parameters, dict):
            params: dict = parameters

        else:
            params = parameters.model_json_schema()

        function_schema = {
            "name": name or params.pop("title", ""),
            "description": description or params.pop("description", ""),
            "parameters": params,
        }

        data = {
            "type": target_type,
            "custom_instructions": custom_instructions,
            "id": str(function_id) if function_id else str(uuid.uuid4()),
            "schema": function_schema,
        }
        response = await self.client.post("/memory-functions", json=data)
        raise_for_status_with_text(response)
        return response.json()

    async def get_memory_function(self, memory_function_id: ID_T) -> Dict[str, Any]:
        """Get a memory function.

        Args:
            memory_function_id (ID_T): The memory function's ID.

        Returns:
            Dict[str, Any]: The memory function's data.
        """

        response = await self.client.get(
            f"/memory-functions/{_as_uuid(memory_function_id)}"
        )
        raise_for_status_with_text(response)
        return response.json()

    async def list_memory_functions(
        self, *, target_type: Optional[Sequence[str]] = None
    ) -> AsyncGenerator[Dict[str, Any], None]:
        """List memory functions.

        Args:
            target_type (Sequence[str], optional): The memory function's target type. Defaults to None.

        Returns:
            AsyncGenerator[Dict[str, Any], None]: The memory functions' data.
        """

        body = {}
        if target_type is not None:
            body["target_type"] = (
                [target_type] if isinstance(target_type, str) else target_type
            )
        cursor = None
        while True:
            if cursor is not None:
                body["cursor"] = cursor
            response = await self.client.post("/memory-functions/query", json=body)
            raise_for_status_with_text(response)
            data = response.json()
            for function in data.get("memory_functions", []):
                yield function
            cursor = data.get("next_cursor")
            if cursor is None:
                break

    async def update_memory_function(
        self,
        memory_function_id: ID_T,
        *,
        name: Optional[str] = None,
        schema: Optional[Union[BaseModel, dict]] = None,
        custom_instructions: Optional[str] = None,
        description: Optional[str] = None,
        function_type: Optional[str] = None,
        status: Optional[Literal["active", "disabled"]] = None,
    ) -> Dict[str, Any]:
        """Update a memory function.

        Args:
            memory_function_id (ID_T): The memory function's ID.
            name (Optional[str], optional): The memory function's name. Defaults to None.
            schema (Optional[Union[BaseModel, dict]], optional): The memory function's schema. Defaults to None.
            custom_instructions (Optional[str], optional): The memory function's custom instructions. Defaults to None.
            description (Optional[str], optional): The memory function's description. Defaults to None.
            function_type (Optional[str], optional): The memory function's type. Defaults to None.
            status: Optional[Literal["active", "disabled"]], optional): The memory function's status.
                Use to activate or disable the memory function. Disabled memory functions no longer
                trigger on new threads.

        Returns:
            Dict[str, Any]: The memory function's data.
        """

        data: Dict[str, Any] = {
            "name": name,
            "description": description,
            "custom_instructions": custom_instructions,
            "type": function_type,
            "status": status,
        }
        if schema is not None:
            data["function"] = (
                schema
                if isinstance(schema, dict)
                else json.loads(schema.model_dump_json())
            )
        response = await self.client.patch(
            f"/memory-functions/{_as_uuid(memory_function_id)}",
            json={k: v for k, v in data.items() if v is not None},
        )
        raise_for_status_with_text(response)
        return response.json()

    async def delete_memory_function(
        self,
        memory_function_id: ID_T,
    ) -> None:
        """Delete a memory function.

        Args:
            memory_function_id (ID_T): The memory function's ID.
        """
        response = await self.client.delete(
            f"/memory-functions/{_as_uuid(memory_function_id)}"
        )
        raise_for_status_with_text(response)
        return response.json()

    async def create_thread(
        self,
        *,
        thread_id: Optional[ID_T] = None,
        messages: Optional[Sequence[Dict[str, Any]]] = None,
        metadata: Optional[Dict[str, str]] = None,
    ) -> Dict[str, Any]:
        """Create a thread.

        Args:
            thread_id (ID_T): The thread's ID.
            messages (Sequence[Dict[str, Any]]): A sequence of dictionaries representing the messages in the thread.
            metadata (Dict[str, str]): Additional metadata associated with the thread.

        Returns:
            Dict[str, Any]: The thread's data.
        """

        data = {
            "id": thread_id,
            "messages": messages,
            "metadata": metadata,
        }
        response = await self.client.post("/threads", json=data)
        raise_for_status_with_text(response)
        return response.json()

    async def add_messages(
        self, thread_id: ID_T, *, messages: Sequence[schemas.MESSAGE_LIKE]
    ) -> None:
        """Add messages to a thread.

        This method allows you to add messages to a specific thread identified by its ID.

        Args:
            thread_id (ID_T): The ID of the thread to which the messages will be added.
            messages (Sequence[Dict[str, Any]]): A sequence of dictionaries representing the messages to be added. Each dictionary should contain the following keys:
                - "role" (str): The role of the message sender (e.g., "user", "bot").
                - "content" (str): The content of the message.
                - "name" (str): The name of the message sender.
                - "metadata" (dict): Additional metadata associated with the message.

        Returns:
            None

        Examples:
            Add messages in a new thread:

            >>> from langmem import Client
            >>> client = Client()
            >>> messages = [
            ...     {
            ...         "role": "user",
            ...         "content": "Did you know pikas make their own haypiles?",
            ...         "name": "Will",
            ...         "metadata": {"user_id": user_id},
            ...     },
            ...     {
            ...         "role": "assistant",
            ...         "content": "Yes, pikas are fascinating creatures!",
            ...         "name": "Bot",
            ...     },
            ... ]
            >>> await client.add_messages(thread_id, messages=messages)
        """

        data = {"messages": messages}
        response = await self.client.post(
            f"/threads/{_as_uuid(thread_id)}/add_messages",
            data=json.dumps(data, default=_default_serializer),  # type: ignore[arg-type]
        )
        raise_for_status_with_text(response)
        return response.json()

    async def get_thread(self, thread_id: ID_T) -> Dict[str, Any]:
        """Get a thread.

        Args:
            thread_id (ID_T): The thread's ID.

        Returns:
            Dict[str, Any]: The thread's data.
        """

        response = await self.client.get(f"/threads/{_as_uuid(thread_id)}")
        raise_for_status_with_text(response)
        return response.json()

    async def list_threads(self) -> Iterable[Dict[str, Any]]:
        """List threads.

        Returns:
            Iterable[Dict[str, Any]]: The threads' data.
        """

        response = await self.client.get("/threads")
        raise_for_status_with_text(response)
        return response.json()

    async def list_thread_memory(self, thread_id: ID_T) -> List[Dict[str, Any]]:
        """List a thread's memory.

        This method retrieves all memories associated with a given thread.
        It will return outputs from all memory function types defined for the thread.

        Args:
            thread_id (ID_T): The thread's ID.

        Returns:
            List[Dict[str, Any]]: The thread's memory.

        Examples:

            >>> from langmem import AsyncClient
            >>> client = AsyncClient()
            >>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
            >>> memories = client.list_thread_memory(thread_id)
            >>> async for memory in memories:
            ...     print(memory)
        """

        response = await self.client.get(f"/threads/{_as_uuid(thread_id)}/memory")
        raise_for_status_with_text(response)
        return response.json()

    async def get_thread_memory(
        self,
        thread_id: ID_T,
        *,
        memory_function_id: ID_T,
    ) -> dict:
        """Get a thread's memory state.

        This method retrieves the current memory state for a specific thread and memory function.
        It is faster than querying and useful for "thread_state" type memories.

        Args:
            thread_id (ID_T): The thread's ID.
            memory_function_id (ID_T): The memory function's ID.

        Returns:
            dict: The memory state.

        Examples:

            >>> from langmem import AsyncClient
            >>> client = AsyncClient()
            >>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
            >>> memory_function_id = "cb217ff7-963e-44fc-b222-01f01058d64b"
            >>> await client.get_thread_memory(thread_id, memory_function_id=memory_function_id)
        """
        response = await self.client.get(
            f"/threads/{_as_uuid(thread_id)}/memory/{_as_uuid(memory_function_id)}/state"
        )
        raise_for_status_with_text(response)
        return response.json()

    async def trigger_all_for_thread(self, thread_id: ID_T) -> None:
        """Trigger all memory functions for a thread.

        This method eagerly processes any pending memories for the given thread.
        It will trigger all memory function types defined for the thread.

        Args:
            thread_id (ID_T): The thread's ID.

        Examples:

            >>> from langmem import Client
            >>> client = Client()
            >>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
            >>> await client.trigger_all_for_thread(thread_id)
        """

        response = await self.client.post(f"/threads/{_as_uuid(thread_id)}/trigger-all")
        raise_for_status_with_text(response)
        return response.json()

    async def add_thread_state(
        self, thread_id: ID_T, state: Dict[str, Any], *, key: Optional[str] = None
    ) -> None:
        """Add a thread state.

        Args:
            thread_id (ID_T): The thread's ID.
            state (Dict[str, Any]): The thread state.
        """

        response = await self.client.post(
            f"/threads/{_as_uuid(thread_id)}/thread_state",
            json={"state": state, "key": key},
        )
        raise_for_status_with_text(response)
        return response.json()

    async def get_thread_state(
        self, thread_id: ID_T, *, key: Optional[str] = None
    ) -> dict:
        """Get a thread state.

        Args:
            thread_id (ID_T): The thread's ID.

        Returns:
            GetThreadStateResponse: The thread state.
        """
        response = await self.client.post(
            f"/threads/{_as_uuid(thread_id)}/thread_state/query", json={"key": key}
        )
        raise_for_status_with_text(response)
        return response.json()

    async def list_messages(
        self,
        thread_id: ID_T,
        *,
        response_format: Optional[Literal["openai", "langmem"]] = None,
        ascending_order: Optional[bool] = None,
        page_size: Optional[int] = None,
        limit: Optional[int] = None,
    ) -> AsyncGenerator[Dict[str, Any], None]:
        """List a thread's messages.

        Args:
            thread_id (ID_T): The thread's ID.
            response_format (Optional[Literal["openai", "langmem"]], optional): The response format.
                Defaults to None, which is the openai format.
            ascending_order (Optional[bool], optional): Whether to return messages in ascending order.
            page_size (Optional[int], optional): The page size. Defaults to None.
            limit (Optional[int], optional): The maximum number of messages to return. Defaults to None.

        Returns:
            AsyncGenerator[Dict[str, Any], None]: The messages' data.
        """

        params: Dict[str, Any] = {
            "response_format": response_format,
            "page_size": page_size,
            "ascending_order": ascending_order,
        }
        params = {k: v for k, v in params.items() if v is not None}

        # Handle pagination for large threads
        cursor = None
        idx = 0
        while True:
            if cursor is not None:
                params["cursor"] = cursor
            response = await self.client.get(
                f"/threads/{_as_uuid(thread_id)}/messages", params=params
            )
            raise_for_status_with_text(response)
            data = response.json()
            for message in data.get("messages", []):
                yield message
                idx += 1
                if limit is not None and idx >= limit:
                    break
            cursor = data.get("next_cursor")
            if cursor is None or (limit is not None and idx >= limit):
                break

create_user(*, user_id, name, tags=None, metadata={}) async

Create a user.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
name str

The user's name.

required
tags Optional[Sequence[str]]

The user's tags. Defaults to None.

None
metadata Dict[str, str]

The user's metadata. Defaults to {}.

{}

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The user's data.

Source code in langmem/client.py
async def create_user(
    self,
    *,
    user_id: ID_T,
    name: str,
    tags: Optional[Sequence[str]] = None,
    metadata: Dict[str, str] = {},
) -> Dict[str, Any]:
    """Create a user.

    Args:
        user_id (ID_T): The user's ID.
        name (str): The user's name.
        tags (Optional[Sequence[str]], optional): The user's tags. Defaults to None.
        metadata (Dict[str, str], optional): The user's metadata. Defaults to {}.

    Returns:
        Dict[str, Any]: The user's data.
    """

    data = {
        "id": user_id,
        "name": name,
        "tags": tags,
        "metadata": metadata,
    }
    response = await self.client.post("/users", json=data)

    return response.json()

get_user(user_id) async

Get a user.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The user's data.

Source code in langmem/client.py
async def get_user(self, user_id: ID_T) -> Dict[str, Any]:
    """Get a user.

    Args:
        user_id (ID_T): The user's ID.

    Returns:
        Dict[str, Any]: The user's data.
    """

    response = await self.client.get(f"/users/{_as_uuid(user_id)}")
    raise_for_status_with_text(response)
    return response.json()

update_user(user_id, *, name=None, tags=None, metadata=None) async

Update a user.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
name Optional[str]

The user's name. Defaults to None.

None
tags Optional[Sequence[str]]

The user's tags. Defaults to None.

None
metadata Optional[Dict[str, str]]

The user's metadata. Defaults to None.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The user's data.

Source code in langmem/client.py
async def update_user(
    self,
    user_id: ID_T,
    *,
    name: Optional[str] = None,
    tags: Optional[Sequence[str]] = None,
    metadata: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
    """Update a user.

    Args:
        user_id (ID_T): The user's ID.
        name (Optional[str], optional): The user's name. Defaults to None.
        tags (Optional[Sequence[str]], optional): The user's tags. Defaults to None.
        metadata (Optional[Dict[str, str]], optional): The user's metadata. Defaults to None.

    Returns:
        Dict[str, Any]: The user's data.
    """

    data: Dict[str, Any] = {}
    if name is not None:
        data["name"] = name
    if tags is not None:
        data["tags"] = tags
    if metadata is not None:
        data["metadata"] = metadata
    response = await self.client.patch(f"/users/{_as_uuid(user_id)}", json=data)
    raise_for_status_with_text(response)
    return response.json()

list_users(*, name=None, id=None) async

List users.

Parameters:

Name Type Description Default
name Optional[Sequence[str]]

The user's name. Defaults to None.

None
id Optional[Sequence[ID_T]]

The user's ID. Defaults to None.

None

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: The users' data.

Source code in langmem/client.py
async def list_users(
    self,
    *,
    name: Optional[Sequence[str]] = None,
    id: Optional[Sequence[ID_T]] = None,
) -> List[Dict[str, Any]]:
    """List users.

    Args:
        name (Optional[Sequence[str]], optional): The user's name. Defaults to None.
        id (Optional[Sequence[ID_T]], optional): The user's ID. Defaults to None.

    Returns:
        List[Dict[str, Any]]: The users' data.
    """

    params = {
        "name": name,
        "id": id,
    }

    response = await self.client.post(
        "/users/query",
        json=params,
        headers={"Content-Type": "application/json"},
    )
    raise_for_status_with_text(response)
    return response.json()["users"]

list_user_memory(user_id) async

List a user's memory.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: The user's memory.

Source code in langmem/client.py
async def list_user_memory(self, user_id: ID_T) -> List[Dict[str, Any]]:
    """List a user's memory.

    Args:
        user_id (ID_T): The user's ID.

    Returns:
        List[Dict[str, Any]]: The user's memory.
    """

    response = await self.client.get(f"/users/{_as_uuid(user_id)}/memory")
    raise_for_status_with_text(response)
    return response.json()

trigger_all_for_user(user_id) async

Trigger all memory functions for a user.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
Source code in langmem/client.py
async def trigger_all_for_user(self, user_id: ID_T) -> None:
    """Trigger all memory functions for a user.

    Args:
        user_id (ID_T): The user's ID.
    """

    response = await self.client.post(f"/users/{_as_uuid(user_id)}/trigger-all")
    raise_for_status_with_text(response)
    return response.json()

delete_user_memory(*, user_id, memory_function_id) async

Delete a user's memory.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
memory_function_id ID_T

The memory function's ID.

required
Source code in langmem/client.py
async def delete_user_memory(
    self,
    *,
    user_id: ID_T,
    memory_function_id: ID_T,
) -> None:
    """Delete a user's memory.

    Args:
        user_id (ID_T): The user's ID.
        memory_function_id (ID_T): The memory function's ID.
    """

    response = await self.client.delete(
        f"/users/{_as_uuid(user_id)}/memory/{_as_uuid(memory_function_id)}/state"
    )
    raise_for_status_with_text(response)
    return response.json()

update_user_memory(user_id, *, memory_function_id, state) async

Update a user's memory.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
memory_function_id ID_T

The memory function's ID.

required
state dict

The memory state.

required
Source code in langmem/client.py
async def update_user_memory(
    self,
    user_id: ID_T,
    *,
    memory_function_id: ID_T,
    state: dict,
) -> None:
    """Update a user's memory.

    Args:
        user_id (ID_T): The user's ID.
        memory_function_id (ID_T): The memory function's ID.
        state (dict): The memory state.
    """
    response = await self.client.put(
        f"/users/{_as_uuid(user_id)}/memory/{_as_uuid(memory_function_id)}/state",
        data=json.dumps(  # type: ignore[arg-type]
            {"state": state},
            default=_default_serializer,
        ),
    )
    raise_for_status_with_text(response)
    return response.json()

get_user_memory(user_id, *, memory_function_id) async

Get a user's memory state.

This method retrieves the current memory state for a specific user and memory function. It is faster than querying and useful for "user_state" type memories.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
memory_function_id ID_T

The memory function's ID.

required

Returns:

Name Type Description
dict dict

The memory state.

Examples:

>>> from langmem import AsyncClient
>>> client = AsyncClient()
>>> user_id = "2d1a8daf-2319-4e3e-9fd0-6d7981ceb8a6"
>>> memory_function_id = "cb217ff7-963e-44fc-b222-01f01058d64b"
>>> await client.get_user_memory(user_id, memory_function_id=memory_function_id)
Source code in langmem/client.py
async def get_user_memory(
    self,
    user_id: ID_T,
    *,
    memory_function_id: ID_T,
) -> dict:
    """Get a user's memory state.

    This method retrieves the current memory state for a specific user and memory function.
    It is faster than querying and useful for "user_state" type memories.

    Args:
        user_id (ID_T): The user's ID.
        memory_function_id (ID_T): The memory function's ID.

    Returns:
        dict: The memory state.

    Examples:

        >>> from langmem import AsyncClient
        >>> client = AsyncClient()
        >>> user_id = "2d1a8daf-2319-4e3e-9fd0-6d7981ceb8a6"
        >>> memory_function_id = "cb217ff7-963e-44fc-b222-01f01058d64b"
        >>> await client.get_user_memory(user_id, memory_function_id=memory_function_id)
    """
    response = await self.client.get(
        f"/users/{_as_uuid(user_id)}/memory/{_as_uuid(memory_function_id)}/state"
    )
    raise_for_status_with_text(response)
    return response.json()

query_user_memory(user_id, text, k=200, memory_function_ids=None, weights=None, states_to_return=None, thread_summaries=None, thread_summaries_k=None) async

Query a user's memory.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
text str

The query text.

required
k int

The number of results to return. Defaults to 200.

200
memory_function_ids Optional[Sequence[ID_T]]

Semantic memory outputs to include. Defaults to None, meaning just the unstructured memories.

None
weights Optional[dict]

Weights for the different memory types. Backend default equally weights relevance, recency, and importance. Defaults to None.

None
states_to_return Optional[Sequence[ID_T]]

The user state memory function IDs to include in the response.

None
thread_summaries Optional[Sequence[ID_T]]

The thread summary memory function IDs to include in the response, if any.

None
thread_summaries_k Optional[int]

If you include thread summaries, this controls the number of threads whose summaries you wish to return per thread summary memory function. Defaults to None.

None

Returns:

Name Type Description
List List

The query results.

Examples:

Query a user's semantic memory:
    >>> from langmem import AsyncClient
    >>> client = AsyncClient()
    >>> user_id = uuid.uuid4()
    >>> await client.query_user_memory(user_id, text="pikas", k=10)

Query the memory, ignoring recency or perceived importance:

    >>> await client.query_user_memory(
    ...     user_id,
    ...     text="pikas",
    ...     k=10,
    ...     weights={"relevance": 1.0, "recency": 0.0, "importance": 0.0},
    ... )

Include user state memories in the response (to save the number of API calls):
    >>> mem_functions_ = client.list_memory_functions(target_type="user")
    >>> mem_functions = []
    >>> async for mem_function in mem_functions_:
    ...     if mem_function["type"] == "user_state":
    ...         mem_functions.append(mem_function["id"])
    >>> await client.query_user_memory(
    ...     user_id,
    ...     text="pikas",
    ...     k=10,
    ...     states_to_return=mem_functions,
    ... )

Query over user_append_state memories:
    >>> mem_functions_ = client.list_memory_functions(target_type="user")
    >>> mem_functions = []
    >>> async for mem_function in mem_functions_:
    ...     if mem_function["type"] == "user_append_state":
    ...         mem_functions.append(mem_function["id"])
    >>> await client.query_user_memory(
    ...     user_id,
    ...     text="pikas",
    ...     k=10,
    ...     memory_function_ids=mem_functions,
    ... )

Include thread summaries for the most recent threads:
    >>> mem_functions_ = client.list_memory_functions(target_type="thread")
    >>> mem_functions = []
    >>> async for mem_function in mem_functions_:
    ...     mem_functions.append(mem_function["id"])
    >>> await client.query_user_memory(
    ...     user_id,
    ...     text="pikas",
    ...     k=10,
    ...     thread_summaries=mem_functions,
    ...     thread_summaries_k=5,
    ... )
Source code in langmem/client.py
async def query_user_memory(
    self,
    user_id: ID_T,
    text: str,
    k: int = 200,
    memory_function_ids: Optional[Sequence[ID_T]] = None,
    weights: Optional[dict] = None,
    states_to_return: Optional[Sequence[ID_T]] = None,
    thread_summaries: Optional[Sequence[ID_T]] = None,
    thread_summaries_k: Optional[int] = None,
) -> List:
    """Query a user's memory.

    Args:
        user_id (ID_T): The user's ID.
        text (str): The query text.
        k (int, optional): The number of results to return. Defaults to 200.
        memory_function_ids (Optional[Sequence[ID_T]], optional): Semantic memory outputs
                to include. Defaults to None, meaning just the unstructured memories.
        weights (Optional[dict], optional): Weights for the different memory types.
                Backend default equally weights relevance, recency, and importance.
                Defaults to None.
        states_to_return (Optional[Sequence[ID_T]], optional): The user state
                memory function IDs to include in the response.
        thread_summaries (Optional[Sequence[ID_T]], optional): The thread
                summary memory function IDs to include in the response, if any.
        thread_summaries_k (Optional[int], optional): If you include thread summaries,
            this controls the number of threads whose summaries you wish to return per
            thread summary memory function. Defaults to None.

    Returns:
        List: The query results.


    Examples:

        Query a user's semantic memory:
            >>> from langmem import AsyncClient
            >>> client = AsyncClient()
            >>> user_id = uuid.uuid4()
            >>> await client.query_user_memory(user_id, text="pikas", k=10)

        Query the memory, ignoring recency or perceived importance:

            >>> await client.query_user_memory(
            ...     user_id,
            ...     text="pikas",
            ...     k=10,
            ...     weights={"relevance": 1.0, "recency": 0.0, "importance": 0.0},
            ... )

        Include user state memories in the response (to save the number of API calls):
            >>> mem_functions_ = client.list_memory_functions(target_type="user")
            >>> mem_functions = []
            >>> async for mem_function in mem_functions_:
            ...     if mem_function["type"] == "user_state":
            ...         mem_functions.append(mem_function["id"])
            >>> await client.query_user_memory(
            ...     user_id,
            ...     text="pikas",
            ...     k=10,
            ...     states_to_return=mem_functions,
            ... )

        Query over user_append_state memories:
            >>> mem_functions_ = client.list_memory_functions(target_type="user")
            >>> mem_functions = []
            >>> async for mem_function in mem_functions_:
            ...     if mem_function["type"] == "user_append_state":
            ...         mem_functions.append(mem_function["id"])
            >>> await client.query_user_memory(
            ...     user_id,
            ...     text="pikas",
            ...     k=10,
            ...     memory_function_ids=mem_functions,
            ... )

        Include thread summaries for the most recent threads:
            >>> mem_functions_ = client.list_memory_functions(target_type="thread")
            >>> mem_functions = []
            >>> async for mem_function in mem_functions_:
            ...     mem_functions.append(mem_function["id"])
            >>> await client.query_user_memory(
            ...     user_id,
            ...     text="pikas",
            ...     k=10,
            ...     thread_summaries=mem_functions,
            ...     thread_summaries_k=5,
            ... )

    """
    thread_query: Optional[dict] = None
    if thread_summaries is not None:
        thread_query = {
            "memory_function_ids": thread_summaries,
        }
        if thread_summaries_k is not None:
            thread_query["k"] = thread_summaries_k

    response = await self.client.post(
        f"/users/{_as_uuid(user_id)}/memory/query",
        data=json.dumps(  # type: ignore[arg-type]
            {
                "text": text,
                "k": k,
                "memory_function_ids": memory_function_ids,
                "weights": weights,
                "state": states_to_return,
            },
            default=_default_serializer,
        ),
    )
    raise_for_status_with_text(response)
    return response.json()

create_memory_function(parameters, *, target_type='user_state', name=None, description=None, custom_instructions=None, function_id=None) async

Create a memory function.

Parameters:

Name Type Description Default
parameters Union[BaseModel, dict]

The memory function's parameters.

required
target_type str

The memory function's target type. Defaults to "user_state".

'user_state'
name Optional[str]

The memory function's name. Defaults to None.

None
description Optional[str]

The memory function's description. Defaults to None.

None
custom_instructions Optional[str]

The memory function's custom instructions. Defaults to None.

None
function_id Optional[ID_T]

The memory function's ID. Defaults to None.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The memory function's data.

Examples:

Create a user profile memory function:

    >>> from pydantic import BaseModel, Field
    >>> from langmem import Client
    >>> client = AsyncClient()
    >>> class UserProfile(BaseModel):
    ...     name: str = Field(description="The user's name")
    ...     age: int = Field(description="The user's age")
    ...     interests: List[str] = Field(description="The user's interests")
    ...     relationships: Dict[str, str] = Field(
    ...         description="The user's friends, family, pets,and other relationships."
    ...     )
    >>> memory_function = await client.create_memory_function(
    ...     UserProfile,
    ...     target_type="user_state",
    ...     name="User Profile",
    ... )

Create an append-only user memory function:

    >>> class FormativeEvent(BaseModel):
    ...     event: str = Field(description="The formative event that occurred.")
    ...     impact: str = Field(description="How this event impacted the user.")
    >>> event_function = await client.create_memory_function(
    ...     FormativeEvent, target_type="user_append_state"
    ... )
Source code in langmem/client.py
async def create_memory_function(
    self,
    parameters: Union[BaseModel, dict],
    *,
    target_type: str = "user_state",
    name: Optional[str] = None,
    description: Optional[str] = None,
    custom_instructions: Optional[str] = None,
    function_id: Optional[ID_T] = None,
) -> Dict[str, Any]:
    """Create a memory function.

    Args:
        parameters (Union[BaseModel, dict]): The memory function's parameters.
        target_type (str, optional): The memory function's target type. Defaults to "user_state".
        name (Optional[str], optional): The memory function's name. Defaults to None.
        description (Optional[str], optional): The memory function's description. Defaults to None.
        custom_instructions (Optional[str], optional): The memory function's custom instructions. Defaults to None.
        function_id (Optional[ID_T], optional): The memory function's ID. Defaults to None.

    Returns:
        Dict[str, Any]: The memory function's data.

    Examples:

        Create a user profile memory function:

            >>> from pydantic import BaseModel, Field
            >>> from langmem import Client
            >>> client = AsyncClient()
            >>> class UserProfile(BaseModel):
            ...     name: str = Field(description="The user's name")
            ...     age: int = Field(description="The user's age")
            ...     interests: List[str] = Field(description="The user's interests")
            ...     relationships: Dict[str, str] = Field(
            ...         description="The user's friends, family, pets,and other relationships."
            ...     )
            >>> memory_function = await client.create_memory_function(
            ...     UserProfile,
            ...     target_type="user_state",
            ...     name="User Profile",
            ... )

        Create an append-only user memory function:

            >>> class FormativeEvent(BaseModel):
            ...     event: str = Field(description="The formative event that occurred.")
            ...     impact: str = Field(description="How this event impacted the user.")
            >>> event_function = await client.create_memory_function(
            ...     FormativeEvent, target_type="user_append_state"
            ... )

    """
    if isinstance(parameters, dict):
        params: dict = parameters

    else:
        params = parameters.model_json_schema()

    function_schema = {
        "name": name or params.pop("title", ""),
        "description": description or params.pop("description", ""),
        "parameters": params,
    }

    data = {
        "type": target_type,
        "custom_instructions": custom_instructions,
        "id": str(function_id) if function_id else str(uuid.uuid4()),
        "schema": function_schema,
    }
    response = await self.client.post("/memory-functions", json=data)
    raise_for_status_with_text(response)
    return response.json()

get_memory_function(memory_function_id) async

Get a memory function.

Parameters:

Name Type Description Default
memory_function_id ID_T

The memory function's ID.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The memory function's data.

Source code in langmem/client.py
async def get_memory_function(self, memory_function_id: ID_T) -> Dict[str, Any]:
    """Get a memory function.

    Args:
        memory_function_id (ID_T): The memory function's ID.

    Returns:
        Dict[str, Any]: The memory function's data.
    """

    response = await self.client.get(
        f"/memory-functions/{_as_uuid(memory_function_id)}"
    )
    raise_for_status_with_text(response)
    return response.json()

list_memory_functions(*, target_type=None) async

List memory functions.

Parameters:

Name Type Description Default
target_type Sequence[str]

The memory function's target type. Defaults to None.

None

Returns:

Type Description
AsyncGenerator[Dict[str, Any], None]

AsyncGenerator[Dict[str, Any], None]: The memory functions' data.

Source code in langmem/client.py
async def list_memory_functions(
    self, *, target_type: Optional[Sequence[str]] = None
) -> AsyncGenerator[Dict[str, Any], None]:
    """List memory functions.

    Args:
        target_type (Sequence[str], optional): The memory function's target type. Defaults to None.

    Returns:
        AsyncGenerator[Dict[str, Any], None]: The memory functions' data.
    """

    body = {}
    if target_type is not None:
        body["target_type"] = (
            [target_type] if isinstance(target_type, str) else target_type
        )
    cursor = None
    while True:
        if cursor is not None:
            body["cursor"] = cursor
        response = await self.client.post("/memory-functions/query", json=body)
        raise_for_status_with_text(response)
        data = response.json()
        for function in data.get("memory_functions", []):
            yield function
        cursor = data.get("next_cursor")
        if cursor is None:
            break

update_memory_function(memory_function_id, *, name=None, schema=None, custom_instructions=None, description=None, function_type=None, status=None) async

Update a memory function.

Parameters:

Name Type Description Default
memory_function_id ID_T

The memory function's ID.

required
name Optional[str]

The memory function's name. Defaults to None.

None
schema Optional[Union[BaseModel, dict]]

The memory function's schema. Defaults to None.

None
custom_instructions Optional[str]

The memory function's custom instructions. Defaults to None.

None
description Optional[str]

The memory function's description. Defaults to None.

None
function_type Optional[str]

The memory function's type. Defaults to None.

None
status Optional[Literal['active', 'disabled']]

Optional[Literal["active", "disabled"]], optional): The memory function's status. Use to activate or disable the memory function. Disabled memory functions no longer trigger on new threads.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The memory function's data.

Source code in langmem/client.py
async def update_memory_function(
    self,
    memory_function_id: ID_T,
    *,
    name: Optional[str] = None,
    schema: Optional[Union[BaseModel, dict]] = None,
    custom_instructions: Optional[str] = None,
    description: Optional[str] = None,
    function_type: Optional[str] = None,
    status: Optional[Literal["active", "disabled"]] = None,
) -> Dict[str, Any]:
    """Update a memory function.

    Args:
        memory_function_id (ID_T): The memory function's ID.
        name (Optional[str], optional): The memory function's name. Defaults to None.
        schema (Optional[Union[BaseModel, dict]], optional): The memory function's schema. Defaults to None.
        custom_instructions (Optional[str], optional): The memory function's custom instructions. Defaults to None.
        description (Optional[str], optional): The memory function's description. Defaults to None.
        function_type (Optional[str], optional): The memory function's type. Defaults to None.
        status: Optional[Literal["active", "disabled"]], optional): The memory function's status.
            Use to activate or disable the memory function. Disabled memory functions no longer
            trigger on new threads.

    Returns:
        Dict[str, Any]: The memory function's data.
    """

    data: Dict[str, Any] = {
        "name": name,
        "description": description,
        "custom_instructions": custom_instructions,
        "type": function_type,
        "status": status,
    }
    if schema is not None:
        data["function"] = (
            schema
            if isinstance(schema, dict)
            else json.loads(schema.model_dump_json())
        )
    response = await self.client.patch(
        f"/memory-functions/{_as_uuid(memory_function_id)}",
        json={k: v for k, v in data.items() if v is not None},
    )
    raise_for_status_with_text(response)
    return response.json()

delete_memory_function(memory_function_id) async

Delete a memory function.

Parameters:

Name Type Description Default
memory_function_id ID_T

The memory function's ID.

required
Source code in langmem/client.py
async def delete_memory_function(
    self,
    memory_function_id: ID_T,
) -> None:
    """Delete a memory function.

    Args:
        memory_function_id (ID_T): The memory function's ID.
    """
    response = await self.client.delete(
        f"/memory-functions/{_as_uuid(memory_function_id)}"
    )
    raise_for_status_with_text(response)
    return response.json()

create_thread(*, thread_id=None, messages=None, metadata=None) async

Create a thread.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

None
messages Sequence[Dict[str, Any]]

A sequence of dictionaries representing the messages in the thread.

None
metadata Dict[str, str]

Additional metadata associated with the thread.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The thread's data.

Source code in langmem/client.py
async def create_thread(
    self,
    *,
    thread_id: Optional[ID_T] = None,
    messages: Optional[Sequence[Dict[str, Any]]] = None,
    metadata: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
    """Create a thread.

    Args:
        thread_id (ID_T): The thread's ID.
        messages (Sequence[Dict[str, Any]]): A sequence of dictionaries representing the messages in the thread.
        metadata (Dict[str, str]): Additional metadata associated with the thread.

    Returns:
        Dict[str, Any]: The thread's data.
    """

    data = {
        "id": thread_id,
        "messages": messages,
        "metadata": metadata,
    }
    response = await self.client.post("/threads", json=data)
    raise_for_status_with_text(response)
    return response.json()

add_messages(thread_id, *, messages) async

Add messages to a thread.

This method allows you to add messages to a specific thread identified by its ID.

Parameters:

Name Type Description Default
thread_id ID_T

The ID of the thread to which the messages will be added.

required
messages Sequence[Dict[str, Any]]

A sequence of dictionaries representing the messages to be added. Each dictionary should contain the following keys: - "role" (str): The role of the message sender (e.g., "user", "bot"). - "content" (str): The content of the message. - "name" (str): The name of the message sender. - "metadata" (dict): Additional metadata associated with the message.

required

Returns:

Type Description
None

None

Examples:

Add messages in a new thread:

>>> from langmem import Client
>>> client = Client()
>>> messages = [
...     {
...         "role": "user",
...         "content": "Did you know pikas make their own haypiles?",
...         "name": "Will",
...         "metadata": {"user_id": user_id},
...     },
...     {
...         "role": "assistant",
...         "content": "Yes, pikas are fascinating creatures!",
...         "name": "Bot",
...     },
... ]
>>> await client.add_messages(thread_id, messages=messages)
Source code in langmem/client.py
async def add_messages(
    self, thread_id: ID_T, *, messages: Sequence[schemas.MESSAGE_LIKE]
) -> None:
    """Add messages to a thread.

    This method allows you to add messages to a specific thread identified by its ID.

    Args:
        thread_id (ID_T): The ID of the thread to which the messages will be added.
        messages (Sequence[Dict[str, Any]]): A sequence of dictionaries representing the messages to be added. Each dictionary should contain the following keys:
            - "role" (str): The role of the message sender (e.g., "user", "bot").
            - "content" (str): The content of the message.
            - "name" (str): The name of the message sender.
            - "metadata" (dict): Additional metadata associated with the message.

    Returns:
        None

    Examples:
        Add messages in a new thread:

        >>> from langmem import Client
        >>> client = Client()
        >>> messages = [
        ...     {
        ...         "role": "user",
        ...         "content": "Did you know pikas make their own haypiles?",
        ...         "name": "Will",
        ...         "metadata": {"user_id": user_id},
        ...     },
        ...     {
        ...         "role": "assistant",
        ...         "content": "Yes, pikas are fascinating creatures!",
        ...         "name": "Bot",
        ...     },
        ... ]
        >>> await client.add_messages(thread_id, messages=messages)
    """

    data = {"messages": messages}
    response = await self.client.post(
        f"/threads/{_as_uuid(thread_id)}/add_messages",
        data=json.dumps(data, default=_default_serializer),  # type: ignore[arg-type]
    )
    raise_for_status_with_text(response)
    return response.json()

get_thread(thread_id) async

Get a thread.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The thread's data.

Source code in langmem/client.py
async def get_thread(self, thread_id: ID_T) -> Dict[str, Any]:
    """Get a thread.

    Args:
        thread_id (ID_T): The thread's ID.

    Returns:
        Dict[str, Any]: The thread's data.
    """

    response = await self.client.get(f"/threads/{_as_uuid(thread_id)}")
    raise_for_status_with_text(response)
    return response.json()

list_threads() async

List threads.

Returns:

Type Description
Iterable[Dict[str, Any]]

Iterable[Dict[str, Any]]: The threads' data.

Source code in langmem/client.py
async def list_threads(self) -> Iterable[Dict[str, Any]]:
    """List threads.

    Returns:
        Iterable[Dict[str, Any]]: The threads' data.
    """

    response = await self.client.get("/threads")
    raise_for_status_with_text(response)
    return response.json()

list_thread_memory(thread_id) async

List a thread's memory.

This method retrieves all memories associated with a given thread. It will return outputs from all memory function types defined for the thread.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: The thread's memory.

Examples:

>>> from langmem import AsyncClient
>>> client = AsyncClient()
>>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
>>> memories = client.list_thread_memory(thread_id)
>>> async for memory in memories:
...     print(memory)
Source code in langmem/client.py
async def list_thread_memory(self, thread_id: ID_T) -> List[Dict[str, Any]]:
    """List a thread's memory.

    This method retrieves all memories associated with a given thread.
    It will return outputs from all memory function types defined for the thread.

    Args:
        thread_id (ID_T): The thread's ID.

    Returns:
        List[Dict[str, Any]]: The thread's memory.

    Examples:

        >>> from langmem import AsyncClient
        >>> client = AsyncClient()
        >>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
        >>> memories = client.list_thread_memory(thread_id)
        >>> async for memory in memories:
        ...     print(memory)
    """

    response = await self.client.get(f"/threads/{_as_uuid(thread_id)}/memory")
    raise_for_status_with_text(response)
    return response.json()

get_thread_memory(thread_id, *, memory_function_id) async

Get a thread's memory state.

This method retrieves the current memory state for a specific thread and memory function. It is faster than querying and useful for "thread_state" type memories.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required
memory_function_id ID_T

The memory function's ID.

required

Returns:

Name Type Description
dict dict

The memory state.

Examples:

>>> from langmem import AsyncClient
>>> client = AsyncClient()
>>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
>>> memory_function_id = "cb217ff7-963e-44fc-b222-01f01058d64b"
>>> await client.get_thread_memory(thread_id, memory_function_id=memory_function_id)
Source code in langmem/client.py
async def get_thread_memory(
    self,
    thread_id: ID_T,
    *,
    memory_function_id: ID_T,
) -> dict:
    """Get a thread's memory state.

    This method retrieves the current memory state for a specific thread and memory function.
    It is faster than querying and useful for "thread_state" type memories.

    Args:
        thread_id (ID_T): The thread's ID.
        memory_function_id (ID_T): The memory function's ID.

    Returns:
        dict: The memory state.

    Examples:

        >>> from langmem import AsyncClient
        >>> client = AsyncClient()
        >>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
        >>> memory_function_id = "cb217ff7-963e-44fc-b222-01f01058d64b"
        >>> await client.get_thread_memory(thread_id, memory_function_id=memory_function_id)
    """
    response = await self.client.get(
        f"/threads/{_as_uuid(thread_id)}/memory/{_as_uuid(memory_function_id)}/state"
    )
    raise_for_status_with_text(response)
    return response.json()

trigger_all_for_thread(thread_id) async

Trigger all memory functions for a thread.

This method eagerly processes any pending memories for the given thread. It will trigger all memory function types defined for the thread.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required

Examples:

>>> from langmem import Client
>>> client = Client()
>>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
>>> await client.trigger_all_for_thread(thread_id)
Source code in langmem/client.py
async def trigger_all_for_thread(self, thread_id: ID_T) -> None:
    """Trigger all memory functions for a thread.

    This method eagerly processes any pending memories for the given thread.
    It will trigger all memory function types defined for the thread.

    Args:
        thread_id (ID_T): The thread's ID.

    Examples:

        >>> from langmem import Client
        >>> client = Client()
        >>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
        >>> await client.trigger_all_for_thread(thread_id)
    """

    response = await self.client.post(f"/threads/{_as_uuid(thread_id)}/trigger-all")
    raise_for_status_with_text(response)
    return response.json()

add_thread_state(thread_id, state, *, key=None) async

Add a thread state.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required
state Dict[str, Any]

The thread state.

required
Source code in langmem/client.py
async def add_thread_state(
    self, thread_id: ID_T, state: Dict[str, Any], *, key: Optional[str] = None
) -> None:
    """Add a thread state.

    Args:
        thread_id (ID_T): The thread's ID.
        state (Dict[str, Any]): The thread state.
    """

    response = await self.client.post(
        f"/threads/{_as_uuid(thread_id)}/thread_state",
        json={"state": state, "key": key},
    )
    raise_for_status_with_text(response)
    return response.json()

get_thread_state(thread_id, *, key=None) async

Get a thread state.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required

Returns:

Name Type Description
GetThreadStateResponse dict

The thread state.

Source code in langmem/client.py
async def get_thread_state(
    self, thread_id: ID_T, *, key: Optional[str] = None
) -> dict:
    """Get a thread state.

    Args:
        thread_id (ID_T): The thread's ID.

    Returns:
        GetThreadStateResponse: The thread state.
    """
    response = await self.client.post(
        f"/threads/{_as_uuid(thread_id)}/thread_state/query", json={"key": key}
    )
    raise_for_status_with_text(response)
    return response.json()

list_messages(thread_id, *, response_format=None, ascending_order=None, page_size=None, limit=None) async

List a thread's messages.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required
response_format Optional[Literal['openai', 'langmem']]

The response format. Defaults to None, which is the openai format.

None
ascending_order Optional[bool]

Whether to return messages in ascending order.

None
page_size Optional[int]

The page size. Defaults to None.

None
limit Optional[int]

The maximum number of messages to return. Defaults to None.

None

Returns:

Type Description
AsyncGenerator[Dict[str, Any], None]

AsyncGenerator[Dict[str, Any], None]: The messages' data.

Source code in langmem/client.py
async def list_messages(
    self,
    thread_id: ID_T,
    *,
    response_format: Optional[Literal["openai", "langmem"]] = None,
    ascending_order: Optional[bool] = None,
    page_size: Optional[int] = None,
    limit: Optional[int] = None,
) -> AsyncGenerator[Dict[str, Any], None]:
    """List a thread's messages.

    Args:
        thread_id (ID_T): The thread's ID.
        response_format (Optional[Literal["openai", "langmem"]], optional): The response format.
            Defaults to None, which is the openai format.
        ascending_order (Optional[bool], optional): Whether to return messages in ascending order.
        page_size (Optional[int], optional): The page size. Defaults to None.
        limit (Optional[int], optional): The maximum number of messages to return. Defaults to None.

    Returns:
        AsyncGenerator[Dict[str, Any], None]: The messages' data.
    """

    params: Dict[str, Any] = {
        "response_format": response_format,
        "page_size": page_size,
        "ascending_order": ascending_order,
    }
    params = {k: v for k, v in params.items() if v is not None}

    # Handle pagination for large threads
    cursor = None
    idx = 0
    while True:
        if cursor is not None:
            params["cursor"] = cursor
        response = await self.client.get(
            f"/threads/{_as_uuid(thread_id)}/messages", params=params
        )
        raise_for_status_with_text(response)
        data = response.json()
        for message in data.get("messages", []):
            yield message
            idx += 1
            if limit is not None and idx >= limit:
                break
        cursor = data.get("next_cursor")
        if cursor is None or (limit is not None and idx >= limit):
            break

Client

The Langmem client.

Examples:

Basic usage:

    >>> from langmem import Client
    >>> from pydantic import BaseModel, Field
    >>> client = Client()
    >>> class UserProfile(BaseModel):
    ...     name: str = Field(description="The user's name")
    ...     age: int = Field(description="The user's age")
    ...     interests: List[str] = Field(description="The user's interests")
    ...     relationships: Dict[str, str] = Field(
    ...         description="The user's friends, family, pets,and other relationships."
    ...     )
    >>> memory_function = client.create_memory_function(
    ...     UserProfile,
    ...     target_type="user_state",
    ...     name="User Profile",
    ... )
    >>> user_id = uuid.uuid4()
    >>> user_name = "Will"
    >>> messages = [
    ...     {
    ...         "role": "user",
    ...         "content": "Did you know pikas make their own haypiles?",
    ...         "name": "Will",
    ...         "metadata": {"user_id": user_id},
    ...     },
    ...     {
    ...         "role": "assistant",
    ...         "content": "Yes! And did you know they're actually related to rabbits?",
    ...     },
    ...     {
    ...         "role": "user",
    ...         "content": "I did! More people should know this important knowledge.",
    ...         "name": "Will",
    ...         "metadata": {"user_id": user_id},
    ...     },
    ... ]
    >>> thread_id = uuid.uuid4()
    >>> client.add_messages(thread_id, messages)
    >>> client.trigger_all_for_thread(thread_id)
    >>> client.get_user_memory(user_id, memory_function_id=memory_function["id"])
    >>> # Or query the unstructured memory
    >>> client.query_user_memory(user_id, "pikas", k=1)

    Query user memories semantically:

    >>> client.query_user_memory(
    ...     user_id=user_id,
    ...     text="What does the user think about rabbits?",
    ...     memory_function_ids=[belief_function["id"]],
    ...     k=3,
    ... )

    Create a thread summary memory function:

    >>> class ConversationSummary(BaseModel):
    ...     title: str = Field(description="Distinct for the conversation.")
    ...     summary: str = Field(description="High level summary of the interactions.")
    ...     topic: List[str] = Field(
    ...         description="Tags for topics discussed in this conversation."
    ...     )
    >>> thread_summary_function = client.create_memory_function(
    ...     ConversationSummary, target_type="thread_summary"
    ... )

    Fetch thread messages:

    >>> messages = client.list_messages(thread_id=thread_id)
    >>> for message in messages:
    ...     print(message)
Source code in langmem/client.py
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
class Client:
    """The Langmem client.

    Examples:

        Basic usage:

            >>> from langmem import Client
            >>> from pydantic import BaseModel, Field
            >>> client = Client()
            >>> class UserProfile(BaseModel):
            ...     name: str = Field(description="The user's name")
            ...     age: int = Field(description="The user's age")
            ...     interests: List[str] = Field(description="The user's interests")
            ...     relationships: Dict[str, str] = Field(
            ...         description="The user's friends, family, pets,and other relationships."
            ...     )
            >>> memory_function = client.create_memory_function(
            ...     UserProfile,
            ...     target_type="user_state",
            ...     name="User Profile",
            ... )
            >>> user_id = uuid.uuid4()
            >>> user_name = "Will"
            >>> messages = [
            ...     {
            ...         "role": "user",
            ...         "content": "Did you know pikas make their own haypiles?",
            ...         "name": "Will",
            ...         "metadata": {"user_id": user_id},
            ...     },
            ...     {
            ...         "role": "assistant",
            ...         "content": "Yes! And did you know they're actually related to rabbits?",
            ...     },
            ...     {
            ...         "role": "user",
            ...         "content": "I did! More people should know this important knowledge.",
            ...         "name": "Will",
            ...         "metadata": {"user_id": user_id},
            ...     },
            ... ]
            >>> thread_id = uuid.uuid4()
            >>> client.add_messages(thread_id, messages)
            >>> client.trigger_all_for_thread(thread_id)
            >>> client.get_user_memory(user_id, memory_function_id=memory_function["id"])
            >>> # Or query the unstructured memory
            >>> client.query_user_memory(user_id, "pikas", k=1)

            Query user memories semantically:

            >>> client.query_user_memory(
            ...     user_id=user_id,
            ...     text="What does the user think about rabbits?",
            ...     memory_function_ids=[belief_function["id"]],
            ...     k=3,
            ... )

            Create a thread summary memory function:

            >>> class ConversationSummary(BaseModel):
            ...     title: str = Field(description="Distinct for the conversation.")
            ...     summary: str = Field(description="High level summary of the interactions.")
            ...     topic: List[str] = Field(
            ...         description="Tags for topics discussed in this conversation."
            ...     )
            >>> thread_summary_function = client.create_memory_function(
            ...     ConversationSummary, target_type="thread_summary"
            ... )

            Fetch thread messages:

            >>> messages = client.list_messages(thread_id=thread_id)
            >>> for message in messages:
            ...     print(message)
    """

    __slots__ = ["api_key", "client"]

    def __init__(self, api_url: Optional[str] = None, api_key: Optional[str] = None):
        self.api_key = api_key or os.environ.get("LANGMEM_API_KEY")
        base_url = _ensure_url(api_url)
        self.client = httpx.Client(
            base_url=base_url,
            headers=Client._get_headers(self.api_key),
            timeout=DEFAULT_TIMEOUT,
        )

    @staticmethod
    def _get_headers(api_key: Optional[str]):
        if not api_key:
            return {}
        return {
            "x-api-key": api_key,
        }

    @property
    def _headers(self):
        return self._get_headers(self.api_key)

    def __enter__(self):
        return self

    def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
        self.client.close()

    def create_user(
        self,
        *,
        user_id: ID_T,
        name: str,
        tags: Optional[Sequence[str]] = None,
        metadata: Dict[str, str] = {},
    ) -> Dict[str, Any]:
        """Create a user.

        Args:
            user_id (ID_T): The user's ID.
            name (str): The user's name.
            tags (Optional[Sequence[str]], optional): The user's tags. Defaults to None.
            metadata (Dict[str, str], optional): The user's metadata. Defaults to {}.

        Returns:
            Dict[str, Any]: The user's data.
        """

        data = {
            "id": user_id,
            "name": name,
            "tags": tags,
            "metadata": metadata,
        }
        response = self.client.post("/users", json=data)
        raise_for_status_with_text(response)
        return response.json()

    def get_user(self, user_id: ID_T) -> Dict[str, Any]:
        """Get a user.

        Args:
            user_id (ID_T): The user's ID.

        Returns:
            Dict[str, Any]: The user's data.
        """
        response = self.client.get(f"/users/{_as_uuid(user_id)}")
        raise_for_status_with_text(response)
        return response.json()

    def update_user(
        self,
        user_id: ID_T,
        *,
        name: Optional[str] = None,
        tags: Optional[Sequence[str]] = None,
        metadata: Optional[Dict[str, str]] = None,
    ) -> Dict[str, Any]:
        """Update a user.

        Args:
            user_id (ID_T): The user's ID.
            name (Optional[str], optional): The user's name. Defaults to None.
            tags (Optional[Sequence[str]], optional): The user's tags. Defaults to None.
            metadata (Optional[Dict[str, str]], optional): The user's metadata. Defaults to None.

        Returns:
            Dict[str, Any]: The user's data.
        """
        data: Dict[str, Any] = {}
        if name is not None:
            data["name"] = name
        if tags is not None:
            data["tags"] = tags
        if metadata is not None:
            data["metadata"] = metadata
        response = self.client.patch(f"/users/{_as_uuid(user_id)}", json=data)
        raise_for_status_with_text(response)
        return response.json()

    def list_users(
        self,
        *,
        name: Optional[Sequence[str]] = None,
        id: Optional[Sequence[ID_T]] = None,
    ) -> Iterable[Dict[str, Any]]:
        """List users.

        Args:
            name (Optional[Sequence[str]], optional): The user's name. Defaults to None.
            id (Optional[Sequence[ID_T]], optional): The user's ID. Defaults to None.

        Returns:
            List[Dict[str, Any]]: The users' data.
        """
        body = {
            "name": name,
            "id": id,
        }
        response = self.client.post(
            "/users/query",
            data=json.dumps(  # type: ignore[arg-type]
                body, default=_default_serializer
            ),
            headers={"Content-Type": "application/json"},
        )
        raise_for_status_with_text(response)
        return response.json()["users"]

    def trigger_all_for_user(self, user_id: ID_T) -> None:
        """Trigger all memory functions for a user.

        Args:
            user_id (ID_T): The user's ID.
        """
        response = self.client.post(f"/users/{_as_uuid(user_id)}/trigger-all")
        raise_for_status_with_text(response)
        return response.json()

    def delete_user_memory(
        self,
        *,
        user_id: ID_T,
        memory_function_id: ID_T,
    ) -> None:
        """Delete a user's memory.

        Args:
            user_id (ID_T): The user's ID.
            memory_function_id (ID_T): The memory function's ID. Defaults to None.
        """
        response = self.client.delete(
            f"/users/{_as_uuid(user_id)}/memory/{_as_uuid(memory_function_id)}/state"
        )
        raise_for_status_with_text(response)
        return response.json()

    def update_user_memory(
        self,
        user_id: ID_T,
        *,
        memory_function_id: ID_T,
        state: dict,
    ) -> None:
        """Update a user's memory.

        Args:
            user_id (ID_T): The user's ID.
            memory_function_id (ID_T): The memory function's ID.
            state (dict): The memory state.
        """
        response = self.client.put(
            f"/users/{_as_uuid(user_id)}/memory/{_as_uuid(memory_function_id)}/state",
            data=json.dumps(  # type: ignore[arg-type]
                {"state": state},
                default=_default_serializer,
            ),
        )
        raise_for_status_with_text(response)
        return response.json()

    def get_user_memory(
        self,
        user_id: ID_T,
        *,
        memory_function_id: ID_T,
    ) -> dict:
        """Get a user's memory state.

        This method retrieves the current memory state for a specific user and memory function.
        It is faster than querying and useful for "user_state" type memories.

        Args:
            user_id (ID_T): The user's ID.
            memory_function_id (ID_T): The memory function's ID.

        Returns:
            dict: The memory state.

        Examples:

            >>> from langmem import Client
            >>> client = Client()
            >>> user_id = "2d1a8daf-2319-4e3e-9fd0-6d7981ceb8a6"
            >>> memory_function_id = "cb217ff7-963e-44fc-b222-01f01058d64b"
            >>> client.get_user_memory(user_id, memory_function_id=memory_function_id)
        """
        response = self.client.get(
            f"/users/{_as_uuid(user_id)}/memory/{_as_uuid(memory_function_id)}/state"
        )
        raise_for_status_with_text(response)
        return response.json()

    def query_user_memory(
        self,
        user_id: ID_T,
        text: str,
        k: int = 200,
        memory_function_ids: Optional[Sequence[ID_T]] = None,
        weights: Optional[dict] = None,
        states_to_return: Optional[Sequence[ID_T]] = None,
        thread_summaries: Optional[Sequence[ID_T]] = None,
        thread_summaries_k: Optional[int] = None,
    ) -> List:
        """Query a user's memory.

        Args:
            user_id (ID_T): The user's ID.
            text (str): The query text.
            k (int, optional): The number of results to return. Defaults to 200.
            memory_function_ids (Optional[Sequence[ID_T]], optional): Semantic memory outputs
                to include. Defaults to None, meaning just the unstructured memories.
            weights (Optional[dict], optional): Weights for the different memory types.
                Backend default equally weights relevance, recency, and importance.
                Defaults to None.
            states_to_return (Optional[Sequence[ID_T]], optional): The user state
                memory function IDs to include in the response.

        Returns:
            List: The query results.


        Examples:

            Query a user's semantic memory:
                >>> from langmem import Client
                >>> client = Client()
                >>> user_id = uuid.uuid4()
                >>> client.query_user_memory(user_id, text="pikas", k=10)

            Query the memory, ignoring recency or perceived importance:

                >>> client.query_user_memory(
                ...     user_id,
                ...     text="pikas",
                ...     k=10,
                ...     weights={"relevance": 1.0, "recency": 0.0, "importance": 0.0},
                ... )

            Include user state memories in the response (to save the number of API calls):
                >>> mem_functions = [
                ...     f["id"]
                ...     for f in client.list_memory_functions(target_type="user")
                ...     if f["type"] == "user_state"
                ... ]
                >>> client.query_user_memory(
                ...     user_id,
                ...     text="pikas",
                ...     k=10,
                ...     states_to_return=mem_functions,
                ... )

            Query over user_append_state memories:
                >>> mem_functions = [
                ...    f["id"]
                ...    for f in client.list_memory_functions(target_type="user")
                ...    if f["type"] == "user_append_state"
                ... )
                >>> client.query_user_memory(
                ...     user_id,
                ...     text="pikas",
                ...     k=10,
                ...     memory_function_ids=mem_functions,
                ... )

            Include thread summaries for the most recent threads:

                >>> mem_functions = [
                ...     f["id"] for f in client.list_memory_functions(target_type="thread")
                ... ]
                >>> client.query_user_memory(
                ...     user_id,
                ...     text="pikas",
                ...     k=10,
                ...     thread_summaries=mem_functions,
                ...     thread_summaries_k=5,
                ... )
        """
        thread_query = None
        if thread_summaries is not None:
            thread_query = {
                "memory_function_ids": thread_summaries,
            }
            if thread_summaries_k is not None:
                thread_query["k"] = thread_summaries
        response = self.client.post(
            f"/users/{_as_uuid(user_id)}/memory/query",
            data=json.dumps(  # type: ignore[arg-type]
                {
                    "text": text,
                    "k": k,
                    "memory_function_ids": memory_function_ids,
                    "weights": weights,
                    "state": states_to_return,
                    "thread_query": thread_query,
                },
                default=_default_serializer,
            ),
        )
        raise_for_status_with_text(response)
        return response.json()

    def create_memory_function(
        self,
        parameters: Union[BaseModel, dict],
        *,
        target_type: str = "user_state",
        name: Optional[str] = None,
        description: Optional[str] = None,
        custom_instructions: Optional[str] = None,
        function_id: Optional[ID_T] = None,
    ) -> Dict[str, Any]:
        """Create a memory function.

        Args:
            parameters (Union[BaseModel, dict]): The memory function's parameters.
            target_type (str, optional): The memory function's target type. Defaults to "user_state".
            name (Optional[str], optional): The memory function's name. Defaults to None.
            description (Optional[str], optional): The memory function's description. Defaults to None.
            custom_instructions (Optional[str], optional): The memory function's custom instructions. Defaults to None.
            function_id (Optional[ID_T], optional): The memory function's ID. Defaults to None.

        Returns:
            Dict[str, Any]: The memory function's data.

        Examples:

            Create a user profile memory function:

                >>> from pydantic import BaseModel, Field
                >>> from langmem import Client
                >>> client = Client()
                >>> class UserProfile(BaseModel):
                ...     name: str = Field(description="The user's name")
                ...     age: int = Field(description="The user's age")
                ...     interests: List[str] = Field(description="The user's interests")
                ...     relationships: Dict[str, str] = Field(
                ...         description="The user's friends, family, pets,and other relationships."
                ...     )
                >>> memory_function = client.create_memory_function(
                ...     UserProfile,
                ...     target_type="user_state",
                ...     name="User Profile",
                ... )

            Create an append-only user memory function:

                >>> class FormativeEvent(BaseModel):
                ...     event: str = Field(description="The formative event that occurred.")
                ...     impact: str = Field(description="How this event impacted the user.")
                >>> event_function = client.create_memory_function(
                ...     FormativeEvent, target_type="user_append_state"
                ... )

        """
        if isinstance(parameters, dict):
            params = parameters
        else:
            params = parameters.model_json_schema()
        function_schema = {
            "name": name or params.pop("title", ""),
            "description": description or params.pop("description", ""),
            "parameters": params,
        }
        data = {
            "type": target_type,
            "custom_instructions": custom_instructions,
            "id": function_id or str(uuid.uuid4()),
            "schema": function_schema,
        }
        response = self.client.post("/memory-functions", json=data)
        raise_for_status_with_text(response)
        return response.json()

    def get_memory_function(self, memory_function_id: ID_T) -> Dict[str, Any]:
        """Get a memory function.

        Args:
            memory_function_id (ID_T): The memory function's ID.

        Returns:
            Dict[str, Any]: The memory function's data.
        """
        response = self.client.get(f"/memory-functions/{_as_uuid(memory_function_id)}")
        raise_for_status_with_text(response)
        return response.json()

    def list_memory_functions(
        self, *, target_type: Optional[Sequence[str]] = None
    ) -> Iterable[Dict[str, Any]]:
        """List memory functions.

        Args:
            target_type (Sequence[str], optional): The memory function's target type. Defaults to None.

        Returns:
            List[Dict[str, Any]]: The memory functions' data.
        """
        body = {}
        if target_type is not None:
            body["target_type"] = (
                [target_type] if isinstance(target_type, str) else target_type
            )
        cursor = None
        while True:
            if cursor is not None:
                body["cursor"] = cursor
            response = self.client.post("/memory-functions/query", json=body)
            raise_for_status_with_text(response)
            data = response.json()
            for function in data.get("memory_functions", []):
                yield function
            cursor = data.get("next_cursor")
            if cursor is None:
                break

    def update_memory_function(
        self,
        memory_function_id: ID_T,
        *,
        name: Optional[str] = None,
        schema: Optional[Union[BaseModel, dict]] = None,
        custom_instructions: Optional[str] = None,
        description: Optional[str] = None,
        function_type: Optional[str] = None,
        status: Optional[Literal["active", "disabled"]] = None,
    ) -> Dict[str, Any]:
        """Update a memory function.

        Args:
            memory_function_id (ID_T): The memory function's ID.
            name (Optional[str], optional): The memory function's name. Defaults to None.
            schema (Optional[Union[BaseModel, dict]], optional): The memory function's schema. Defaults to None.
            custom_instructions (Optional[str], optional): The memory function's custom instructions. Defaults to None.
            description (Optional[str], optional): The memory function's description. Defaults to None.
            function_type (Optional[str], optional): The memory function's type. Defaults to None.
            status: Optional[Literal["active", "disabled"]], optional): The memory function's status.
                Use to activate or disable the memory function. Disabled memory functions no longer
                trigger on new threads.

        Returns:
            Dict[str, Any]: The memory function's data.


        Examples:

            Update a memory function's name:
                >>> from langmem import Client
                >>> client = Client()
                >>> memory_function_id = list(client.list_memory_functions())[0]["id"]
                >>> client.update_memory_function(memory_function_id, name="New Name")

            Disable a memory function:
                >>> client.update_memory_function(memory_function_id, status="disabled")

            Update a memory function's schema:
                >>> from pydantic import BaseModel, Field
                >>> class UserProfile:
                ...     name: str = Field(description="The user's name")
                ...     favorite_animals: List[str] = Field(
                ...         description="The user's favorite animals"
                ...     )
                >>> client.update_memory_function(memory_function_id, schema=UserProfile)

            Update the custom instructions for a memory function:

                >>> client.update_memory_function(
                ...     memory_function_id,
                ...     custom_instructions="Update the user profile."
                ...     " Never delete anything in the current one."
                ...     " If you don't know, guess as much as you'd like.",
                ... )


        """
        data: dict = {
            "name": name,
            "description": description,
            "custom_instructions": custom_instructions,
            "type": function_type,
            "status": status,
        }
        if schema is not None:
            if isinstance(schema, dict):
                data["schema"] = schema
            else:
                data["schema"] = schema.model_json_schema()
        response = self.client.patch(
            f"/memory-functions/{_as_uuid(memory_function_id)}",
            json={k: v for k, v in data.items() if v is not None},
        )
        raise_for_status_with_text(response)
        return response.json()

    def delete_memory_function(
        self,
        memory_function_id: ID_T,
    ) -> None:
        """Delete a memory function.

        Args:
            memory_function_id (ID_T): The memory function's ID.
        """
        response = self.client.delete(
            f"/memory-functions/{_as_uuid(memory_function_id)}"
        )
        raise_for_status_with_text(response)
        return response.json()

    def create_thread(
        self,
        *,
        thread_id: Optional[ID_T] = None,
        messages: Optional[Sequence[schemas.MESSAGE_LIKE]] = None,
        metadata: Optional[Dict[str, str]] = None,
    ) -> Dict[str, Any]:
        """Create a thread.

        Args:
            thread_id (ID_T): The thread's ID.
            messages (Sequence[Dict[str, Any]]): The messages to add.
            metadata (Dict[str, str], optional): The thread's metadata. Defaults to {}.

        Returns:
            Dict[str, Any]: The thread's data.
        """
        data = {
            "id": thread_id,
            "messages": messages,
            "metadata": metadata,
        }
        response = self.client.post("/threads", json=data)
        raise_for_status_with_text(response)
        return response.json()

    def add_messages(
        self, thread_id: ID_T, *, messages: Sequence[Dict[str, Any]]
    ) -> None:
        """Add messages to a thread.

        This method allows you to add multiple messages to a specific thread identified by its ID.
        If the thread is not found, it will be created implicitly.

        Args:
            thread_id (ID_T): The ID of the thread to which the messages will be added.
            messages (Sequence[Dict[str, Any]]): A sequence of dictionaries representing the messages to be added.
                Each dictionary should contain the necessary information for a single message, such as its content,
                author, timestamp, etc.

        Examples:

            Add messages in a new thread:

            >>> from langmem import Client
            >>> client = Client()
            >>> messages = [
            ...     {
            ...         "role": "user",
            ...         "content": "Did you know pikas make their own haypiles?",
            ...         "name": "Will",
            ...         "metadata": {"user_id": user_id},
            ...     },
            ...     {
            ...         "role": "assistant",
            ...         "content": "Yes, pikas are fascinating creatures!",
            ...         "name": "Bot",
            ...     },
            ... ]
            >>> client.add_messages(thread_id, messages=messages)


        Raises:
            HTTPError: If the request to add the messages fails.

        Returns:
            None: This method does not return any value.
        """
        data = {"messages": messages}
        response = self.client.post(
            f"/threads/{_as_uuid(thread_id)}/add_messages",
            data=json.dumps(data, default=_default_serializer),  # type: ignore[arg-type]
        )
        raise_for_status_with_text(response)
        return response.json()

    def get_thread(self, thread_id: ID_T) -> Dict[str, Any]:
        """Get a thread.

        Args:
            thread_id (ID_T): The thread's ID.

        Returns:
            Dict[str, Any]: The thread's data.
        """
        response = self.client.get(f"/threads/{_as_uuid(thread_id)}")
        raise_for_status_with_text(response)
        return response.json()

    def list_threads(self) -> Iterable[Dict[str, Any]]:
        """List threads.

        Returns:
            Iterable[Dict[str, Any]]: The threads' data.
        """
        response = self.client.get("/threads")
        raise_for_status_with_text(response)
        return response.json()

    def list_thread_memory(self, thread_id: ID_T) -> List[Dict[str, Any]]:
        """List a thread's memory.

        This method retrieves all memories associated with a given thread.
        It will return outputs from all memory function types defined for the thread.

        Args:
            thread_id (ID_T): The thread's ID.

        Returns:
            List[Dict[str, Any]]: The thread's memory.

        Examples:

            >>> from langmem import Client
            >>> client = Client()
            >>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
            >>> memories = client.list_thread_memory(thread_id)
            >>> for memory in memories:
            ...     print(memory)
        """
        response = self.client.get(f"/threads/{_as_uuid(thread_id)}/memory")
        raise_for_status_with_text(response)
        return response.json()

    def trigger_all_for_thread(self, thread_id: ID_T) -> None:
        """Trigger all memory functions for a thread.

        This method eagerly processes any pending memories for the given thread.
        It will trigger all memory function types defined for the thread.

        Args:
            thread_id (ID_T): The thread's ID.

        Examples:

            >>> from langmem import Client
            >>> client = Client()
            >>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
            >>> client.trigger_all_for_thread(thread_id)
        """
        response = self.client.post(f"/threads/{_as_uuid(thread_id)}/trigger-all")
        raise_for_status_with_text(response)
        return response.json()

    def get_thread_memory(
        self,
        thread_id: ID_T,
        *,
        memory_function_id: ID_T,
    ) -> dict:
        """Get a thread's memory state.

        This method retrieves the current memory state for a specific thread and memory function.
        It is faster than querying and useful for "thread_state" type memories.

        Args:
            thread_id (ID_T): The thread's ID.
            memory_function_id (ID_T): The memory function's ID.

        Returns:
            dict: The memory state.

        Examples:

            >>> from langmem import Client
            >>> client = Client()
            >>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
            >>> memory_function_id = "cb217ff7-963e-44fc-b222-01f01058d64b"
            >>> client.get_thread_memory(thread_id, memory_function_id=memory_function_id)
        """
        response = self.client.get(
            f"/threads/{_as_uuid(thread_id)}/memory/{_as_uuid(memory_function_id)}/state"
        )
        raise_for_status_with_text(response)
        return response.json()

    def add_thread_state(
        self, thread_id: ID_T, state: Dict[str, Any], *, key: Optional[str] = None
    ) -> None:
        """Add a thread state.

        Args:
            thread_id (ID_T): The thread's ID.
            state (Dict[str, Any]): The thread state.
        """
        response = self.client.post(
            f"/threads/{_as_uuid(thread_id)}/thread_state",
            json={"state": state, "key": key},
        )
        raise_for_status_with_text(response)
        return response.json()

    def get_thread_state(self, thread_id: ID_T, *, key: Optional[str] = None) -> dict:
        """Get a thread state.

        Args:
            thread_id (ID_T): The thread's ID.

        Returns:
            GetThreadStateResponse: The thread state.
        """
        response = self.client.post(
            f"/threads/{_as_uuid(thread_id)}/thread_state/query", json={"key": key}
        )
        raise_for_status_with_text(response)
        return response.json()

    def list_messages(
        self,
        thread_id: ID_T,
        *,
        response_format: Optional[Literal["openai", "langmem"]] = None,
        page_size: Optional[int] = None,
        limit: Optional[int] = None,
        ascending_order: Optional[bool] = None,
    ) -> Iterable[Dict[str, Any]]:
        """List a thread's messages.

        Args:
            thread_id (ID_T): The thread's ID.
            response_format (Optional[Literal["openai", "langmem"]], optional): The response format.
                Defaults to None, which is the openai format.
            page_size (Optional[int], optional): The page size. Defaults to None.
            limit (Optional[int], optional): The maximum number of messages to return. Defaults to None.
            ascending_order (Optional[bool], optional): Whether to return messages in ascending_order order.
                Defaults to None.

        Returns:
            Iterable[Dict[str, Any]]: The messages' data.
        """
        params: Dict[str, Any] = {
            "response_format": response_format,
            "page_size": page_size,
            "ascending_order": ascending_order,
        }
        params = {k: v for k, v in params.items() if v is not None}
        cursor: Optional[str] = None
        idx = 0
        while True:
            if cursor is not None:
                params["cursor"] = cursor
            response = self.client.get(
                f"/threads/{_as_uuid(thread_id)}/messages", params=params
            )
            raise_for_status_with_text(response)
            data = response.json()
            for message in data.get("messages", []):
                yield message
                idx += 1
                if limit is not None and idx >= limit:
                    break
            cursor = data.get("next_cursor")
            if cursor is None or (limit is not None and idx >= limit):
                break

create_user(*, user_id, name, tags=None, metadata={})

Create a user.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
name str

The user's name.

required
tags Optional[Sequence[str]]

The user's tags. Defaults to None.

None
metadata Dict[str, str]

The user's metadata. Defaults to {}.

{}

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The user's data.

Source code in langmem/client.py
def create_user(
    self,
    *,
    user_id: ID_T,
    name: str,
    tags: Optional[Sequence[str]] = None,
    metadata: Dict[str, str] = {},
) -> Dict[str, Any]:
    """Create a user.

    Args:
        user_id (ID_T): The user's ID.
        name (str): The user's name.
        tags (Optional[Sequence[str]], optional): The user's tags. Defaults to None.
        metadata (Dict[str, str], optional): The user's metadata. Defaults to {}.

    Returns:
        Dict[str, Any]: The user's data.
    """

    data = {
        "id": user_id,
        "name": name,
        "tags": tags,
        "metadata": metadata,
    }
    response = self.client.post("/users", json=data)
    raise_for_status_with_text(response)
    return response.json()

get_user(user_id)

Get a user.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The user's data.

Source code in langmem/client.py
def get_user(self, user_id: ID_T) -> Dict[str, Any]:
    """Get a user.

    Args:
        user_id (ID_T): The user's ID.

    Returns:
        Dict[str, Any]: The user's data.
    """
    response = self.client.get(f"/users/{_as_uuid(user_id)}")
    raise_for_status_with_text(response)
    return response.json()

update_user(user_id, *, name=None, tags=None, metadata=None)

Update a user.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
name Optional[str]

The user's name. Defaults to None.

None
tags Optional[Sequence[str]]

The user's tags. Defaults to None.

None
metadata Optional[Dict[str, str]]

The user's metadata. Defaults to None.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The user's data.

Source code in langmem/client.py
def update_user(
    self,
    user_id: ID_T,
    *,
    name: Optional[str] = None,
    tags: Optional[Sequence[str]] = None,
    metadata: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
    """Update a user.

    Args:
        user_id (ID_T): The user's ID.
        name (Optional[str], optional): The user's name. Defaults to None.
        tags (Optional[Sequence[str]], optional): The user's tags. Defaults to None.
        metadata (Optional[Dict[str, str]], optional): The user's metadata. Defaults to None.

    Returns:
        Dict[str, Any]: The user's data.
    """
    data: Dict[str, Any] = {}
    if name is not None:
        data["name"] = name
    if tags is not None:
        data["tags"] = tags
    if metadata is not None:
        data["metadata"] = metadata
    response = self.client.patch(f"/users/{_as_uuid(user_id)}", json=data)
    raise_for_status_with_text(response)
    return response.json()

list_users(*, name=None, id=None)

List users.

Parameters:

Name Type Description Default
name Optional[Sequence[str]]

The user's name. Defaults to None.

None
id Optional[Sequence[ID_T]]

The user's ID. Defaults to None.

None

Returns:

Type Description
Iterable[Dict[str, Any]]

List[Dict[str, Any]]: The users' data.

Source code in langmem/client.py
def list_users(
    self,
    *,
    name: Optional[Sequence[str]] = None,
    id: Optional[Sequence[ID_T]] = None,
) -> Iterable[Dict[str, Any]]:
    """List users.

    Args:
        name (Optional[Sequence[str]], optional): The user's name. Defaults to None.
        id (Optional[Sequence[ID_T]], optional): The user's ID. Defaults to None.

    Returns:
        List[Dict[str, Any]]: The users' data.
    """
    body = {
        "name": name,
        "id": id,
    }
    response = self.client.post(
        "/users/query",
        data=json.dumps(  # type: ignore[arg-type]
            body, default=_default_serializer
        ),
        headers={"Content-Type": "application/json"},
    )
    raise_for_status_with_text(response)
    return response.json()["users"]

trigger_all_for_user(user_id)

Trigger all memory functions for a user.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
Source code in langmem/client.py
def trigger_all_for_user(self, user_id: ID_T) -> None:
    """Trigger all memory functions for a user.

    Args:
        user_id (ID_T): The user's ID.
    """
    response = self.client.post(f"/users/{_as_uuid(user_id)}/trigger-all")
    raise_for_status_with_text(response)
    return response.json()

delete_user_memory(*, user_id, memory_function_id)

Delete a user's memory.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
memory_function_id ID_T

The memory function's ID. Defaults to None.

required
Source code in langmem/client.py
def delete_user_memory(
    self,
    *,
    user_id: ID_T,
    memory_function_id: ID_T,
) -> None:
    """Delete a user's memory.

    Args:
        user_id (ID_T): The user's ID.
        memory_function_id (ID_T): The memory function's ID. Defaults to None.
    """
    response = self.client.delete(
        f"/users/{_as_uuid(user_id)}/memory/{_as_uuid(memory_function_id)}/state"
    )
    raise_for_status_with_text(response)
    return response.json()

update_user_memory(user_id, *, memory_function_id, state)

Update a user's memory.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
memory_function_id ID_T

The memory function's ID.

required
state dict

The memory state.

required
Source code in langmem/client.py
def update_user_memory(
    self,
    user_id: ID_T,
    *,
    memory_function_id: ID_T,
    state: dict,
) -> None:
    """Update a user's memory.

    Args:
        user_id (ID_T): The user's ID.
        memory_function_id (ID_T): The memory function's ID.
        state (dict): The memory state.
    """
    response = self.client.put(
        f"/users/{_as_uuid(user_id)}/memory/{_as_uuid(memory_function_id)}/state",
        data=json.dumps(  # type: ignore[arg-type]
            {"state": state},
            default=_default_serializer,
        ),
    )
    raise_for_status_with_text(response)
    return response.json()

get_user_memory(user_id, *, memory_function_id)

Get a user's memory state.

This method retrieves the current memory state for a specific user and memory function. It is faster than querying and useful for "user_state" type memories.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
memory_function_id ID_T

The memory function's ID.

required

Returns:

Name Type Description
dict dict

The memory state.

Examples:

>>> from langmem import Client
>>> client = Client()
>>> user_id = "2d1a8daf-2319-4e3e-9fd0-6d7981ceb8a6"
>>> memory_function_id = "cb217ff7-963e-44fc-b222-01f01058d64b"
>>> client.get_user_memory(user_id, memory_function_id=memory_function_id)
Source code in langmem/client.py
def get_user_memory(
    self,
    user_id: ID_T,
    *,
    memory_function_id: ID_T,
) -> dict:
    """Get a user's memory state.

    This method retrieves the current memory state for a specific user and memory function.
    It is faster than querying and useful for "user_state" type memories.

    Args:
        user_id (ID_T): The user's ID.
        memory_function_id (ID_T): The memory function's ID.

    Returns:
        dict: The memory state.

    Examples:

        >>> from langmem import Client
        >>> client = Client()
        >>> user_id = "2d1a8daf-2319-4e3e-9fd0-6d7981ceb8a6"
        >>> memory_function_id = "cb217ff7-963e-44fc-b222-01f01058d64b"
        >>> client.get_user_memory(user_id, memory_function_id=memory_function_id)
    """
    response = self.client.get(
        f"/users/{_as_uuid(user_id)}/memory/{_as_uuid(memory_function_id)}/state"
    )
    raise_for_status_with_text(response)
    return response.json()

query_user_memory(user_id, text, k=200, memory_function_ids=None, weights=None, states_to_return=None, thread_summaries=None, thread_summaries_k=None)

Query a user's memory.

Parameters:

Name Type Description Default
user_id ID_T

The user's ID.

required
text str

The query text.

required
k int

The number of results to return. Defaults to 200.

200
memory_function_ids Optional[Sequence[ID_T]]

Semantic memory outputs to include. Defaults to None, meaning just the unstructured memories.

None
weights Optional[dict]

Weights for the different memory types. Backend default equally weights relevance, recency, and importance. Defaults to None.

None
states_to_return Optional[Sequence[ID_T]]

The user state memory function IDs to include in the response.

None

Returns:

Name Type Description
List List

The query results.

Examples:

Query a user's semantic memory:
    >>> from langmem import Client
    >>> client = Client()
    >>> user_id = uuid.uuid4()
    >>> client.query_user_memory(user_id, text="pikas", k=10)

Query the memory, ignoring recency or perceived importance:

    >>> client.query_user_memory(
    ...     user_id,
    ...     text="pikas",
    ...     k=10,
    ...     weights={"relevance": 1.0, "recency": 0.0, "importance": 0.0},
    ... )

Include user state memories in the response (to save the number of API calls):
    >>> mem_functions = [
    ...     f["id"]
    ...     for f in client.list_memory_functions(target_type="user")
    ...     if f["type"] == "user_state"
    ... ]
    >>> client.query_user_memory(
    ...     user_id,
    ...     text="pikas",
    ...     k=10,
    ...     states_to_return=mem_functions,
    ... )

Query over user_append_state memories:
    >>> mem_functions = [
    ...    f["id"]
    ...    for f in client.list_memory_functions(target_type="user")
    ...    if f["type"] == "user_append_state"
    ... )
    >>> client.query_user_memory(
    ...     user_id,
    ...     text="pikas",
    ...     k=10,
    ...     memory_function_ids=mem_functions,
    ... )

Include thread summaries for the most recent threads:

    >>> mem_functions = [
    ...     f["id"] for f in client.list_memory_functions(target_type="thread")
    ... ]
    >>> client.query_user_memory(
    ...     user_id,
    ...     text="pikas",
    ...     k=10,
    ...     thread_summaries=mem_functions,
    ...     thread_summaries_k=5,
    ... )
Source code in langmem/client.py
def query_user_memory(
    self,
    user_id: ID_T,
    text: str,
    k: int = 200,
    memory_function_ids: Optional[Sequence[ID_T]] = None,
    weights: Optional[dict] = None,
    states_to_return: Optional[Sequence[ID_T]] = None,
    thread_summaries: Optional[Sequence[ID_T]] = None,
    thread_summaries_k: Optional[int] = None,
) -> List:
    """Query a user's memory.

    Args:
        user_id (ID_T): The user's ID.
        text (str): The query text.
        k (int, optional): The number of results to return. Defaults to 200.
        memory_function_ids (Optional[Sequence[ID_T]], optional): Semantic memory outputs
            to include. Defaults to None, meaning just the unstructured memories.
        weights (Optional[dict], optional): Weights for the different memory types.
            Backend default equally weights relevance, recency, and importance.
            Defaults to None.
        states_to_return (Optional[Sequence[ID_T]], optional): The user state
            memory function IDs to include in the response.

    Returns:
        List: The query results.


    Examples:

        Query a user's semantic memory:
            >>> from langmem import Client
            >>> client = Client()
            >>> user_id = uuid.uuid4()
            >>> client.query_user_memory(user_id, text="pikas", k=10)

        Query the memory, ignoring recency or perceived importance:

            >>> client.query_user_memory(
            ...     user_id,
            ...     text="pikas",
            ...     k=10,
            ...     weights={"relevance": 1.0, "recency": 0.0, "importance": 0.0},
            ... )

        Include user state memories in the response (to save the number of API calls):
            >>> mem_functions = [
            ...     f["id"]
            ...     for f in client.list_memory_functions(target_type="user")
            ...     if f["type"] == "user_state"
            ... ]
            >>> client.query_user_memory(
            ...     user_id,
            ...     text="pikas",
            ...     k=10,
            ...     states_to_return=mem_functions,
            ... )

        Query over user_append_state memories:
            >>> mem_functions = [
            ...    f["id"]
            ...    for f in client.list_memory_functions(target_type="user")
            ...    if f["type"] == "user_append_state"
            ... )
            >>> client.query_user_memory(
            ...     user_id,
            ...     text="pikas",
            ...     k=10,
            ...     memory_function_ids=mem_functions,
            ... )

        Include thread summaries for the most recent threads:

            >>> mem_functions = [
            ...     f["id"] for f in client.list_memory_functions(target_type="thread")
            ... ]
            >>> client.query_user_memory(
            ...     user_id,
            ...     text="pikas",
            ...     k=10,
            ...     thread_summaries=mem_functions,
            ...     thread_summaries_k=5,
            ... )
    """
    thread_query = None
    if thread_summaries is not None:
        thread_query = {
            "memory_function_ids": thread_summaries,
        }
        if thread_summaries_k is not None:
            thread_query["k"] = thread_summaries
    response = self.client.post(
        f"/users/{_as_uuid(user_id)}/memory/query",
        data=json.dumps(  # type: ignore[arg-type]
            {
                "text": text,
                "k": k,
                "memory_function_ids": memory_function_ids,
                "weights": weights,
                "state": states_to_return,
                "thread_query": thread_query,
            },
            default=_default_serializer,
        ),
    )
    raise_for_status_with_text(response)
    return response.json()

create_memory_function(parameters, *, target_type='user_state', name=None, description=None, custom_instructions=None, function_id=None)

Create a memory function.

Parameters:

Name Type Description Default
parameters Union[BaseModel, dict]

The memory function's parameters.

required
target_type str

The memory function's target type. Defaults to "user_state".

'user_state'
name Optional[str]

The memory function's name. Defaults to None.

None
description Optional[str]

The memory function's description. Defaults to None.

None
custom_instructions Optional[str]

The memory function's custom instructions. Defaults to None.

None
function_id Optional[ID_T]

The memory function's ID. Defaults to None.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The memory function's data.

Examples:

Create a user profile memory function:

    >>> from pydantic import BaseModel, Field
    >>> from langmem import Client
    >>> client = Client()
    >>> class UserProfile(BaseModel):
    ...     name: str = Field(description="The user's name")
    ...     age: int = Field(description="The user's age")
    ...     interests: List[str] = Field(description="The user's interests")
    ...     relationships: Dict[str, str] = Field(
    ...         description="The user's friends, family, pets,and other relationships."
    ...     )
    >>> memory_function = client.create_memory_function(
    ...     UserProfile,
    ...     target_type="user_state",
    ...     name="User Profile",
    ... )

Create an append-only user memory function:

    >>> class FormativeEvent(BaseModel):
    ...     event: str = Field(description="The formative event that occurred.")
    ...     impact: str = Field(description="How this event impacted the user.")
    >>> event_function = client.create_memory_function(
    ...     FormativeEvent, target_type="user_append_state"
    ... )
Source code in langmem/client.py
def create_memory_function(
    self,
    parameters: Union[BaseModel, dict],
    *,
    target_type: str = "user_state",
    name: Optional[str] = None,
    description: Optional[str] = None,
    custom_instructions: Optional[str] = None,
    function_id: Optional[ID_T] = None,
) -> Dict[str, Any]:
    """Create a memory function.

    Args:
        parameters (Union[BaseModel, dict]): The memory function's parameters.
        target_type (str, optional): The memory function's target type. Defaults to "user_state".
        name (Optional[str], optional): The memory function's name. Defaults to None.
        description (Optional[str], optional): The memory function's description. Defaults to None.
        custom_instructions (Optional[str], optional): The memory function's custom instructions. Defaults to None.
        function_id (Optional[ID_T], optional): The memory function's ID. Defaults to None.

    Returns:
        Dict[str, Any]: The memory function's data.

    Examples:

        Create a user profile memory function:

            >>> from pydantic import BaseModel, Field
            >>> from langmem import Client
            >>> client = Client()
            >>> class UserProfile(BaseModel):
            ...     name: str = Field(description="The user's name")
            ...     age: int = Field(description="The user's age")
            ...     interests: List[str] = Field(description="The user's interests")
            ...     relationships: Dict[str, str] = Field(
            ...         description="The user's friends, family, pets,and other relationships."
            ...     )
            >>> memory_function = client.create_memory_function(
            ...     UserProfile,
            ...     target_type="user_state",
            ...     name="User Profile",
            ... )

        Create an append-only user memory function:

            >>> class FormativeEvent(BaseModel):
            ...     event: str = Field(description="The formative event that occurred.")
            ...     impact: str = Field(description="How this event impacted the user.")
            >>> event_function = client.create_memory_function(
            ...     FormativeEvent, target_type="user_append_state"
            ... )

    """
    if isinstance(parameters, dict):
        params = parameters
    else:
        params = parameters.model_json_schema()
    function_schema = {
        "name": name or params.pop("title", ""),
        "description": description or params.pop("description", ""),
        "parameters": params,
    }
    data = {
        "type": target_type,
        "custom_instructions": custom_instructions,
        "id": function_id or str(uuid.uuid4()),
        "schema": function_schema,
    }
    response = self.client.post("/memory-functions", json=data)
    raise_for_status_with_text(response)
    return response.json()

get_memory_function(memory_function_id)

Get a memory function.

Parameters:

Name Type Description Default
memory_function_id ID_T

The memory function's ID.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The memory function's data.

Source code in langmem/client.py
def get_memory_function(self, memory_function_id: ID_T) -> Dict[str, Any]:
    """Get a memory function.

    Args:
        memory_function_id (ID_T): The memory function's ID.

    Returns:
        Dict[str, Any]: The memory function's data.
    """
    response = self.client.get(f"/memory-functions/{_as_uuid(memory_function_id)}")
    raise_for_status_with_text(response)
    return response.json()

list_memory_functions(*, target_type=None)

List memory functions.

Parameters:

Name Type Description Default
target_type Sequence[str]

The memory function's target type. Defaults to None.

None

Returns:

Type Description
Iterable[Dict[str, Any]]

List[Dict[str, Any]]: The memory functions' data.

Source code in langmem/client.py
def list_memory_functions(
    self, *, target_type: Optional[Sequence[str]] = None
) -> Iterable[Dict[str, Any]]:
    """List memory functions.

    Args:
        target_type (Sequence[str], optional): The memory function's target type. Defaults to None.

    Returns:
        List[Dict[str, Any]]: The memory functions' data.
    """
    body = {}
    if target_type is not None:
        body["target_type"] = (
            [target_type] if isinstance(target_type, str) else target_type
        )
    cursor = None
    while True:
        if cursor is not None:
            body["cursor"] = cursor
        response = self.client.post("/memory-functions/query", json=body)
        raise_for_status_with_text(response)
        data = response.json()
        for function in data.get("memory_functions", []):
            yield function
        cursor = data.get("next_cursor")
        if cursor is None:
            break

update_memory_function(memory_function_id, *, name=None, schema=None, custom_instructions=None, description=None, function_type=None, status=None)

Update a memory function.

Parameters:

Name Type Description Default
memory_function_id ID_T

The memory function's ID.

required
name Optional[str]

The memory function's name. Defaults to None.

None
schema Optional[Union[BaseModel, dict]]

The memory function's schema. Defaults to None.

None
custom_instructions Optional[str]

The memory function's custom instructions. Defaults to None.

None
description Optional[str]

The memory function's description. Defaults to None.

None
function_type Optional[str]

The memory function's type. Defaults to None.

None
status Optional[Literal['active', 'disabled']]

Optional[Literal["active", "disabled"]], optional): The memory function's status. Use to activate or disable the memory function. Disabled memory functions no longer trigger on new threads.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The memory function's data.

Examples:

Update a memory function's name:
    >>> from langmem import Client
    >>> client = Client()
    >>> memory_function_id = list(client.list_memory_functions())[0]["id"]
    >>> client.update_memory_function(memory_function_id, name="New Name")

Disable a memory function:
    >>> client.update_memory_function(memory_function_id, status="disabled")

Update a memory function's schema:
    >>> from pydantic import BaseModel, Field
    >>> class UserProfile:
    ...     name: str = Field(description="The user's name")
    ...     favorite_animals: List[str] = Field(
    ...         description="The user's favorite animals"
    ...     )
    >>> client.update_memory_function(memory_function_id, schema=UserProfile)

Update the custom instructions for a memory function:

    >>> client.update_memory_function(
    ...     memory_function_id,
    ...     custom_instructions="Update the user profile."
    ...     " Never delete anything in the current one."
    ...     " If you don't know, guess as much as you'd like.",
    ... )
Source code in langmem/client.py
def update_memory_function(
    self,
    memory_function_id: ID_T,
    *,
    name: Optional[str] = None,
    schema: Optional[Union[BaseModel, dict]] = None,
    custom_instructions: Optional[str] = None,
    description: Optional[str] = None,
    function_type: Optional[str] = None,
    status: Optional[Literal["active", "disabled"]] = None,
) -> Dict[str, Any]:
    """Update a memory function.

    Args:
        memory_function_id (ID_T): The memory function's ID.
        name (Optional[str], optional): The memory function's name. Defaults to None.
        schema (Optional[Union[BaseModel, dict]], optional): The memory function's schema. Defaults to None.
        custom_instructions (Optional[str], optional): The memory function's custom instructions. Defaults to None.
        description (Optional[str], optional): The memory function's description. Defaults to None.
        function_type (Optional[str], optional): The memory function's type. Defaults to None.
        status: Optional[Literal["active", "disabled"]], optional): The memory function's status.
            Use to activate or disable the memory function. Disabled memory functions no longer
            trigger on new threads.

    Returns:
        Dict[str, Any]: The memory function's data.


    Examples:

        Update a memory function's name:
            >>> from langmem import Client
            >>> client = Client()
            >>> memory_function_id = list(client.list_memory_functions())[0]["id"]
            >>> client.update_memory_function(memory_function_id, name="New Name")

        Disable a memory function:
            >>> client.update_memory_function(memory_function_id, status="disabled")

        Update a memory function's schema:
            >>> from pydantic import BaseModel, Field
            >>> class UserProfile:
            ...     name: str = Field(description="The user's name")
            ...     favorite_animals: List[str] = Field(
            ...         description="The user's favorite animals"
            ...     )
            >>> client.update_memory_function(memory_function_id, schema=UserProfile)

        Update the custom instructions for a memory function:

            >>> client.update_memory_function(
            ...     memory_function_id,
            ...     custom_instructions="Update the user profile."
            ...     " Never delete anything in the current one."
            ...     " If you don't know, guess as much as you'd like.",
            ... )


    """
    data: dict = {
        "name": name,
        "description": description,
        "custom_instructions": custom_instructions,
        "type": function_type,
        "status": status,
    }
    if schema is not None:
        if isinstance(schema, dict):
            data["schema"] = schema
        else:
            data["schema"] = schema.model_json_schema()
    response = self.client.patch(
        f"/memory-functions/{_as_uuid(memory_function_id)}",
        json={k: v for k, v in data.items() if v is not None},
    )
    raise_for_status_with_text(response)
    return response.json()

delete_memory_function(memory_function_id)

Delete a memory function.

Parameters:

Name Type Description Default
memory_function_id ID_T

The memory function's ID.

required
Source code in langmem/client.py
def delete_memory_function(
    self,
    memory_function_id: ID_T,
) -> None:
    """Delete a memory function.

    Args:
        memory_function_id (ID_T): The memory function's ID.
    """
    response = self.client.delete(
        f"/memory-functions/{_as_uuid(memory_function_id)}"
    )
    raise_for_status_with_text(response)
    return response.json()

create_thread(*, thread_id=None, messages=None, metadata=None)

Create a thread.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

None
messages Sequence[Dict[str, Any]]

The messages to add.

None
metadata Dict[str, str]

The thread's metadata. Defaults to {}.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The thread's data.

Source code in langmem/client.py
def create_thread(
    self,
    *,
    thread_id: Optional[ID_T] = None,
    messages: Optional[Sequence[schemas.MESSAGE_LIKE]] = None,
    metadata: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
    """Create a thread.

    Args:
        thread_id (ID_T): The thread's ID.
        messages (Sequence[Dict[str, Any]]): The messages to add.
        metadata (Dict[str, str], optional): The thread's metadata. Defaults to {}.

    Returns:
        Dict[str, Any]: The thread's data.
    """
    data = {
        "id": thread_id,
        "messages": messages,
        "metadata": metadata,
    }
    response = self.client.post("/threads", json=data)
    raise_for_status_with_text(response)
    return response.json()

add_messages(thread_id, *, messages)

Add messages to a thread.

This method allows you to add multiple messages to a specific thread identified by its ID. If the thread is not found, it will be created implicitly.

Parameters:

Name Type Description Default
thread_id ID_T

The ID of the thread to which the messages will be added.

required
messages Sequence[Dict[str, Any]]

A sequence of dictionaries representing the messages to be added. Each dictionary should contain the necessary information for a single message, such as its content, author, timestamp, etc.

required

Examples:

Add messages in a new thread:

>>> from langmem import Client
>>> client = Client()
>>> messages = [
...     {
...         "role": "user",
...         "content": "Did you know pikas make their own haypiles?",
...         "name": "Will",
...         "metadata": {"user_id": user_id},
...     },
...     {
...         "role": "assistant",
...         "content": "Yes, pikas are fascinating creatures!",
...         "name": "Bot",
...     },
... ]
>>> client.add_messages(thread_id, messages=messages)

Raises:

Type Description
HTTPError

If the request to add the messages fails.

Returns:

Name Type Description
None None

This method does not return any value.

Source code in langmem/client.py
def add_messages(
    self, thread_id: ID_T, *, messages: Sequence[Dict[str, Any]]
) -> None:
    """Add messages to a thread.

    This method allows you to add multiple messages to a specific thread identified by its ID.
    If the thread is not found, it will be created implicitly.

    Args:
        thread_id (ID_T): The ID of the thread to which the messages will be added.
        messages (Sequence[Dict[str, Any]]): A sequence of dictionaries representing the messages to be added.
            Each dictionary should contain the necessary information for a single message, such as its content,
            author, timestamp, etc.

    Examples:

        Add messages in a new thread:

        >>> from langmem import Client
        >>> client = Client()
        >>> messages = [
        ...     {
        ...         "role": "user",
        ...         "content": "Did you know pikas make their own haypiles?",
        ...         "name": "Will",
        ...         "metadata": {"user_id": user_id},
        ...     },
        ...     {
        ...         "role": "assistant",
        ...         "content": "Yes, pikas are fascinating creatures!",
        ...         "name": "Bot",
        ...     },
        ... ]
        >>> client.add_messages(thread_id, messages=messages)


    Raises:
        HTTPError: If the request to add the messages fails.

    Returns:
        None: This method does not return any value.
    """
    data = {"messages": messages}
    response = self.client.post(
        f"/threads/{_as_uuid(thread_id)}/add_messages",
        data=json.dumps(data, default=_default_serializer),  # type: ignore[arg-type]
    )
    raise_for_status_with_text(response)
    return response.json()

get_thread(thread_id)

Get a thread.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The thread's data.

Source code in langmem/client.py
def get_thread(self, thread_id: ID_T) -> Dict[str, Any]:
    """Get a thread.

    Args:
        thread_id (ID_T): The thread's ID.

    Returns:
        Dict[str, Any]: The thread's data.
    """
    response = self.client.get(f"/threads/{_as_uuid(thread_id)}")
    raise_for_status_with_text(response)
    return response.json()

list_threads()

List threads.

Returns:

Type Description
Iterable[Dict[str, Any]]

Iterable[Dict[str, Any]]: The threads' data.

Source code in langmem/client.py
def list_threads(self) -> Iterable[Dict[str, Any]]:
    """List threads.

    Returns:
        Iterable[Dict[str, Any]]: The threads' data.
    """
    response = self.client.get("/threads")
    raise_for_status_with_text(response)
    return response.json()

list_thread_memory(thread_id)

List a thread's memory.

This method retrieves all memories associated with a given thread. It will return outputs from all memory function types defined for the thread.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: The thread's memory.

Examples:

>>> from langmem import Client
>>> client = Client()
>>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
>>> memories = client.list_thread_memory(thread_id)
>>> for memory in memories:
...     print(memory)
Source code in langmem/client.py
def list_thread_memory(self, thread_id: ID_T) -> List[Dict[str, Any]]:
    """List a thread's memory.

    This method retrieves all memories associated with a given thread.
    It will return outputs from all memory function types defined for the thread.

    Args:
        thread_id (ID_T): The thread's ID.

    Returns:
        List[Dict[str, Any]]: The thread's memory.

    Examples:

        >>> from langmem import Client
        >>> client = Client()
        >>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
        >>> memories = client.list_thread_memory(thread_id)
        >>> for memory in memories:
        ...     print(memory)
    """
    response = self.client.get(f"/threads/{_as_uuid(thread_id)}/memory")
    raise_for_status_with_text(response)
    return response.json()

trigger_all_for_thread(thread_id)

Trigger all memory functions for a thread.

This method eagerly processes any pending memories for the given thread. It will trigger all memory function types defined for the thread.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required

Examples:

>>> from langmem import Client
>>> client = Client()
>>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
>>> client.trigger_all_for_thread(thread_id)
Source code in langmem/client.py
def trigger_all_for_thread(self, thread_id: ID_T) -> None:
    """Trigger all memory functions for a thread.

    This method eagerly processes any pending memories for the given thread.
    It will trigger all memory function types defined for the thread.

    Args:
        thread_id (ID_T): The thread's ID.

    Examples:

        >>> from langmem import Client
        >>> client = Client()
        >>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
        >>> client.trigger_all_for_thread(thread_id)
    """
    response = self.client.post(f"/threads/{_as_uuid(thread_id)}/trigger-all")
    raise_for_status_with_text(response)
    return response.json()

get_thread_memory(thread_id, *, memory_function_id)

Get a thread's memory state.

This method retrieves the current memory state for a specific thread and memory function. It is faster than querying and useful for "thread_state" type memories.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required
memory_function_id ID_T

The memory function's ID.

required

Returns:

Name Type Description
dict dict

The memory state.

Examples:

>>> from langmem import Client
>>> client = Client()
>>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
>>> memory_function_id = "cb217ff7-963e-44fc-b222-01f01058d64b"
>>> client.get_thread_memory(thread_id, memory_function_id=memory_function_id)
Source code in langmem/client.py
def get_thread_memory(
    self,
    thread_id: ID_T,
    *,
    memory_function_id: ID_T,
) -> dict:
    """Get a thread's memory state.

    This method retrieves the current memory state for a specific thread and memory function.
    It is faster than querying and useful for "thread_state" type memories.

    Args:
        thread_id (ID_T): The thread's ID.
        memory_function_id (ID_T): The memory function's ID.

    Returns:
        dict: The memory state.

    Examples:

        >>> from langmem import Client
        >>> client = Client()
        >>> thread_id = "e4d2c7a0-9441-4ea2-8ebe-2204f3e95a28"
        >>> memory_function_id = "cb217ff7-963e-44fc-b222-01f01058d64b"
        >>> client.get_thread_memory(thread_id, memory_function_id=memory_function_id)
    """
    response = self.client.get(
        f"/threads/{_as_uuid(thread_id)}/memory/{_as_uuid(memory_function_id)}/state"
    )
    raise_for_status_with_text(response)
    return response.json()

add_thread_state(thread_id, state, *, key=None)

Add a thread state.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required
state Dict[str, Any]

The thread state.

required
Source code in langmem/client.py
def add_thread_state(
    self, thread_id: ID_T, state: Dict[str, Any], *, key: Optional[str] = None
) -> None:
    """Add a thread state.

    Args:
        thread_id (ID_T): The thread's ID.
        state (Dict[str, Any]): The thread state.
    """
    response = self.client.post(
        f"/threads/{_as_uuid(thread_id)}/thread_state",
        json={"state": state, "key": key},
    )
    raise_for_status_with_text(response)
    return response.json()

get_thread_state(thread_id, *, key=None)

Get a thread state.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required

Returns:

Name Type Description
GetThreadStateResponse dict

The thread state.

Source code in langmem/client.py
def get_thread_state(self, thread_id: ID_T, *, key: Optional[str] = None) -> dict:
    """Get a thread state.

    Args:
        thread_id (ID_T): The thread's ID.

    Returns:
        GetThreadStateResponse: The thread state.
    """
    response = self.client.post(
        f"/threads/{_as_uuid(thread_id)}/thread_state/query", json={"key": key}
    )
    raise_for_status_with_text(response)
    return response.json()

list_messages(thread_id, *, response_format=None, page_size=None, limit=None, ascending_order=None)

List a thread's messages.

Parameters:

Name Type Description Default
thread_id ID_T

The thread's ID.

required
response_format Optional[Literal['openai', 'langmem']]

The response format. Defaults to None, which is the openai format.

None
page_size Optional[int]

The page size. Defaults to None.

None
limit Optional[int]

The maximum number of messages to return. Defaults to None.

None
ascending_order Optional[bool]

Whether to return messages in ascending_order order. Defaults to None.

None

Returns:

Type Description
Iterable[Dict[str, Any]]

Iterable[Dict[str, Any]]: The messages' data.

Source code in langmem/client.py
def list_messages(
    self,
    thread_id: ID_T,
    *,
    response_format: Optional[Literal["openai", "langmem"]] = None,
    page_size: Optional[int] = None,
    limit: Optional[int] = None,
    ascending_order: Optional[bool] = None,
) -> Iterable[Dict[str, Any]]:
    """List a thread's messages.

    Args:
        thread_id (ID_T): The thread's ID.
        response_format (Optional[Literal["openai", "langmem"]], optional): The response format.
            Defaults to None, which is the openai format.
        page_size (Optional[int], optional): The page size. Defaults to None.
        limit (Optional[int], optional): The maximum number of messages to return. Defaults to None.
        ascending_order (Optional[bool], optional): Whether to return messages in ascending_order order.
            Defaults to None.

    Returns:
        Iterable[Dict[str, Any]]: The messages' data.
    """
    params: Dict[str, Any] = {
        "response_format": response_format,
        "page_size": page_size,
        "ascending_order": ascending_order,
    }
    params = {k: v for k, v in params.items() if v is not None}
    cursor: Optional[str] = None
    idx = 0
    while True:
        if cursor is not None:
            params["cursor"] = cursor
        response = self.client.get(
            f"/threads/{_as_uuid(thread_id)}/messages", params=params
        )
        raise_for_status_with_text(response)
        data = response.json()
        for message in data.get("messages", []):
            yield message
            idx += 1
            if limit is not None and idx >= limit:
                break
        cursor = data.get("next_cursor")
        if cursor is None or (limit is not None and idx >= limit):
            break

raise_for_status_with_text(response)

Raise an error with the response text.

Source code in langmem/client.py
def raise_for_status_with_text(response: httpx.Response) -> None:
    """Raise an error with the response text."""
    try:
        response.raise_for_status()
    except httpx.HTTPError as e:
        raise httpx.HTTPError(f"{str(e)}: {response.text}") from e