From 46694bfb5b16f0496f9191b8214ca33385374d4b Mon Sep 17 00:00:00 2001 From: kexsh <769014005@qq.com> Date: Wed, 27 Aug 2025 23:03:35 +0800 Subject: [PATCH] =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E4=BB=A3=E7=90=86=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- knightutils/utils/__init__.py | 0 knightutils/utils/proxy_example.py | 142 ++++++++++++++++++++++++++ knightutils/utils/set_proxy.py | 103 +++++++++++++++++++ test/llamaindex/prompt.markdown | 51 +++++++++ test/llamaindex/test_20250826_1.ipynb | 39 +++++-- 5 files changed, 329 insertions(+), 6 deletions(-) create mode 100644 knightutils/utils/__init__.py create mode 100644 knightutils/utils/proxy_example.py create mode 100644 knightutils/utils/set_proxy.py create mode 100644 test/llamaindex/prompt.markdown diff --git a/knightutils/utils/__init__.py b/knightutils/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/knightutils/utils/proxy_example.py b/knightutils/utils/proxy_example.py new file mode 100644 index 0000000..97dbb01 --- /dev/null +++ b/knightutils/utils/proxy_example.py @@ -0,0 +1,142 @@ +""" +Python中设置代理的完整示例 +""" + +import os +import requests +import urllib.request +from urllib.parse import urlparse + + +def set_global_proxy(proxy_url): + """ + 为整个Python进程设置全局代理 + + Args: + proxy_url (str): 代理地址,例如 "http://proxy.example.com:8080" + 或 "socks5://127.0.0.1:1080" + """ + # 解析代理URL + parsed = urlparse(proxy_url) + proxy_address = f"{parsed.scheme}://{parsed.hostname}:{parsed.port}" + + # 设置环境变量(影响urllib、requests等库) + os.environ['http_proxy'] = proxy_address + os.environ['https_proxy'] = proxy_address + + # 有些库可能使用大写环境变量 + os.environ['HTTP_PROXY'] = proxy_address + os.environ['HTTPS_PROXY'] = proxy_address + + print(f"已设置全局代理: {proxy_address}") + + +def set_requests_proxy(proxy_url, username=None, password=None): + """ + 仅为requests库设置代理 + + Args: + proxy_url (str): 代理地址 + username (str, optional): 代理用户名 + password (str, optional): 代理密码 + + Returns: + dict: 可直接用于requests的代理字典 + """ + if username and password: + # 添加认证信息 + parsed = urlparse(proxy_url) + proxy_with_auth = f"{parsed.scheme}://{username}:{password}@{parsed.hostname}:{parsed.port}" + proxies = { + 'http': proxy_with_auth, + 'https': proxy_with_auth + } + else: + proxies = { + 'http': proxy_url, + 'https': proxy_url + } + + print(f"已为requests设置代理: {proxy_url}") + return proxies + + +def test_proxy_connection(test_url="https://httpbin.org/ip", proxies=None): + """ + 测试代理连接 + + Args: + test_url (str): 测试URL + proxies (dict, optional): 代理设置 + """ + try: + if proxies: + response = requests.get(test_url, proxies=proxies, timeout=10) + else: + response = requests.get(test_url, timeout=10) + + print(f"代理测试成功,IP信息: {response.json()}") + return True + except Exception as e: + print(f"代理测试失败: {e}") + return False + + +def clear_proxy(): + """ + 清除代理设置 + """ + for var in ['http_proxy', 'https_proxy', 'HTTP_PROXY', 'HTTPS_PROXY']: + if var in os.environ: + del os.environ[var] + + print("已清除代理设置") + + +def example_with_requests(): + """ + 使用requests库通过代理访问网络的示例 + """ + print("\n=== Requests代理示例 ===") + + # 不使用代理 + print("不使用代理:") + test_proxy_connection() + + # 使用代理(示例地址,请替换为实际代理地址) + print("\n使用代理:") + proxies = set_requests_proxy("http://proxy.example.com:8080") + # test_proxy_connection(proxies=proxies) # 取消注释并替换为实际代理地址进行测试 + + +def example_with_global_proxy(): + """ + 设置全局代理的示例 + """ + print("\n=== 全局代理示例 ===") + + # 设置全局代理 + set_global_proxy("http://proxy.example.com:8080") + + # 测试连接 + test_proxy_connection() + + # 清除代理 + clear_proxy() + + +if __name__ == "__main__": + print("Python代理设置完整示例") + print("=" * 40) + + # 示例1: 使用requests设置代理 + example_with_requests() + + # 示例2: 设置全局代理 + example_with_global_proxy() + + print("\n代理设置说明:") + print("1. 环境变量方法影响整个Python进程") + print("2. requests代理方法仅影响使用requests的请求") + print("3. 实际使用时请替换示例代理地址为真实地址") + print("4. SOCKS代理需要安装: pip install requests[socks]") \ No newline at end of file diff --git a/knightutils/utils/set_proxy.py b/knightutils/utils/set_proxy.py new file mode 100644 index 0000000..e9abf02 --- /dev/null +++ b/knightutils/utils/set_proxy.py @@ -0,0 +1,103 @@ +""" +演示在Python中设置代理的几种方法 +""" + +import os +import requests +from urllib.request import ProxyHandler, build_opener + +fiddler_proxy = 'http://localhost:8866' +fiddlers_proxy = 'http://localhost:8866' + +proxy = fiddler_proxy +proxys = fiddlers_proxy + + +def set_proxy_with_os(): + """ + 方法1: 使用环境变量设置代理 + 这种方法会影响整个Python进程的网络请求 + """ + # 设置HTTP代理 + os.environ['http_proxy'] = proxy + os.environ['https_proxy'] = proxys + + # 如果需要身份验证 + # os.environ['http_proxy'] = 'http://username:password@proxy.example.com:8080' + # os.environ['https_proxy'] = 'http://username:password@proxy.example.com:8080' + + print("已通过环境变量设置代理") + + +def set_proxy_with_requests(): + """ + 方法2: 使用requests库单独设置代理 + 这种方法只影响使用requests的请求 + """ + proxies = { + 'http': proxy, + 'https': proxys + } + + # 如果需要身份验证 + # proxies = { + # 'http': 'http://username:password@proxy.example.com:8080', + # 'https': 'http://username:password@proxy.example.com:8080' + # } + + try: + response = requests.get('https://httpbin.org/ip', proxies=proxies, timeout=10) + print(f"通过代理访问的结果: {response.json()}") + except Exception as e: + print(f"使用requests通过代理访问出错: {e}") + + +def set_proxy_with_urllib(): + """ + 方法3: 使用urllib设置代理 + """ + proxy_handler = ProxyHandler({ + 'http': proxy, + 'https': proxys + }) + + opener = build_opener(proxy_handler) + + try: + response = opener.open('https://httpbin.org/ip', timeout=10) + print(f"通过urllib代理访问的结果: {response.read().decode()}") + except Exception as e: + print(f"使用urllib通过代理访问出错: {e}") + + +def unset_proxy(): + """ + 取消代理设置 + """ + if 'http_proxy' in os.environ: + del os.environ['http_proxy'] + if 'https_proxy' in os.environ: + del os.environ['https_proxy'] + if 'HTTP_PROXY' in os.environ: + del os.environ['HTTP_PROXY'] + if 'HTTPS_PROXY' in os.environ: + del os.environ['HTTPS_PROXY'] + + print("已取消代理设置") + + +if __name__ == "__main__": + print("Python代理设置演示") + print("=" * 30) + + # 演示设置代理 + set_proxy_with_os() + + # 演示使用requests通过代理访问 + set_proxy_with_requests() + + # 演示使用urllib通过代理访问 + set_proxy_with_urllib() + + # 取消代理设置 + unset_proxy() \ No newline at end of file diff --git a/test/llamaindex/prompt.markdown b/test/llamaindex/prompt.markdown new file mode 100644 index 0000000..fcef553 --- /dev/null +++ b/test/llamaindex/prompt.markdown @@ -0,0 +1,51 @@ +You are designed to help with a variety of tasks, from answering questions to providing summaries to other types of analyses. +## Tools + +You have access to a wide variety of tools. You are responsible for using the tools in any sequence you deem appropriate to complete the task at hand. +This may require breaking the task into subtasks and using different tools to complete each subtask. + +You have access to the following tools: +> Tool Name: multiply +Tool Description: multiply(a: float, b: float) -> float +Useful for multiplying two numbers. +Tool Args: {\"type\": \"object\", \"properties\": {\"a\": {\"title\": \"A\", \"type\": \"number\"}, \"b\": {\"title\": \"B\", \"type\": \"number\"}}, \"required\": [\"a\", \"b\"]} + + + +## Output Format + +Please answer in the same language as the question and use the following format: + +``` +Thought: The current language of the user is: (user's language). I need to use a tool to help me answer the question. +Action: tool name (one of multiply) if using a tool. +Action Input: the input to the tool, in a JSON format representing the kwargs (e.g. {\"input\": \"hello world\", \"num_beams\": 5}) +``` + +Please ALWAYS start with a Thought. + +NEVER surround your response with markdown code markers. You may use code markers within your response if you need to. + +Please use a valid JSON format for the Action Input. Do NOT do this {'input': 'hello world', 'num_beams': 5}. + +If this format is used, the user will respond in the following format: + +``` +Observation: tool response +``` + +You should keep repeating the above format till you have enough information to answer the question without using any more tools. At that point, you MUST respond in the one of the following two formats: + +``` +Thought: I can answer without using any more tools. I'll use the user's language to answer +Answer: [your answer here (In the same language as the user's question)] +``` + +``` +Thought: I cannot answer the question with the provided tools. +Answer: [your answer here (In the same language as the user's question)] +``` + +## Current Conversation + +Below is the current conversation consisting of interleaving human and assistant messages. \ No newline at end of file diff --git a/test/llamaindex/test_20250826_1.ipynb b/test/llamaindex/test_20250826_1.ipynb index 6bc8a9e..cbc5c7c 100644 --- a/test/llamaindex/test_20250826_1.ipynb +++ b/test/llamaindex/test_20250826_1.ipynb @@ -1,31 +1,58 @@ { "cells": [ { - "metadata": {}, - "cell_type": "raw", + "metadata": { + "ExecuteTime": { + "end_time": "2025-08-27T14:50:29.709398Z", + "start_time": "2025-08-27T14:50:28.732112Z" + } + }, + "cell_type": "code", "source": [ + "import os\n", + "\n", "from llama_index.llms.dashscope import DashScope\n", "from llama_index.llms.openai import OpenAI\n", "\n", + "os.environ[\"DASHSCOPE_API_KEY\"] = \"sk-e2a05bbcfac84e53b73f98acef15a009\"\n", "llm = DashScope(model_name=\"qwen-max\") # 设置检索引擎生成回答时调用的大模型。" ], - "id": "a5d3b9e1d4e6588f" + "id": "2eeef59eecfab41a", + "outputs": [], + "execution_count": 1 }, { "cell_type": "code", "id": "initial_id", "metadata": { "collapsed": true, - "jupyter": { - "is_executing": true + "ExecuteTime": { + "end_time": "2025-08-27T14:50:42.901841Z", + "start_time": "2025-08-27T14:50:31.035200Z" } }, "source": [ "response = llm.complete(\"William Shakespeare is \")\n", "print(response)" ], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "William Shakespeare (1564-1616) is widely regarded as one of the greatest writers in the English language and one of the world's pre-eminent dramatists. He is often called England's national poet and the \"Bard of Avon.\" His works, including 39 plays, 154 sonnets, and two long narrative poems, have been translated into every major living language and are performed more often than those of any other playwright. Some of his most famous plays include \"Romeo and Juliet,\" \"Hamlet,\" \"Macbeth,\" \"Othello,\" and \"King Lear.\" Shakespeare's influence extends from theater and literature to film, popular culture, and the English language itself, with many phrases and expressions from his works still in use today.\n" + ] + } + ], + "execution_count": 2 + }, + { + "metadata": {}, + "cell_type": "code", "outputs": [], - "execution_count": null + "execution_count": null, + "source": "", + "id": "5e8170348d3bad72" } ], "metadata": {