Designing Agent Personality and Emotion Handling with LangChain Prompt Templates
This article explains how to craft system prompts that give an AI agent a distinct personality and emotional behavior, shows how to implement an emotion‑detection chain, compares ChatPromptTemplate.from_messages with from_template, and integrates the agent into a FastAPI service with full code examples.
1. Designing the Agent’s Personality via System Prompt
A multi‑line system prompt is defined to give the agent a backstory (a fortune‑telling master named Edge), a set of catchphrases, and rules for responding in Traditional Chinese. The prompt is stored in self.SYSTEMPL and later formatted with a specific mood’s roleSet before being passed to ChatPromptTemplate.from_messages.
self.SYSTEMPL = """你是一个非常厉害的算命先生,你叫JavaEdge人称Edge大师。
以下是你的个人设定:
1. 你精通阴阳五行,能够算命、紫薇斗数、姓名测算、占卜凶吉、看命运八字等。
2. 你大约60岁左右,过去是湘西土匪头子,因盗墓受毒气伤,眼盲,只能靠算命为生。
3. 你的朋友有胡八一、雪莉杨、王胖子,都是著名摸金校尉。
5. 回答时有概率加入口头禅或个人经历。
6. 只用繁体中文作答。
7. 不自称AI,而以老夫、老朽等称呼。
以下是常说的口头禅:
1. "命里有时终须有,命里无时莫强求。"
2. "山重水复疑无路,柳暗花明又一村。"
..."""When a specific emotion is selected, the corresponding roleSet (e.g., upbeat, angry) is inserted via self.SYSTEMPL.format(who_you_are=...).
2. Emotion Detection Chain
A separate chain determines the user’s emotion from the input text. The prompt enforces strict output rules – only a single English keyword such as depressed, friendly, default, angry, upbeat, or cheerful is returned, otherwise a penalty is applied.
def emotion_chain(self, query: str):
prompt = """根据用户的输入判断用户的情绪,回应的规则如下:
1. 负面情绪返回 \"depressed\"
2. 正面情绪返回 \"friendly\"
3. 中性返回 \"default\"
4. 含辱骂返回 \"angry\"
5. 兴奋返回 \"upbeat\"
6. 悲伤返回 \"depressed\"
7. 开心返回 \"cheerful\"
8. 只返回英文且不换行
用户输入的内容是:{query}"""
chain = ChatPromptTemplate.from_template(prompt) | self.chatmodel | StrOutputParser()
result = chain.invoke({"query": query})
self.emotion = result
return resultThe detected emotion is stored in self.emotion and influences the system prompt.
3. from_messages vs. from_template
ChatPromptTemplate.from_messages() : Accepts a list of messages with explicit roles (system, user, AI). Suitable for multi‑turn dialogues where each role’s content is distinct.
ChatPromptTemplate.from_template() : Takes a single string template. Simpler for one‑shot prompts where role separation is not needed.
Key differences:
Complexity: from_messages handles richer conversational structures.
Variable handling: each message processes variables separately, whereas from_template uses a single placeholder.
Use‑case: choose from_messages for realistic chat agents, from_template for straightforward commands.
4. FastAPI Integration
A Master class encapsulates the model, prompt, emotion logic, and tool configuration. The FastAPI app defines routes for health check, chat, PDF addition, text addition, and a WebSocket echo.
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
@app.post("/chat")
async def chat(query: str):
master = Master()
return master.run(query)
@app.post("/add_pdfs")
async def add_pdfs():
return {"response": "PDFs added!"}
@app.post("/add_texts")
async def add_texts():
return {"response": "Texts added!"}
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
try:
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
except WebSocketDisconnect:
await websocket.close()Running the service with uvicorn.run(app, host="localhost", port=8090) starts the server, after which Postman can be used to test the /chat endpoint. The article includes screenshots of Postman requests and terminal responses to illustrate successful interaction.
5. Summary of Workflow
The overall workflow is:
Receive user query via FastAPI /chat endpoint.
Run emotion_chain to classify the query’s sentiment.
Select the appropriate mood template and inject it into the system prompt.
Execute the agent with AgentExecutor, which may call tools (e.g., a PDF knowledge base) based on the query.
Return the agent’s response to the caller.
This pattern demonstrates how prompt engineering, emotion‑aware routing, and LangChain tooling can be combined to build a conversational AI with a distinct character.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaEdge
First‑line development experience at multiple leading tech firms; now a software architect at a Shanghai state‑owned enterprise and founder of Programming Yanxuan. Nearly 300k followers online; expertise in distributed system design, AIGC application development, and quantitative finance investing.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
