{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "b1f2ff89", "metadata": {}, "outputs": [], "source": [ "## 准备部分\n", "# 指定Embed对象\n", "embed_object = \"oracle-scm-planning\"\n", "# 指定用户问题\n", "query_text = \"How AI can help SCM planning?\"" ] }, { "cell_type": "code", "execution_count": 2, "id": "4b9d9fa0-1c73-4cef-abc4-397458215159", "metadata": {}, "outputs": [], "source": [ "# 导入必要的包\n", "import time\n", "import os\n", "import sys\n", "import json\n", "import requests\n", "from chromadb import Client\n", "\n", "# 获取当前脚本的目录\n", "current_dir = os.getcwd()\n", "\n", "# 读取设定文件\n", "config_file_path = os.path.join(current_dir, \"..\", \"setup\", \"config_embed.json\")\n", "\n", "# 读取配置项目\n", "try:\n", " with open(config_file_path, \"r\", encoding=\"utf-8\") as f:\n", " dict_config = json.load(f)\n", " # 读取通用项目\n", " API_URL = dict_config[\"API_URL\"]\n", " cohere_access_token = dict_config[\"cohere_access_token\"]\n", " custom_proxies = dict_config[\"custom_proxies\"]\n", " list_chroma_dir = dict_config[\"list_chroma_dir\"]\n", " list_embed_file_path = dict_config[\"list_embed_file_path\"]\n", " # 读取Embed对象项目\n", " model_name = dict_config[\"docs\"][embed_object][\"model_name\"]\n", " embed_file_name = dict_config[\"docs\"][embed_object][\"file_name\"]\n", " split_chunk_size = dict_config[\"docs\"][embed_object][\"split_chunk_size\"]\n", " split_overlap = dict_config[\"docs\"][embed_object][\"split_overlap\"]\n", " model_batch_size = dict_config[\"docs\"][embed_object][\"model_batch_size\"]\n", " collection_ids_prefix = dict_config[\"docs\"][embed_object][\"collection_ids_prefix\"]\n", " embed_collection_name = dict_config[\"docs\"][embed_object][\"collection_name\"]\n", "except Exception as e:\n", " print(\"配置文件读取失败\", e)\n", " sys.exit(\"Stop processing\")\n", "\n", "# 回退到上级目录并构建相对路径\n", "chroma_dir = os.path.join(current_dir, *list_chroma_dir)\n", "embed_file_path = os.path.join(current_dir, *list_embed_file_path, embed_file_name)" ] }, { "cell_type": "code", "execution_count": 3, "id": "630b5215-b3ad-43e6-8f48-83b78abf9c10", "metadata": {}, "outputs": [], "source": [ "import chromadb\n", "\n", "# 初始化 Chroma 客户端,指定之前的数据存储目录\n", "client = chromadb.PersistentClient(path=chroma_dir)\n", "\n", "# 获取 \"document_embeddings\" 集合\n", "collection = client.get_collection(embed_collection_name)" ] }, { "cell_type": "code", "execution_count": 4, "id": "953b58a8-3c70-4774-ba91-100cfd744337", "metadata": {}, "outputs": [], "source": [ "# 执行嵌入查询\n", "def get_embeddings(texts: list):\n", "\n", " retry_cnt = 0\n", " \n", " while True:\n", " try:\n", " response = requests.post(\n", " API_URL,\n", " proxies=custom_proxies,\n", " timeout=(60, 6),\n", " headers={\"Authorization\": \"Bearer {0}\".format(cohere_access_token)},\n", " json={\n", " \"model\": model_name,\n", " \"texts\": texts,\n", " \"input_type\": \"classification\",\n", " \"truncate\": \"NONE\"\n", " }\n", " )\n", " response.raise_for_status() # 确保请求成功\n", " break\n", " except Exception as e:\n", " time.sleep(1)\n", " print(\"error\", e)\n", " if retry_cnt > 5:\n", " return None\n", " retry_cnt += 1\n", "\n", " return response.json() # 返回嵌入向量" ] }, { "cell_type": "code", "execution_count": 5, "id": "667253d4-1a55-406a-b3d4-51f4b9957aca", "metadata": {}, "outputs": [], "source": [ "# 查询文本\n", "query_embedding = get_embeddings([query_text]) # 使用之前的 get_embedding 函数生成嵌入" ] }, { "cell_type": "code", "execution_count": 6, "id": "f3df429f-b4d6-4e66-803b-ae5e9ed95922", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Document: [\"real-time analytics that trackprogress towards your goals. You can see exceptions at a glance, review recommended actions, and use guidedresolution to make quicker, smarter planning decisions.As your team gains planning process knowledge, you can manage planning parameters by policy. Oracle SupplyChain Planning applies segmentation, demand priorities, sourcing rules, and attribute-based demand-supplymatching to perform planning tasks at a detailed level, letting you focus on the big picture.Similarly, built-in machine learning can identify cause and effect relationships, and prescribe actions for commonissues. Oracle's planning advisor predicts new item demand and potential supply disruptions, and alerts you tosystematic lead time deviations, stale parameter settings, and other issues. You can filter and prioritize advisormessages, review the predicted accuracy or confidence level of the recommendations, and hyperlink to theappropriate planning view in context to take action.Oracle’s\", \"Oracle Supply Chain PlanningToday's supply chains are more global, complex, and volatile than ever. To increase revenue and reduce costs, youneed future-ready supply chain planning that outpaces change and embeds intelligence in your planning process.Oracle Fusion Cloud Supply Chain Planning anticipates demand, manages supply, and aligns stakeholder and tradingpartner actions to your objectives. It’s also flexible, so you can adapt your planning processes as new challenges arise.Figure 1. Oracle Supply Chain Planning: a unified cloud platform to improve enterprise visibility, speed, and agilityPlan for the future of supply chain decision makingDigital supply chain planning enhances plan quality and increases planner productivity. Intelligent automation inOracle Supply Chain Planning makes digital planning intuitive, starting with embedded real-time analytics that trackprogress towards your goals. You can see exceptions at a glance, review recommended actions, and use guidedresolution\", \"component and the starting point for Oracle's Supply Chain CommandCenter solution. Planning insights and machine learning models drive manufacturing, inventory, transportation, andprocurement actions, with predefined use cases that detect, decide, and execute responses to issues across yoursupply chain network. You can visualize plan-to-actual performance, asses long term trends, and apply ad hocmachine learning to devise solutions. Deep links into Oracle Supply Chain Execution allow you to take action incontext.5 Solution Brief / Oracle Fusion Cloud Supply Chain PlanningCopyright © 2024, Oracle and/or its affiliates / PublicFigure 5. Visualize the impact of your planning decisions in Supply Chain Command CenterImprove profitability and accelerate supply chain innovationImplementing a world-class supply chain planning process doesn't have to be costly or disruptive. Cloud deploymentenhances availability and security. You get immediate access to planning innovations, feature\", 'the predicted accuracy or confidence level of the recommendations, and hyperlink to theappropriate planning view in context to take action.Oracle’s ultimate objective is to enable decision-centric planning that presents scenarios and alternatives with therange of expected outcomes for business issues that need planner input, complemented by fully autonomousplanning for those in which the system can determine the root cause, preferred solution alternative, and executionpath on its own.1 Solution Brief / Oracle Fusion Cloud Supply Chain PlanningCopyright © 2024, Oracle and/or its affiliates / PublicIntegrate business planning, tactical planning & executionOracle Fusion Cloud Sales and Operations Planning (S&OP) enables continuous and forward-looking integratedbusiness planning that profitably aligns product, demand, supply, workforce, and sales plans with operational andfinancial objectives. You can collaborate with colleagues within the application to arrive at a consolidated plan', 'changing market conditions.Oracle Demand Management captures and assimilates diverse demand signals on a continuous basis, prioritizingthose with the greatest causal impact to detect seasonality, trend, and sudden disruptive “regime changes” in demandpatterns. These can include customer-specific demand, sales forecasts, orders, shipments, weather, economic data,social sentiment, and other variables.The forecasting engine applies a proven ensemble of analytical and machine learning methods to assesses dataquality, select models, and evaluate the accuracy of results. Automated self-tuning reduces the need for extensivestaff expertise, while enhancing the timeliness, detail, and relevance of forecasting to the business. Feature-basedforecasting uses eXtreme Gradient Boosting to identify the item attributes, physical locations, and time varyingfeatures that drive demand.Figure 2. Planning Advisor forecasts new items by identifying key features that predict demand, along with their']\n", "Metadata: [{'chunk': 1}, {'chunk': 0}, {'chunk': 13}, {'chunk': 2}, {'chunk': 4}]\n" ] } ], "source": [ "# 查询集合,返回前5个匹配的文档\n", "results = collection.query(\n", " query_embeddings=query_embedding[\"embeddings\"],\n", " n_results=5\n", ")\n", "\n", "# 显示查询结果\n", "for doc, metadata in zip(results['documents'], results['metadatas']):\n", " print(\"Document:\", doc)\n", " print(\"Metadata:\", metadata)" ] }, { "cell_type": "code", "execution_count": 7, "id": "01ed14d1-71b5-42b3-82d6-47a053894a74", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[\n", " [\n", " \"real-time analytics that trackprogress towards your goals. You can see exceptions at a glance, review recommended actions, and use guidedresolution to make quicker, smarter planning decisions.As your team gains planning process knowledge, you can manage planning parameters by policy. Oracle SupplyChain Planning applies segmentation, demand priorities, sourcing rules, and attribute-based demand-supplymatching to perform planning tasks at a detailed level, letting you focus on the big picture.Similarly, built-in machine learning can identify cause and effect relationships, and prescribe actions for commonissues. Oracle's planning advisor predicts new item demand and potential supply disruptions, and alerts you tosystematic lead time deviations, stale parameter settings, and other issues. You can filter and prioritize advisormessages, review the predicted accuracy or confidence level of the recommendations, and hyperlink to theappropriate planning view in context to take action.Oracle’s\",\n", " \"Oracle Supply Chain PlanningToday's supply chains are more global, complex, and volatile than ever. To increase revenue and reduce costs, youneed future-ready supply chain planning that outpaces change and embeds intelligence in your planning process.Oracle Fusion Cloud Supply Chain Planning anticipates demand, manages supply, and aligns stakeholder and tradingpartner actions to your objectives. It’s also flexible, so you can adapt your planning processes as new challenges arise.Figure 1. Oracle Supply Chain Planning: a unified cloud platform to improve enterprise visibility, speed, and agilityPlan for the future of supply chain decision makingDigital supply chain planning enhances plan quality and increases planner productivity. Intelligent automation inOracle Supply Chain Planning makes digital planning intuitive, starting with embedded real-time analytics that trackprogress towards your goals. You can see exceptions at a glance, review recommended actions, and use guidedresolution\",\n", " \"component and the starting point for Oracle's Supply Chain CommandCenter solution. Planning insights and machine learning models drive manufacturing, inventory, transportation, andprocurement actions, with predefined use cases that detect, decide, and execute responses to issues across yoursupply chain network. You can visualize plan-to-actual performance, asses long term trends, and apply ad hocmachine learning to devise solutions. Deep links into Oracle Supply Chain Execution allow you to take action incontext.5 Solution Brief / Oracle Fusion Cloud Supply Chain PlanningCopyright © 2024, Oracle and/or its affiliates / PublicFigure 5. Visualize the impact of your planning decisions in Supply Chain Command CenterImprove profitability and accelerate supply chain innovationImplementing a world-class supply chain planning process doesn't have to be costly or disruptive. Cloud deploymentenhances availability and security. You get immediate access to planning innovations, feature\",\n", " \"the predicted accuracy or confidence level of the recommendations, and hyperlink to theappropriate planning view in context to take action.Oracle’s ultimate objective is to enable decision-centric planning that presents scenarios and alternatives with therange of expected outcomes for business issues that need planner input, complemented by fully autonomousplanning for those in which the system can determine the root cause, preferred solution alternative, and executionpath on its own.1 Solution Brief / Oracle Fusion Cloud Supply Chain PlanningCopyright © 2024, Oracle and/or its affiliates / PublicIntegrate business planning, tactical planning & executionOracle Fusion Cloud Sales and Operations Planning (S&OP) enables continuous and forward-looking integratedbusiness planning that profitably aligns product, demand, supply, workforce, and sales plans with operational andfinancial objectives. You can collaborate with colleagues within the application to arrive at a consolidated plan\",\n", " \"changing market conditions.Oracle Demand Management captures and assimilates diverse demand signals on a continuous basis, prioritizingthose with the greatest causal impact to detect seasonality, trend, and sudden disruptive “regime changes” in demandpatterns. These can include customer-specific demand, sales forecasts, orders, shipments, weather, economic data,social sentiment, and other variables.The forecasting engine applies a proven ensemble of analytical and machine learning methods to assesses dataquality, select models, and evaluate the accuracy of results. Automated self-tuning reduces the need for extensivestaff expertise, while enhancing the timeliness, detail, and relevance of forecasting to the business. Feature-basedforecasting uses eXtreme Gradient Boosting to identify the item attributes, physical locations, and time varyingfeatures that drive demand.Figure 2. Planning Advisor forecasts new items by identifying key features that predict demand, along with their\"\n", " ]\n", "]\n" ] } ], "source": [ "import json\n", "print(json.dumps(results[\"documents\"], indent=4, ensure_ascii=False))" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.3" } }, "nbformat": 4, "nbformat_minor": 5 }