Skip to content

Commit

Permalink
Add C7-5 C7-6 notebook
Browse files Browse the repository at this point in the history
  • Loading branch information
AXYZdong committed Aug 29, 2024
1 parent 4ea15c5 commit 4eb64b2
Show file tree
Hide file tree
Showing 3 changed files with 321 additions and 1 deletion.
2 changes: 1 addition & 1 deletion docs/_sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* 第 5 章 Ollama 在 LangChain 中的使用
* [5.1 在 Python 中的集成](C5/1.%20Ollama%20在%20LangChain%20中的使用%20-%20Python%20集成.md)
* [5.2 在 JavaScript 中的集成](C5/2.%20Ollama%20在%20LangChain%20中的使用%20-%20JavaScript%20集成.md)
* 第 6 章 Ollama可视化界面部署
* 第 6 章 Ollama 可视化界面部署
* [6.1 使用 FastAPI 部署 Ollama 可视化对话界面](C6/1.%20使用%20FastAPI%20部署%20Ollama%20可视化对话界面.md)
* [6.2 使用 WebUI 部署 Ollama 可视化对话界面](C6/2.%20使用%20WebUI%20部署%20Ollama%20可视化对话界面.md)
* 第 7 章 应用案例
Expand Down
159 changes: 159 additions & 0 deletions notebook/C7/LangChain_Agent/使用LangChain实现本地Agent.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
{
"cells": [
{
"cell_type": "code",
"id": "initial_id",
"metadata": {
"collapsed": true,
"ExecuteTime": {
"end_time": "2024-08-06T09:04:06.202874Z",
"start_time": "2024-08-06T09:04:05.436564Z"
}
},
"source": [
"from langchain_core.tools import tool \n",
"from langchain.pydantic_v1 import BaseModel, Field\n",
"from langchain_core.tools import render_text_description\n",
"from langchain.agents import AgentExecutor, create_react_agent\n",
"from langchain import hub\n",
"from langchain_community.chat_models import ChatOllama\n",
"\n",
"# ============================================================\n",
"# 自定义工具\n",
"# ============================================================\n",
"class SearchInput(BaseModel):\n",
" location: str = Field(description=\"location to search for\") # 定义一个 Pydantic 模型,用于描述输入模式,并提供描述信息\n",
"\n",
"@tool(args_schema=SearchInput)\n",
"def weather_forecast(location: str):\n",
" \"\"\"天气预报工具。\"\"\"\n",
" print(f\"Weather for {location}\") # 打印要预报天气的位置\n",
" return f\"A dummy forecast for {location}.\" # 返回给定位置的虚拟天气预报"
],
"outputs": [],
"execution_count": 1
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2024-08-06T09:04:12.527130Z",
"start_time": "2024-08-06T09:04:06.202874Z"
}
},
"cell_type": "code",
"source": [
"# 测试不加工具\n",
"llm = ChatOllama(model=\"gemma:2b\") # 初始化 ChatOllama 模型,使用 \"gemma:2b\"\n",
"llm.invoke(\"What is the weather in Paris?\").content "
],
"id": "73a424092ac0a89a",
"outputs": [
{
"data": {
"text/plain": [
"'I do not have access to real-time information and cannot provide weather updates. For the most up-to-date weather information, I recommend checking a weather app or website such as the National Weather Service (NWS) or the European Central Weather Agency (ECWA).'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"execution_count": 2
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2024-08-06T09:04:33.367487Z",
"start_time": "2024-08-06T09:04:12.527130Z"
}
},
"cell_type": "code",
"source": [
"# 测试使用工具\n",
"tools = [weather_forecast] # 使用 weather_forecast 工具\n",
"prompt = hub.pull(\"hwchase17/react-json\") # 从 hub 拉取特定提示\n",
"prompt = prompt.partial(\n",
" tools=render_text_description(tools), # 为提示呈现工具的文本描述\n",
" tool_names=\", \".join([t.name for t in tools]), # 将工具名称连接成一个以逗号分隔的字符串\n",
")\n",
"agent = create_react_agent(llm, tools, prompt) # 使用 llm、工具和自定义提示创建代理\n",
"agent_executor = AgentExecutor(agent=agent, tools=tools, handle_parsing_errors=True, verbose=False, format=\"json\") # 使用指定参数初始化 AgentExecutor\n",
"print(agent_executor.invoke({\"input\":\"What is the weather in Paris?\"})) # 使用测试输入调用代理并打印结果"
],
"id": "d8ba4157f75da004",
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'input': 'What is the weather in Paris?', 'output': '** 68.2°F (20.1°C) with a 60% chance of rain'}\n"
]
}
],
"execution_count": 3
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2024-08-06T09:04:50.480641Z",
"start_time": "2024-08-06T09:04:33.368490Z"
}
},
"cell_type": "code",
"source": [
"# 使用对话历史\n",
"# 拉去特定提示,注意此处使用的是 react-chat\n",
"prompt = hub.pull(\"hwchase17/react-chat\")\n",
"\n",
"# 构建 ReAct agent\n",
"agent_history = create_react_agent(llm, tools, prompt)\n",
"agent_executor = AgentExecutor(agent=agent_history, tools=tools, verbose=False)\n",
"\n",
"agent_executor.invoke(\n",
" {\n",
" \"input\": \"what's my name? Only use a tool if needed, otherwise respond with Final Answer\",\n",
" \"chat_history\": \"Human: Hi! My name is Bob\\nAI: Hello Bob! Nice to meet you\",\n",
" }\n",
")"
],
"id": "ddc0579b230549aa",
"outputs": [
{
"data": {
"text/plain": [
"{'input': \"what's my name? Only use a tool if needed, otherwise respond with Final Answer\",\n",
" 'chat_history': 'Human: Hi! My name is Bob\\nAI: Hello Bob! Nice to meet you',\n",
" 'output': '** Your name is Bob.'}"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"execution_count": 4
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
161 changes: 161 additions & 0 deletions notebook/C7/LlamaIndex_Agent/使用LlamaIndex实现本地Agent.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
{
"cells": [
{
"metadata": {
"ExecuteTime": {
"end_time": "2024-08-14T08:42:27.374624Z",
"start_time": "2024-08-14T08:42:25.030424Z"
}
},
"cell_type": "code",
"source": [
"from llama_index.core.tools import FunctionTool\n",
"from llama_index.core.agent import ReActAgent\n",
"from llama_index.llms.ollama import Ollama\n",
"\n",
"# Define tools\n",
"def multiply(a: float, b: float) -> float:\n",
" \"\"\"Multiply two integers and return the result integer\"\"\"\n",
" return a * b\n",
"\n",
"# Create FunctionTool instances\n",
"multiply_tool = FunctionTool.from_defaults(\n",
" fn=multiply,\n",
" name=\"MultiplyTool\",\n",
" description=\"A tool that multiplies two floats.\",\n",
" return_direct=True\n",
")"
],
"id": "initial_id",
"outputs": [],
"execution_count": 1
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2024-08-14T08:42:27.565183Z",
"start_time": "2024-08-14T08:42:27.375688Z"
}
},
"cell_type": "code",
"source": [
"# Initialize LLM\n",
"llm = Ollama(model=\"qwen2:0.5b\", request_timeout=360.0)\n",
"\n",
"# Initialize ReAct agent with tools\n",
"agent = ReActAgent.from_tools([multiply_tool], llm=llm, verbose=True)"
],
"id": "d46caad79b3f9a04",
"outputs": [],
"execution_count": 2
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2024-08-14T08:42:33.309189Z",
"start_time": "2024-08-14T08:42:27.565984Z"
}
},
"cell_type": "code",
"source": [
"# direct response\n",
"res_llm = llm.complete(\"What is 2.3 × 4.8 ? Calculate step by step\")\n",
"print(res_llm)"
],
"id": "29f3c21096d8331c",
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"To calculate \\( 2.3 \\times 4.8 \\), you can follow these steps:\n",
"\n",
"1. **Perform the multiplication:** When multiplying decimals, simply multiply the numerators (the top numbers) to get the numerator of the product.\n",
"\n",
" \\[\n",
" 2.3 \\times 4.8 = 9.44\n",
" \\]\n",
"\n",
"2. **Multiply the denominators (bottom numbers)**\n",
"\n",
" The denominator of \\(4.8\\) is not affected by the multiplication because it does not contain a factor that can affect its value or determine the result.\n",
"\n",
"3. **Calculate the product** \n",
" \n",
" Since there are no common factors between the numerator and the denominator, the calculation is:\n",
"\n",
" \\[\n",
" 9.44 = 2.3 \\times 2.3\n",
" \\]\n",
"\n",
" This multiplication does not give you a new number because \\(2.3\\) and \\(2.3\\) are already multiplied to get 5.6.\n",
"\n",
"So, \\(2.3 \\times 4.8 = 9.44\\).\n"
]
}
],
"execution_count": 3
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2024-08-14T08:42:37.068830Z",
"start_time": "2024-08-14T08:42:33.309189Z"
}
},
"cell_type": "code",
"source": [
"# use agent\n",
"response = agent.chat(\"What is 2.3 × 4.8 ? Calculate step by step\")\n",
"response.response"
],
"id": "73a424092ac0a89a",
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"> Running step 9227846e-d630-4ce2-a760-c8e90366dc6c. Step input: What is 2.3 × 4.8 ? Calculate step by step\n",
"\u001B[1;3;38;5;200mThought: The task is asking to multiply two numbers, 2.3 and 4.8, then to calculate this multiplication step by step.\n",
"Action: MultiplyTool\n",
"Action Input: {'a': 2.3, 'b': 4.8}\n",
"\u001B[0m\u001B[1;3;34mObservation: 11.04\n",
"\u001B[0m"
]
},
{
"data": {
"text/plain": [
"'11.04'"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"execution_count": 4
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

0 comments on commit 4eb64b2

Please sign in to comment.