forked from generative-computing/mellea
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlangchain_messages.py
More file actions
46 lines (37 loc) · 1.59 KB
/
langchain_messages.py
File metadata and controls
46 lines (37 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# pytest: ollama, e2e, qualitative
# Installing langchain is necessary for this example, but it works for any library
# you may want to use Mellea with.
from typing import Any
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
# Messages from a different library.
messages = [
SystemMessage(content="You are a helpful assistant"),
HumanMessage(content="Hello!"),
AIMessage(content="Hi there!"),
]
# Some libraries have conversion functions that make it easier to ingest into Mellea.
from langchain_core.messages import convert_to_openai_messages
openai_messages: list[dict[str, Any]] = convert_to_openai_messages(messages=messages)
# Import Mellea.
from mellea import start_session
from mellea.backends import ModelOption
from mellea.stdlib.components import Message
from mellea.stdlib.context import ChatContext
# Mellea uses explicit contexts. Cast the OpenAI formatted messages into
# Mellea messages and add them to the context.
ctx = ChatContext()
for msg in openai_messages:
ctx = ctx.add(
# NOTE: If your messages aren't in OpenAI format or have additional data like
# documents / images, you need to explicitly grab those fields as well.
Message(role=msg["role"], content=msg["content"])
)
# Utilize that new ChatContext to ask the assistant about its past messages.
m = start_session(ctx=ctx)
response = m.chat(
"What exact words did the AI assistant use in its most recent response?",
model_options={
ModelOption.SEED: 123
}, # Utilizing a seed for consistency in the example.
).content
assert "Hi there!" in response