AI智能体的应用场景日益广泛。然而,对于许多初学者来说,构建一个有效的AI智能体似乎是一项艰巨的任务。本文将为你提供一份详细的指南,帮助你轻松迈出构建第一个AI智能体的第一步,并揭示其背后的原理和技巧。
python
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
Load environment variables
load_dotenv
Initialize the ChatOpenAI instance
llm = ChatOpenAI(model=”gpt-4o-mini”)
response = llm.invoke(“Hello! Are you working?”) print(response.content)
python test_setup.py
The original question or task
Tracks the agent’s thinking and decisions
Stores intermediate results from tools
llm = ChatOpenAI(model=”gpt-4o-mini”, temperature=0)
def
summarize_node
(state):
Create a template for the summarization prompt
This tells the model to summarize the input text in one sentence
summarization_prompt = PromptTemplate.from_template(
“””Summarize the following text in one short sentence.
Text: {input}
Summary:”””
)
Create a chain by connecting the prompt template to the language model
The “|” operator pipes the output of the prompt into the model
chain = summarization_prompt | llm
Execute the chain with the input text from the state dictionary
This passes the text to be summarized to the model
response = chain.invoke({“input”: state[“input”]})
Return a dictionary with the summary extracted from the model’s response
This will be merged into the agent’s state
return {“summary”: response.content}
workflow = StateGraph(State)
Add nodes to the graph
workflow.add_node(“classification_node”, classification_node)
workflow.add_node(“entity_extraction”, entity_extraction_node)
workflow.add_node(“summarization”, summarization_node)
Add edges to the graph
workflow.set_entry_point(“classification_node”) # Set the entry point of the graph
workflow.add_edge(“classification_node”, “entity_extraction”)
workflow.add_edge(“entity_extraction”, “summarization”)
workflow.add_edge(“summarization”, END)
Compile the graph
app = workflow.compile
Define a sample text about Anthropic’s MCP to test our agent
sample_text = “””
Anthropic’s MCP (Model Context Protocol) is an open-source powerhouse that lets your applications interact effortlessly with APIs across various systems.
“””
Create the initial state with our sample text
state_input = {“text”: sample_text}
Run the agent’s full workflow on our sample text
result = app.invoke(state_input)
Print each component of the result:
– The classification category (News, Blog, Research, or Other)
print(“Classification:”, result[“classification”])
– The extracted entities (People, Organizations, Locations)
print(“\nEntities:”, result[“entities”])
– The generated summary of the text
print(“\nSummary:”, result[“summary”])
欢迎光临 智客公社 (https://bbs.cnaiplus.com/) | Powered by Discuz! X3.5 |