LangChain
参考教程:https://kq4b3vgg5b.feishu.cn/wiki/OlrewlsjjiFYSJke6enci7eZnId
官方文档:https://python.langchain.com/api_reference/
ChatLangchain:https://chat.langchain.com/
ChatLangchain 的知识库貌似使用的之前的文档
import langchain
print(langchain.__version__) # 1.0.5
加载环境变量
这里需要下载第三方包
uv add python-dotenv
from dotenv import load_dotenv
load_dotenv() # 加载环境变量,可以指定.env文件路径 默认根目录下的.env文件
import os
os.getenv("OLLAMA_BASE_URL") # 获取env文件中的变量
使用OpenAI调试api
- 下载环境
uv add openai
- 进行调试
form openai import OpenAI
# 获取环境变量
longcat_base_url = os.getenv("LongCat_BASE_URL")
longcat_api_key = os.getenv("LongCat_API_KEY")
# 初始化客户端
client = OpenAI(api_key = longcat_api_key, base_url = longcat_base_url)
response = client.chat.completions.create(
model="LongCat-Flash-Chat",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello"},
],
)
print(response.choices[0].message.content)
模型初始化
可以使用对应的模型厂商提供的如langchain_openai,需要单独下载
也可以使用init_chat_model
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model=" ",api_key= ,base_url= )
model.invoke("")
AIMessage(content='The question *"What is the meaning of life?"* is one of the oldest and most profound inquiries in philosophy, religion, science, and personal reflection. There is no single, universally accepted answer, but here are some perspectives that people and traditions have offered:\n\n### **1. Philosophical Perspectives**\n- **Existentialism (Sartre, Camus, Nietzsche):** Life has no inherent meaning; we must create our own purpose through choices, actions, and passion. Camus famously compared life to *Sisyphean struggle*—but suggested we must imagine Sisyphus happy.\n- **Absurdism (Camus):** Life may be inherently meaningless, but we can find joy in the struggle itself, embracing the absurdity.\n- **Stoicism (Marcus Aurelius, Seneca):** Meaning comes from virtue, reason, and living in harmony with nature and our own nature.\n- **Nihilism (Schopenhauer, Nietzsche):** Life is fundamentally without objective meaning, but this can be liberating rather than despairing.\n\n### **2. Religious & Spiritual Perspectives**\n- **Abrahamic Religions (Christianity, Islam, Judaism):** Life’s meaning is found in devotion to God, moral living, and preparation for an afterlife.\n- **Eastern Philosophies (Buddhism, Hinduism, Taoism):** Meaning arises from enlightenment (*nirvana*), fulfilling one’s *dharma* (duty), or living in harmony with the *Tao* (the Way).\n- **Pantheism (Spinoza, some New Age thought):** The universe itself is divine, and meaning comes from unity with existence.\n\n### **3. Scientific & Naturalistic Perspectives**\n- **Biological:** Life’s "meaning" is survival, reproduction, and passing on genes (from an evolutionary standpoint).\n- **Cosmic:** Life is a rare but natural phenomenon in an indifferent universe; meaning is subjective, constructed by consciousness.\n- **Physics (e.g., Sean Carroll):** The universe operates by natural laws, but meaning is something humans create in the "emergent" realm of culture, relationships, and ideas.\n\n### **4. Psychological & Personal Perspectives**\n- **Viktor Frankl (Holocaust survivor, *Man’s Search for Meaning*):** Meaning is found through suffering, love, and a sense of purpose—even in adversity.\n- **Carl Jung & Depth Psychology:** Meaning arises from individuation (becoming your true self) and connecting with the collective unconscious.\n- **Modern Psychology (Seligman, PERMA model):** Meaning comes from relationships, accomplishments, engagement, and a sense of purpose.\n\n### **5. The "Answer" You Choose**\nMany thinkers (like Douglas Adams humorously) suggest that the question itself is more important than any answer. **You get to define meaning** based on:\n- What brings you joy and fulfillment?\n- What impact do you want to leave?\n- What values do you live by?\n\n### **A Simple (But Profound) Takeaway**\nLife has no single, prewritten meaning—but that’s freeing. **Meaning is a verb, not a noun.** It’s found in love, curiosity, creation, growth, and the connections we make. As Kurt Vonnegut put it: *"We are here on Earth to fart around. Don’t let anybody tell you any different."* (But also: *"Peculiar travel suggestions are dancing lessons from God."*)\n\nSo, what meaning will you create? 🌱', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 740, 'prompt_tokens': 18, 'total_tokens': 758, 'completion_tokens_details': None, 'prompt_tokens_details': None, 'cache_write_tokens': 0, 'cache_read_tokens': 0, 'input_tokens': 0, 'output_tokens': 0}, 'model_provider': 'openai', 'model_name': 'longcat-flash-chatai-api', 'system_fingerprint': None, 'id': 'df562d8682c14c158256e9843fb9d757', 'finish_reason': 'stop', 'logprobs': None}, id='lc_run--ee7dcacc-fe99-4844-a7f9-8b0e5227129b-0', usage_metadata={'input_tokens': 18, 'output_tokens': 740, 'total_tokens': 758, 'input_token_details': {}, 'output_token_details': {}})
使用init_chat_model
from langchain.chat_models import init_chat_model
model = init_chat_model(
model = "",
model_provider = ,
base_url = ,
api_key =
)
response = model.invoke("")
print(response)
模型调用
content='你好!我是美团研发的大模型,名字为 LongCat。我可以理解和生成自然语言,帮助用户解决问题。如果你需要帮助,欢迎随时向我提问。' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 32, 'prompt_tokens': 15, 'total_tokens': 47, 'completion_tokens_details': None, 'prompt_tokens_details': None, 'cache_write_tokens': 0, 'cache_read_tokens': 0, 'input_tokens': 0, 'output_tokens': 0}, 'model_provider': 'openai', 'model_name': 'longcat-flash-chatai-api', 'system_fingerprint': None, 'id': '7efdf02210bd46c6a08e4e9c8ca02a7c', 'finish_reason': 'stop', 'logprobs': None} id='lc_run--219672ee-6065-4bf7-ace7-80f2a978052d-0' usage_metadata={'input_tokens': 15, 'output_tokens': 32, 'total_tokens': 47, 'input_token_details': {}, 'output_token_details': {}}
Few-shot 提示
messages = [
SystemMessage("你叫小智,是一名助人为乐的助手。"),
HumanMessage("你好,我叫陈明,好久不见,请介绍下你自己。"),
AIMessage("你好呀!我是小智,一个乐于助人的智能助手。我的主要功能是回答问题、提供建议、协助解决问题,或者陪你聊天。无论是学习、工作、生活琐事,还是想找点有趣的话题,我都可以帮忙!如果有任何需要,随时告诉我哦~ 😊"),
HumanMessage("你好,请问你还记得我叫什么名字么?"),
]
response = model.invoke(messages)
调用stream()返回 AIMessageChunk
for msg in model.stream("简要介绍你自己"): # 每一个msg是一个消息块,可以相加 “消息块相加(chunk summation)”机制
print(msg.text, end='\n', flush=True)
你好
!
我是
美团研发
的大模型
,
名字为
LongCat
。我可以
理解和生成
自然语言
,帮助用户
解决问题。
如果你需要
帮助,
欢迎
随时向我
提问。
批量调用 batch
批量并行,独立请求
responses = model.batch([
"请介绍下你自己。",
"请问什么是机器学习?",
"你知道机器学习和深度学习区别么?"
])
for response in responses:
print(response)
结构化输出
使用pydantic 定义数据结构
from pydantic import BaseModel, Field
class Movie(BaseModel):
"""A movie with details."""
title: str = Field(..., description="The title of the movie")
year: int = Field(..., description="The year the movie was released")
director: str = Field(..., description="The director of the movie")
rating: float = Field(..., description="The movie's rating out of 10")
使用with_structured_output引导模型结构化输出
LongCat 不支持Langchain的with_structured_output自动json约束,需要用提示词进一步约束
model_with_structure = model.with_structured_output(Movie)
response = model_with_structure.invoke("Provide details about the movie Inception")
print(response)
构建模型的时候指定参数with_structured_output 的 include_raw
from pydantic import BaseModel,Field
class Movie(BaseModel):
title: str = Field(...,description="电影名称")
year: int = Field(...,description="上映年份")
rating: float = Field(...,description="评分")
model = init_chat_model(
model = os.getenv("LongCat_MODEL"),
api_key = os.getenv("LongCat_API_KEY"),
base_url = os.getenv("LongCat_BASE_URL"),
model_provider="openai"
)
model_with_schema = model.with_structured_output(Movie, include_raw = True)
response = model_with_schema.invoke("介绍电影《教父》的基本信息,只输出json格式数据")
print(response)
返回结果
{'raw': AIMessage(content='', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 35, 'prompt_tokens': 232, 'total_tokens': 267, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 192}, 'prompt_cache_hit_tokens': 192, 'prompt_cache_miss_tokens': 40}, 'model_provider': 'deepseek', 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_ffc7281d48_prod0820_fp8_kvcache', 'id': 'ba23a6bd-3204-44f0-9987-b7e9a9865378', 'finish_reason': 'tool_calls', 'logprobs': None}, id='lc_run--7d0538ae-3eec-4af7-8a31-566172cd28d4-0', tool_calls=[{'name': 'Movie', 'args': {'title': 'Inception', 'year': 2010, 'director': 'Christopher Nolan', 'rating': 8.8}, 'id': 'call_00_W5707pQrcI0iMZPXsd3AcPQB', 'type': 'tool_call'}], usage_metadata={'input_tokens': 232, 'output_tokens': 35, 'total_tokens': 267, 'input_token_details': {'cache_read': 192}, 'output_token_details': {}}),
'parsed': Movie(title='Inception', year=2010, director='Christopher Nolan', rating=8.8),
'parsing_error': None}
智能体构建
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
import os
from langchain_tavily import TavilySearch
from dotenv import load_dotenv
load_dotenv()
web_search_tool = TavilySearch(tavily_api_key=os.getenv("TAVILY_API_KEY"))
model = init_chat_model(
model = os.getenv("LongCat_MODEL"),
api_key = os.getenv("LongCat_API_KEY"),
base_url = os.getenv("LongCat_BASE_URL"),
model_provider = "openai",
)
agent = create_agent(
model = model,
tools = [web_search_tool],
system_prompt = "你是一个专业的搜索助手,能够帮助用户快速找到相关的信息。",
)
result = agent.invoke(
{
"messages": [
{"role": "user", "content": "查询2025年各个诺贝尔奖得主"}
]
}
)
# 这里需要注意invoke传入的参数 应该使用字典格式,包含 messages 键和 role / content 结构
print(result)
{'messages': [HumanMessage(content='查询2025年各个诺贝尔奖得主', additional_kwargs={}, response_metadata={}, id='46fe96ef-1666-4ea9-a5db-d0f7f10b3c1d'), AIMessage(content='', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 44, 'prompt_tokens': 1804, 'total_tokens': 1848, 'completion_tokens_details': None, 'prompt_tokens_details': None, 'cache_write_tokens': 0, 'cache_read_tokens': 0, 'input_tokens': 0, 'output_tokens': 0}, 'model_provider': 'openai', 'model_name': 'longcat-flash-chatai-api', 'system_fingerprint': None, 'id': '9bba0827cb1443eb9db1785ecef64112', 'finish_reason': 'tool_calls', 'logprobs': None}, id='lc_run--9362548b-cbf1-432d-a771-29c941a7534b-0', tool_calls=[{'name': 'tavily_search', 'args': {'query': '2025年诺贝尔奖得主名单', 'search_depth': 'advanced', 'time_range': 'year'}, 'id': '55951fbd-c583-48a8-be55-8d9ab53fe08a', 'type': 'tool_call'}], usage_metadata={'input_tokens': 1804, 'output_tokens': 44, 'total_tokens': 1848, 'input_token_details': {}, 'output_token_details': {}}), ToolMessage(content='{"query": "2025年诺贝尔奖得主名单", "follow_up_questions": null, "answer": null, "images": [], "results": [{"url": "https://www.takungpao.com/news/232111/2025/1014/1131389.html", "title": "2025年诺贝尔奖得奖名单 - 大公网", "content": "+ 服贸会\\n + /\\n + 东北亚\\n 更多\\n 收起\\n\\n首页 > 新闻 > 国际 > 正文\\n\\n## \ufeff2025年诺贝尔奖得奖名单\\n\\n2025-10-14 05:02:32大公报\\n\\n字号\\n: 放大\\n: 标准\\n\\n分享\\n\\n生理学或医学奖\\n\\n\u3000\u3000•美国分子生物学家布伦科、美国免疫学家拉姆斯德尔、日本免疫学家坂口志文\\n\\n\u3000\u3000物理学奖\\n\\n\u3000\u3000•英国物理学家克拉克、法国物理学家德沃雷、美国物理学家马蒂尼斯\\n\\n\u3000\u3000化学奖\\n\\n\u3000\u3000•日本化学家北川进、英国化学家罗布森、美籍约旦裔化学家亚吉\\n\\n\u3000\u3000文学奖\\n\\n\u3000\u3000•匈牙利作家克拉斯诺霍尔卡伊.拉斯洛\\n\\n\u3000\u3000和平奖\\n\\n\u3000\u3000•委内瑞拉反对派领导人马查多\\n\\n\u3000\u3000经济学奖\\n\\n\u3000\u3000•美以双重国籍经济学家莫基尔、法国经济学家阿吉翁、加拿大经济学家豪伊特\\n\\n### 点击排行", "score": 0.9353998, "raw_content": null}, {"url": "https://www.britannica.com/topic/2025-Nobel-Prize-Winners", "title": "2025 Nobel Prize Winners | Education, Birth Dates, & Facts | Britannica", "content": "The 2025 Nobel Prize for Physics was awarded to British physicist John Clarke, French physicist Michel H. Devoret, and American physicist John M. Martinis on October 7, 2025. They won for their work on enhancing the understanding of quantum mechanics in large-scale electrical systems, paving the way for developing advanced quantum technology such as quantum computing.\\n\\n## John Clarke [...] The 2025 Nobel Prize for Economics (the Sveriges Riksbank Prize in Economic Sciences in Memory of Alfred Nobel) was awarded to Israeli-American economic historian Joel Mokyr, French economist Philippe Aghion, and Canadian economist Peter Howitt on October 13, 2025 for their contributions in explaining innovation-driven economic growth. One half of the award went to Mokyr for the identification of the prerequisites for sustained growth through technological progress, and the other half was [...] The 2025 Nobel Prize for Physiology or Medicine was awarded to American biologists Mary E. Brunkow and Fred Ramsdell and Japanese biologist Shimon Sakaguchi by the Karolinska Institutet on October 6, 2025. They won for their work on the immune system, specifically regulatory T cells, which stop other T cells from attacking the body’s own cells.\\n\\n## Mary E. Brunkow", "score": 0.9305657, "raw_content": null}, {"url": "https://baike.baidu.com/item/2025%E5%B9%B4%E8%AF%BA%E8%B4%9D%E5%B0%94%E5%A5%96/66198359", "title": "2025年诺贝尔奖_百度百科", "content": "网页新闻贴吧知道网盘图片视频地图文库资讯采购百科\\n\\n帮助\\n\\n首页\\n\\n秒懂百科\\n\\n特色百科\\n\\n知识专题\\n\\n加入百科\\n\\n百科团队\\n\\n权威合作\\n\\n# 2025年诺贝尔奖\\n\\n播报讨论上传视频\\n\\n收藏\\n\\n查看我的收藏\\n\\n0有用+1\\n\\n2025年诺贝尔奖(Nobel Prize 2025)是由诺贝尔基金会主办的综合类奖项 。2025年10月6日至10月13日陆续公布获奖名单,12月8日举行诺贝尔奖音乐会,12月10日举行颁奖典礼 。\\n\\n2025年诺贝尔奖共设置6个奖项。各奖项分别由卡罗林斯卡学院的诺贝尔议会、瑞典皇家科学院、瑞典学院、挪威诺贝尔委员会进行评选 。最终,玛丽·E·布伦科、弗雷德·拉姆斯德尔和坂口志文获得诺贝尔生理学或医学奖 ,约翰·克拉克、麦克·H·德沃雷特、约翰·M·马蒂尼获得诺贝尔物理学奖 ,北川进、理查德·罗布森和奥马尔·M·亚吉获得诺贝尔化学奖 ,拉斯洛·卡撒兹纳霍凯获得诺贝尔文学奖 ,玛丽亚·科里纳·马查多获得诺贝尔和平奖 ,乔尔·莫基尔、菲利普·阿吉翁和彼得·豪伊特获得诺贝尔经济学奖 。\\n\\n中文名\\n: 2025年诺贝尔奖 [...] 2025年诺贝尔奖得主\\n\\n## 奖项之最\\n\\n播报\\n\\n编辑\\n\\n 玛丽亚·科里纳·马查多是委内瑞拉第一位获得诺贝尔和平奖的人 。\\n\\n 拉斯洛·卡撒兹纳霍凯是继2002年获奖的凯尔泰斯·伊姆雷之后,第一位获得诺贝尔文学奖的匈牙利人,也是历史上的第二位匈牙利诺贝尔奖得主 。\\n\\n## 颁奖典礼\\n\\n播报\\n\\n编辑\\n\\n| 颁发奖项 | 获奖者公布嘉宾 |\\n --- |\\n| 诺贝尔生理学或医学奖 | 诺贝尔大会秘书长Thomas Perlmann |\\n| 诺贝尔物理学奖 | 瑞典皇家科学院秘书长Hans Ellegren |\\n| 诺贝尔化学奖 | 瑞典皇家科学院秘书长Hans Ellegren |\\n| 诺贝尔文学奖 | 瑞典科学院常务秘书Mats Malm |\\n| 诺贝尔经济学奖 | 挪威诺贝尔委员会主席Jørgen Watne |\\n| 诺贝尔和平奖 | 瑞典皇家科学院秘书长Hans Ellegren |\\n\\n## 奖项评析\\n\\n播报\\n\\n编辑\\n\\n诺贝尔生理或医学奖 [...] | 奖项名称 | 获奖方 | 国家 | 获奖原因 |\\n --- --- |\\n| 诺贝尔生理学或医学奖 | 玛丽·布伦科 | 美国 | 在外周免疫耐受方面的发现 |\\n| 弗雷德·拉姆斯德尔 | 美国 |\\n| 坂口志文 | 日本 |\\n| 诺贝尔物理学奖 | 约翰·克拉克 | 英国 | 发现了电路中的宏观量子隧穿和能量量子化 |\\n| 麦克·H·德沃雷特 | 法国 |\\n| 约翰·M·马蒂尼斯 | 美国 |\\n| 诺贝尔化学奖 | 北川进 | 日本 | 开发金属有机框架 |\\n| 理查德·罗布森 | 英国 |\\n| 奥马尔·亚吉 | 美国 |\\n| 诺贝尔文学奖 | 拉斯洛·卡撒兹纳霍凯 | 匈牙利 | 他引人入胜且富有远见的作品,在世界末日的恐怖中,再次证明了艺术的力量 |\\n| 诺贝尔和平奖 | 玛丽亚·科里纳·马查多 | 委内瑞拉 | 表彰她为促进委内瑞拉人民的民主权利所做的不懈努力,以及她为实现从独裁到民主的公正与和平过渡而进行的斗争 |\\n| 诺贝尔经济学奖 | 乔尔·莫基尔 | 美国 | 对创新驱动型经济增长的阐释 |\\n| 菲利普·阿吉翁 | 法国 |", "score": 0.9205687, "raw_content": null}, {"url": "https://www.edu.cn/rd/special_topic/nobel/wl/202510/t20251009_2693267.shtml", "title": "2025年诺贝尔物理学奖揭晓! - 中国教育和科研计算机网", "content": "中国教育和科研计算机网 中国教育 高校科技 教育信息化 下一代互联网 CERNET 返回首页\\n\\nEDU首页 中国教育 高校科技 教育信息化 CERNET\\n\\n- 滚动 每日要闻\\n- 高校科研 成果 资讯\\n- 专家视点 人才 评论\\n- 科学探索 前沿 科普\\n- 学术会议 通知 新闻\\n- 专题\\n\\n首页 > 高校科技 > 专题报道 > 诺贝尔奖 > 物理学奖\\n\\n2025-10-09 诺贝尔奖委员会官网\\n\\n北京时间10月7日17时45分许,2025年诺贝尔物理学奖揭晓获奖名单。JohnClarke、Michel H.Devoret、John M.Martinis获奖,获奖理由是“在电路中发现宏观量子力学隧道效应与能量量子化现象”。奖金为1100万瑞典克朗。\\n\\n近5年诺贝尔物理学奖得主\\n\\n\u3000\u30002024年,诺贝尔物理学奖颁给约翰·霍普菲尔德(John J. Hopfield)、杰弗里·辛顿(Geoffrey E. Hinton),以表彰他们通过人工神经网络实现机器学习的基础性发现和发明。", "score": 0.91988057, "raw_content": null}, {"url": "https://www.stcn.com/article/detail/3368232.html", "title": "刚刚,诺贝尔奖揭晓! - 证券时报", "content": "当地时间10月6日,瑞典卡罗琳医学院宣布,将2025年诺贝尔生理学或医学奖授予科学家玛丽·布伦科(Mary E. Brunkow)、弗雷德·拉姆斯德尔(Fred Ramsdell)和坂口西蒙(Shimon Sakaguchi)。\\n\\n此前,出生于福建的华人科学家、德克萨斯大学西南医学中心教授陈志坚被业界视为今年生理学或医学奖的热门人选。\\n\\n9月25日,陈志坚刚刚荣获“引文桂冠奖生理学或医学奖”。因学术成就和贡献突出,陈志坚已先后获得“科学突破奖”“拉斯克奖”“引文桂冠奖”三大国际公认的“诺奖风向标”,离诺奖仅一步之遥。2013年,陈志坚团队在国际上首次发现了名为cGAS的酶,解开了DNA如何刺激免疫和炎症反应之谜,这也是一个困扰科学界长达百年的问题。就连陈志坚也曾感叹,“这个‘传感器’竟然是一种酶,真是令人惊讶。” [...] 首页\\n 快讯\\n 要闻\\n 股市\\n 新股\\n 信披+\\n 公司\\n 港美股\\n 数据\\n 基金\\n 金融\\n 视听\\n 评论\\n 专题\\n 产经\\n 创投\\n 科创板\\n 新三板\\n 投教\\n ESG\\n 滚动\\n\\n公众号 电子报 客户端\\n\\n您当前的位置:证券时报 > 要闻 > 正文\\n\\n来源:证券时报网2025-10-06 18:14\\n\\n分享\\n\\n刚刚,2025年首个诺贝尔奖揭晓!\\n\\n瑞典卡罗琳斯卡学院6日宣布,将2025年诺贝尔生理学或医学奖授予,玛丽·布伦科、弗雷德·拉姆斯德尔和坂口西蒙,以表彰其“在外周免疫耐受方面的发现”。\\n\\n随着诺贝尔生理学或医学奖的揭晓,2025年诺贝尔奖“开奖周”也正式拉开帷幕,其他五大奖项将逐次揭晓:\\n\\n物理学奖将于北京时间10月7日(星期二)17:45公布;\\n\\n化学奖将于北京时间10月8日(星期三)17:45揭晓;\\n\\n文学奖将于北京时间10月9日(星期四)19:00公布;\\n\\n和平奖将于北京时间10月10日(星期五)17:00公布;\\n\\n经济学奖将于北京时间10月13日(星期一)17:45公布。\\n\\n三人获奖", "score": 0.8896154, "raw_content": null}], "response_time": 1.72, "request_id": "50ceb202-e7b3-441f-83e1-a3c39aa77c42"}', name='tavily_search', id='500a3047-0222-47c0-ad9c-6de043fa30e3', tool_call_id='55951fbd-c583-48a8-be55-8d9ab53fe08a'), AIMessage(content='以下是2025年诺贝尔奖各奖项得主名单(综合权威来源整理):\n\n---\n\n### **诺贝尔生理学或医学奖**\n- **玛丽·E·布伦科(Mary E. Brunkow)**(美国) \n- **弗雷德·拉姆斯德尔(Fred Ramsdell)**(美国) \n- **坂口志文(Shimon Sakaguchi)**(日本) \n **获奖理由**:在外周免疫耐受方面的发现,特别是调节性T细胞(Treg)的研究。\n\n---\n\n### **诺贝尔物理学奖**\n- **约翰·克拉克(John Clarke)**(英国) \n- **米歇尔·H·德沃雷特(Michel H. Devoret)**(法国) \n- **约翰·M·马蒂尼斯(John M. Martinis)**(美国) \n **获奖理由**:在电路中发现宏观量子隧穿和能量量子化现象,推动量子计算发展。\n\n---\n\n### **诺贝尔化学奖**\n- **北川进(Susumu Kitagawa)**(日本) \n- **理查德·罗布森(Richard Robson)**(英国) \n- **奥马尔·M·亚吉(Omar M. Yaghi)**(美籍约旦裔) \n **获奖理由**:金属有机框架(MOFs)的开发与应用。\n\n---\n\n### **诺贝尔文学奖**\n- **拉斯洛·克拉斯纳霍凯(László Krasznahorkai)**(匈牙利) \n **获奖理由**:作品以“末日恐怖中的艺术力量”展现人类困境。\n\n---\n\n### **诺贝尔和平奖**\n- **玛丽亚·科里纳·马查多(María Corina Machado)**(委内瑞拉) \n **获奖理由**:为促进委内瑞拉民主权利及和平过渡的斗争。\n\n---\n\n### **诺贝尔经济学奖**\n- **乔尔·莫基尔(Joel Mokyr)**(美以双重国籍) \n- **菲利普·阿吉翁(Philippe Aghion)**(法国) \n- **彼得·豪伊特(Peter Howitt)**(加拿大) \n **获奖理由**:对创新驱动型经济增长理论的贡献。\n\n---\n\n**注**: \n1. 部分中文媒体对名字的翻译可能存在差异(如“坂口志文”或“坂口西蒙”)。 \n2. 奖项官方信息可参考[诺贝尔奖官网](https://www.nobelprize.org/)。 \n3. 马查多是委内瑞拉首位诺贝尔和平奖得主,克拉斯纳霍凯是匈牙利第二位文学奖得主。 \n\n如需进一步了解某位得主或奖项细节,可指定查询!', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 552, 'prompt_tokens': 4726, 'total_tokens': 5278, 'completion_tokens_details': None, 'prompt_tokens_details': None, 'cache_write_tokens': 0, 'cache_read_tokens': 0, 'input_tokens': 0, 'output_tokens': 0}, 'model_provider': 'openai', 'model_name': 'longcat-flash-chatai-api', 'system_fingerprint': None, 'id': '4efedc2d76964e3a8a1930f2a6a861f7', 'finish_reason': 'stop', 'logprobs': None}, id='lc_run--c65ee239-38d3-46e8-8458-886358f36ce5-0', usage_metadata={'input_tokens': 4726, 'output_tokens': 552, 'total_tokens': 5278, 'input_token_details': {}, 'output_token_details': {}})]}
result['messages'][-1].content
'以下是2025年诺贝尔奖各奖项得主名单(综合权威来源整理):\n\n---\n\n### **诺贝尔生理学或医学奖**\n- **玛丽·E·布伦科(Mary E. Brunkow)**(美国) \n- **弗雷德·拉姆斯德尔(Fred Ramsdell)**(美国) \n- **坂口志文(Shimon Sakaguchi)**(日本) \n **获奖理由**:在外周免疫耐受方面的发现,特别是调节性T细胞(Treg)的研究。\n\n---\n\n### **诺贝尔物理学奖**\n- **约翰·克拉克(John Clarke)**(英国) \n- **米歇尔·H·德沃雷特(Michel H. Devoret)**(法国) \n- **约翰·M·马蒂尼斯(John M. Martinis)**(美国) \n **获奖理由**:在电路中发现宏观量子隧穿和能量量子化现象,推动量子计算发展。\n\n---\n\n### **诺贝尔化学奖**\n- **北川进(Susumu Kitagawa)**(日本) \n- **理查德·罗布森(Richard Robson)**(英国) \n- **奥马尔·M·亚吉(Omar M. Yaghi)**(美籍约旦裔) \n **获奖理由**:金属有机框架(MOFs)的开发与应用。\n\n---\n\n### **诺贝尔文学奖**\n- **拉斯洛·克拉斯纳霍凯(László Krasznahorkai)**(匈牙利) \n **获奖理由**:作品以“末日恐怖中的艺术力量”展现人类困境。\n\n---\n\n### **诺贝尔和平奖**\n- **玛丽亚·科里纳·马查多(María Corina Machado)**(委内瑞拉) \n **获奖理由**:为促进委内瑞拉民主权利及和平过渡的斗争。\n\n---\n\n### **诺贝尔经济学奖**\n- **乔尔·莫基尔(Joel Mokyr)**(美以双重国籍) \n- **菲利普·阿吉翁(Philippe Aghion)**(法国) \n- **彼得·豪伊特(Peter Howitt)**(加拿大) \n **获奖理由**:对创新驱动型经济增长理论的贡献。\n\n---\n\n**注**: \n1. 部分中文媒体对名字的翻译可能存在差异(如“坂口志文”或“坂口西蒙”)。 \n2. 奖项官方信息可参考[诺贝尔奖官网](https://www.nobelprize.org/)。 \n3. 马查多是委内瑞拉首位诺贝尔和平奖得主,克拉斯纳霍凯是匈牙利第二位文学奖得主。 \n\n如需进一步了解某位得主或奖项细节,可指定查询!'
自定义Langchain的tool
需要有字符串解释函数的作用参数返回值
import os
from dotenv import load_dotenv
from langchain.tools import tool
load_dotenv()
import requests, json
@tool
def get_weather(city):
"""
查询天气函数
:param city: 必要参数,字符串类型,用于表示查询天气的具体城市名称,\
注意,中国的城市需要用对应城市的英文名称代替,例如如果需要查询北京市天气,则loc参数需要输入'Beijing';
:return:OpenWeather API查询即时天气的结果,具体URL请求地址为:https://api.openweathermap.org/data/2.5/weather\
返回结果对象类型为解析之后的JSON格式对象,并用字符串形式进行表示,其中包含了全部重要的天气信息
"""
url = f"http://api.openweathermap.org/data/2.5/weather"
params = {
"q": city,
"appid": os.getenv("OPENWEATHERMAP_API_KEY"),
"units": "metric",
"lang": "zh_cn",
}
response = requests.get(url, params=params)
return json.dumps(response.json())
from langchain.chat_models import init_chat_model
from langchain.agents import create_agent
model = init_chat_model(
model = os.getenv("ARK_MODEL"),
api_key = os.getenv("ARK_API_KEY"),
base_url = os.getenv("ARK_BASE_URL"),
model_provider = "openai",
)
agent = create_agent(
model = model,
tools = [get_weather],
system_prompt = "你是一名多才多艺的智能助手,可以调用工具帮助用户解决问题。",
)
response = agent.invoke(
{
"message": [
{
"role": "user",
"content": "北京天气"
}
]
}
)
response["messages"][-1].content
response
{'messages': [AIMessage(content='', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 275, 'prompt_tokens': 508, 'total_tokens': 783, 'completion_tokens_details': {'accepted_prediction_tokens': None, 'audio_tokens': None, 'reasoning_tokens': 248, 'rejected_prediction_tokens': None}, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}}, 'model_provider': 'openai', 'model_name': 'doubao-seed-1-6-251015', 'system_fingerprint': None, 'id': '021763443209738f20543282e4f4ee32c7da5b3f80f7d14ea5d2d', 'service_tier': 'default', 'finish_reason': 'tool_calls', 'logprobs': None}, id='lc_run--3fa248cc-5abe-47e4-96f9-9ed4dc9711d7-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'Beijing'}, 'id': 'call_ratzfwcics3f2eiwl79ozrgm', 'type': 'tool_call'}], usage_metadata={'input_tokens': 508, 'output_tokens': 275, 'total_tokens': 783, 'input_token_details': {'cache_read': 0}, 'output_token_details': {'reasoning': 248}}),
ToolMessage(content='{"coord": {"lon": 116.3972, "lat": 39.9075}, "weather": [{"id": 802, "main": "Clouds", "description": "\\u591a\\u4e91", "icon": "03d"}], "base": "stations", "main": {"temp": 9.94, "feels_like": 7.5, "temp_min": 9.94, "temp_max": 9.94, "pressure": 1031, "humidity": 14, "sea_level": 1031, "grnd_level": 1026}, "visibility": 10000, "wind": {"speed": 5.05, "deg": 333, "gust": 8.26}, "clouds": {"all": 28}, "dt": 1763443049, "sys": {"type": 1, "id": 9609, "country": "CN", "sunrise": 1763420554, "sunset": 1763456206}, "timezone": 28800, "id": 1816670, "name": "Beijing", "cod": 200}', name='get_weather', id='fcfe9825-06d0-4305-8c4e-ddb3e426030d', tool_call_id='call_ratzfwcics3f2eiwl79ozrgm'),
AIMessage(content='北京当前天气为多云,气温约9.9℃,体感温度7.5℃,湿度14%,风速5.05m/s。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 249, 'prompt_tokens': 870, 'total_tokens': 1119, 'completion_tokens_details': {'accepted_prediction_tokens': None, 'audio_tokens': None, 'reasoning_tokens': 216, 'rejected_prediction_tokens': None}, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}}, 'model_provider': 'openai', 'model_name': 'doubao-seed-1-6-251015', 'system_fingerprint': None, 'id': '021763443216202f20543282e4f4ee32c7da5b3f80f7d141dcf06', 'service_tier': 'default', 'finish_reason': 'stop', 'logprobs': None}, id='lc_run--1b83537f-12fc-47d3-87bc-1b5644dff7e1-0', usage_metadata={'input_tokens': 870, 'output_tokens': 249, 'total_tokens': 1119, 'input_token_details': {'cache_read': 0}, 'output_token_details': {'reasoning': 216}})]}
3110

被折叠的 条评论
为什么被折叠?



