# 基础调用 output = llm([HumanMessage(content="Translate to French: I love programming.")]) print(output) # AIMessage(content="J'aime programmer.")
带角色设定的对话:
1 2 3 4 5 6 7
from langchain.schema import SystemMessage
messages = [ SystemMessage(content="You are a helpful assistant that translates English to French."), HumanMessage(content="I love programming.") ] output = llm(messages)
批量生成:
1 2 3 4 5
batch_messages = [ [SystemMessage(content="Translate to French"), HumanMessage(content="I love programming.")], [SystemMessage(content="Translate to French"), HumanMessage(content="Hello world.")], ] output = llm.generate(batch_messages)
from langchain.prompts.chat import ( ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, )
# 定义系统模板 system_template = "You are a translator from {input_language} to {output_language}." system_message = SystemMessagePromptTemplate.from_template(system_template)
from langchain.chains import LLMChain, SequentialChain from langchain.prompts import ChatPromptTemplate
# 步骤1:翻译评论 first_prompt = ChatPromptTemplate.from_template( "Translate the following review to english:\n\n{Review}" ) chain_one = LLMChain( llm=llm, prompt=first_prompt, output_key="English_Review" )
# 步骤2:一句话总结 second_prompt = ChatPromptTemplate.from_template( "Summarize the following review in 1 sentence:\n\n{English_Review}" ) chain_two = LLMChain( llm=llm, prompt=second_prompt, output_key="summary" )
# 步骤3:检测语言 third_prompt = ChatPromptTemplate.from_template( "What language is this review? Only answer the language name:\n\n{Review}" ) chain_three = LLMChain( llm=llm, prompt=third_prompt, output_key="language" )
# 步骤4:生成回复 fourth_prompt = ChatPromptTemplate.from_template( "Write a follow up response to this summary in the specified language:\n\n" "Summary: {summary}\n\nLanguage: {language}" ) chain_four = LLMChain( llm=llm, prompt=fourth_prompt, output_key="followup_message" )
# 运行 try: output = agent.run( "What was the high temperature in SF yesterday in Fahrenheit? " "What is that number raised to the .023 power?" ) print(output) except Exception as e: print(f"Error: {e}")
执行过程大概这样:
1 2 3 4 5 6 7 8
> Entering new AgentExecutor chain... Thought: I need to find the temperature and calculate... Action: Use calculator Action Input: 72.21 ^ 0.023 Observation: 1.023... Thought: I now know the final answer Final Answer: 1.023... > Finished chain.
结构化对话Agent
复杂工具需要结构化参数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from langchain.tools import StructuredTool
defssh(command: str, host: str, username: str = "root") -> str: """Connect to remote server and execute commands.""" import os return os.popen(f"ssh {host} -l{username} '{command}'").read()
Observation: 15:48:44 up 25 days, 41 min, load average: 1.04 Thought: I have the answer Final Answer: This machine has been running for 25 days and 41 minutes.
# 构建对话历史 messages = [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hi there!"}, {"role": "assistant", "content": "Hello! How can I help you?"}, {"role": "user", "content": "What's the weather like?"} ]
from langchain.prompts import ChatPromptTemplate from langchain.chains import LLMChain
# 客服提示模板 customer_service_prompt = ChatPromptTemplate.from_template(""" You are a customer service AI assistant. Your task is to send an email reply to a valued customer. Given the customer email delimited by ```, Generate a reply to thank the customer for their review. If the sentiment is positive or neutral, thank them for their review. If the sentiment is negative, apologize and suggest that they can reach out to customer service. Make sure to use specific details from the review. Write in a concise and professional tone. Sign the email as `AI customer agent`. Customer review: ```{review}``` Review sentiment: {sentiment} """)
# 情感分析函数 defanalyze_sentiment(review: str) -> str: sentiment_prompt = f"Classify the sentiment of this review: {review}" result = llm([HumanMessage(content=sentiment_prompt)]) return result.content.lower()