To extract a list of prompts (i.e., content from messages where role == "user") from the "conversation_a" column in your Spark DataFrame, where the conversations are stored in a common "messages" format (likely a list of dictionaries like {"role": ..., "content": ...}), you can use PySpark with built-in functions such as from_json, explode, and filtering by role.
Step-by-step Solution (PySpark):
Assuming:
- The column
conversation_a is a JSON string or an array of message objects like this:
[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "How is the weather today?"},
{"role": "assistant", "content": "It's sunny."},
{"role": "user", "content": "What about tomorrow?"}
]
Option 1: If "conversation_a" is a JSON string
1. Define the schema for the conversation:
from pyspark.sql import SparkSession
from pyspark.sql.types import ArrayType, StructType, StructField, StringType
from pyspark.sql.functions import from_json, col, filter
# Initialize Spark session
spark = SparkSession.builder.getOrCreate()
# Schema of individual messages
message_schema = ArrayType(
StructType([
StructField("role", StringType(), True),
StructField("content", StringType(), True)
])
)
2. Parse the JSON column to actual array of structs:
df_parsed = df.withColumn("messages", from_json(col("conversation_a"), message_schema))
3. Extract user prompts:
# For Spark 3.1+, we can use the `filter` SQL function
df_user_prompts = df_parsed.withColumn(
"user_prompts",
filter(col("messages"), lambda x: x["role"] == "user")
).withColumn(
"user_prompt_contents",
expr("transform(user_prompts, x -> x.content)")
)
Now, the column user_prompt_contents will contain an array of prompt strings.
Option 2: If "conversation_a" is already an array column (not a JSON string)
Skip the JSON parsing (from_json) step and start directly from:
df_user_prompts = df.withColumn(
"user_prompts",
filter(col("conversation_a"), lambda x: x["role"] == "user")
).withColumn(
"user_prompt_contents",
expr("transform(user_prompts, x -> x.content)")
)
Example Output
For the input:
[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "How is the weather today?"},
{"role": "assistant", "content": "It's sunny."},
{"role": "user", "content": "What about tomorrow?"}
]
The resulting user_prompt_contents array would be:
["How is the weather today?", "What about tomorrow?"]
Let me know if your data is nested differently or stored in a different format (like a stringified list, or deeply nested structure), and I can adjust the solution accordingly.