forked from epec254/rag_code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2_hello_world_parameterized_chain.py
More file actions
86 lines (68 loc) · 2.31 KB
/
Copy path2_hello_world_parameterized_chain.py
File metadata and controls
86 lines (68 loc) · 2.31 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
47
48
49
50
51
52
53
54
55
56
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
# Databricks notebook source
# DBTITLE 1,Install RAG Studio packages
# MAGIC %run ./wheel_installer
# COMMAND ----------
# Before logging this chain using the driver notebook, you need to comment out this line.
dbutils.library.restartPython()
# COMMAND ----------
from langchain_core.output_parsers import StrOutputParser
from langchain.schema.runnable import RunnableLambda
from operator import itemgetter
from databricks import rag
# COMMAND ----------
# DBTITLE 1,Hello World Model
############
# RAG Studio requires your chain to accept an array of OpenAI-formatted messages as a `messages` parameter. Schema: https://docs.databricks.com/en/machine-learning/foundation-models/api-reference.html#chatmessage
# These helper functions help parse the `messages` array
############
# Return the string contents of the most recent message from the user
def extract_user_query_string(chat_messages_array):
return chat_messages_array[-1]["content"]
# Return the chat history, which is is everything before the last question
def extract_chat_history(chat_messages_array):
return chat_messages_array[:-1]
############
# Get the configuration YAML
############
rag_config = rag.RagConfig("2_hello_world_config.yaml")
############
# Fake model for this hello world example.
############
def fake_model(input):
return f"Config: {rag_config.get('sample_param')}. You asked `{input.get('user_query')}`. Conversation history: {input.get('chat_history')}"
############
# Simplest chain example
############
# RAG Studio requires the chain to return a string value.
chain = (
{
"user_query": itemgetter("messages")
| RunnableLambda(extract_user_query_string),
"chat_history": itemgetter("messages") | RunnableLambda(extract_chat_history),
}
| RunnableLambda(fake_model)
| StrOutputParser()
)
############
# You can test this chain locally in the notebook
############
question = {
"messages": [
{
"role": "user",
"content": "question 1",
},
{
"role": "assistant",
"content": "answer 1",
},
{
"role": "user",
"content": "new question!!",
},
]
}
chain.invoke(question)
# COMMAND ----------
# You need to call `set_chain` in order for RAG Studio to log your chain.
rag.set_chain(chain)