47 lines
1.2 KiB
Python
47 lines
1.2 KiB
Python
"""
|
|
Use the custom BaseChatModel-like class ChatQwenOpenAICompat with LangGraph.
|
|
|
|
Prereqs:
|
|
pip install -U langgraph langchain httpx
|
|
|
|
Env:
|
|
export QWEN_API_KEY=sk-...
|
|
export QWEN_BASE_URL=https://dashscope-intl.aliyuncs.com/compatible-mode/v1
|
|
export QWEN_MODEL=qwen3-coder-flash
|
|
"""
|
|
|
|
from langgraph.prebuilt import create_react_agent
|
|
from langchain_core.messages import HumanMessage
|
|
|
|
try:
|
|
from langchain.tools import tool
|
|
except Exception:
|
|
from langchain_core.tools import tool # type: ignore
|
|
|
|
from langgraph_qwen import ChatQwenOpenAICompat
|
|
|
|
|
|
@tool
|
|
def multiply(x_and_y: str) -> str:
|
|
"""Multiply two integers given as 'x y'."""
|
|
try:
|
|
a, b = [int(s) for s in x_and_y.strip().split()]
|
|
except Exception:
|
|
return "Please provide two integers: 'x y'"
|
|
return str(a * b)
|
|
|
|
|
|
def main():
|
|
base = ChatQwenOpenAICompat(temperature=0)
|
|
model = base.bind_tools([multiply]).bind(tool_choice="auto")
|
|
|
|
agent = create_react_agent(model, [multiply])
|
|
res = agent.invoke({"messages": [HumanMessage(content="计算 6 和 7 的乘积,然后解释你的步骤。")]} )
|
|
print("\n=== Final ===\n")
|
|
print(res["messages"][-1].content)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|