%pip install llama-index-core
设置¶
In [ ]
已复制!
from llama_index.core.memory import ChatMemoryBuffer
memory = ChatMemoryBuffer.from_defaults(token_limit=40000)
from llama_index.core.memory import ChatMemoryBuffer memory = ChatMemoryBuffer.from_defaults(token_limit=40000)
独立使用¶
In [ ]
已复制!
from llama_index.core.llms import ChatMessage
chat_history = [
ChatMessage(role="user", content="Hello, how are you?"),
ChatMessage(role="assistant", content="I'm doing well, thank you!"),
]
# put a list of messages
memory.put_messages(chat_history)
# put one message at a time
# memory.put_message(chat_history[0])
from llama_index.core.llms import ChatMessage chat_history = [ ChatMessage(role="user", content="你好,你好吗?"), ChatMessage(role="assistant", content="我很好,谢谢!"), ] # put a list of messages memory.put_messages(chat_history) # put one message at a time # memory.put_message(chat_history[0])
In [ ]
已复制!
# Get the last X messages that fit into a token limit
history = memory.get()
# 获取符合 token 限制的最后 X 条消息 history = memory.get()
In [ ]
已复制!
# Get all messages
all_history = memory.get_all()
# 获取所有消息 all_history = memory.get_all()
In [ ]
已复制!
# clear the memory
memory.reset()
# 清空记忆 memory.reset()
与代理一起使用¶
您可以在任何代理的 .run() 方法中设置记忆。
In [ ]
已复制!
import os
os.environ["OPENAI_API_KEY"] = "sk-proj-..."
import os os.environ["OPENAI_API_KEY"] = "sk-proj-..." from llama_index.core.agent.workflow import ReActAgent, FunctionAgent from llama_index.core.workflow import Context from llama_index.llms.openai import OpenAI memory = ChatMemoryBuffer.from_defaults(token_limit=40000) agent = FunctionAgent(tools=[], llm=OpenAI(model="gpt-4o-mini")) # context to hold the chat history/state ctx = Context(agent)
In [ ]
已复制!
from llama_index.core.agent.workflow import ReActAgent, FunctionAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
memory = ChatMemoryBuffer.from_defaults(token_limit=40000)
agent = FunctionAgent(tools=[], llm=OpenAI(model="gpt-4o-mini"))
# context to hold the chat history/state
ctx = Context(agent)
resp = await agent.run("你好,你好吗?", ctx=ctx, memory=memory)
In [ ]
已复制!
resp = await agent.run("Hello, how are you?", ctx=ctx, memory=memory)
print(memory.get_all())
In [ ]
已复制!
print(memory.get_all())
回到顶部
[ChatMessage(role=<MessageRole.USER: 'user'>, additional_kwargs={}, blocks=[TextBlock(block_type='text', text='Hello, how are you?')]), ChatMessage(role=<MessageRole.ASSISTANT: 'assistant'>, additional_kwargs={}, blocks=[TextBlock(block_type='text', text="Hello! I'm just a program, so I don't have feelings, but I'm here and ready to help you. How can I assist you today?")])]