阿里云上有很多的服务。在今天的文章中,我重点介绍如何创供我们使用的推理端点,连接器,并使用代码写入我们的数据。在进行下面的操作之前,建议观看视频:阿里云 Elasticsearch 开通试用到登陆 Kibana 教程。
我们可以使用阿里云提供的链接进入到试用页面:
如果你已经创建好了自己的 Elasticsearch 集群,那么再次点击那个链接,你就会看到上面的页面。点击上面的我的试用:
我们点击上面的控制台:
我们可以进行上面的测试。你也可以使用如下的命令来进行测试:
`curl -u elastic:<YourPassword> http://es-cn-rcn4v4kcy0001wg52.public.elasticsearch.aliyuncs.com:9200/`AI写代码
同样地,你需要配置 Kibana 的公网地址:
设置完毕后,我们可以直接访问 Kibana:
这样我们就进入到 Kibana 界面了。
创建 API Key
我们进入到如下的页面来申请 阿里云 ES API Key:
我们保存创建的 API key,并在之后的配置中使用。
创建嵌入推理端点
点击 Kibana 上面的 Stack Management,并进入到连机器页面:
参考如下的文章:
注意:上面的 host 就是指的在 API key 申请的那个地址。
我们可以选择一个支持多语言的模型,比如上面的 ops-text-embedding-002:
上面的 URL 是由 API key 中的地址组成的:
`http://default-8s7v.platform-cn-beijing.opensearch.aliyuncs.com/compatible-mode/v1/embeddings`AI写代码
注意:你需要根据自己在 API key 申请页面中的配置进行相应的修改。
点击上面的设置。我们可以进入到 Dev Tools 来进行测试:
`
1. POST _inference/alibaba_text_embedding
2. {
3. "input": "The sky above the port was the color of television tuned to a dead channel."
4. }
`AI写代码
很显然,它能帮我们生成我们的向量。我们接下来使用之前在文章 “如何写入 IMDB 电影数据并针对它运用 AI Agent Builder 对它进行分享” 示范的那样。我们改写我们的程序如下:
`
1. #!/usr/bin/env python3
2. """Ingest imdb_movies.csv into Elasticsearch, using connection settings from .env."""
4. import csv
5. import os
6. import sys
7. import urllib3
9. from dotenv import load_dotenv
10. from elasticsearch import Elasticsearch
11. from elasticsearch.helpers import bulk, BulkIndexError
12. from elastic_transport import TlsError
14. INDEX_NAME = "imdb"
15. CSV_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "imdb_movies.csv")
16. BULK_CHUNK_SIZE = 50
17. REQUEST_TIMEOUT = 300
19. INDEX_MAPPING = {
20. "mappings": {
21. "properties": {
22. "budget_x": {"type": "double"},
23. "country": {"type": "keyword"},
24. "crew": {"type": "text"},
25. "date_x": {"type": "keyword"},
26. "genre": {"type": "keyword"},
27. "names": {"type": "text"},
28. "orig_lang": {"type": "keyword"},
29. "orig_title": {"type": "text"},
30. "overview": {"type": "text", "copy_to": ["overview_semantic"]},
31. "overview_semantic": {
32. "type": "semantic_text",
33. "inference_id": "alibaba_text_embedding"
34. },
35. "revenue": {"type": "double"},
36. "score": {"type": "double"},
37. "status": {"type": "keyword"},
38. },
39. }
40. }
43. def build_client(es_url: str, es_api_key: str) -> Elasticsearch:
44. """Connect to Elasticsearch, working for both trusted and self-signed TLS certs."""
45. try:
46. client = Elasticsearch(
47. es_url, api_key=es_api_key, verify_certs=True, request_timeout=REQUEST_TIMEOUT
48. )
49. client.info()
50. return client
51. except TlsError:
52. print("Certificate could not be verified (self-signed?), retrying with verify_certs=False", file=sys.stderr)
53. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
54. client = Elasticsearch(
55. es_url, api_key=es_api_key, verify_certs=False, request_timeout=REQUEST_TIMEOUT
56. )
57. client.info()
58. return client
61. def ensure_index(client: Elasticsearch) -> None:
62. if client.indices.exists(index=INDEX_NAME):
63. print(f"Index '{INDEX_NAME}' already exists, skipping creation")
64. return
65. client.indices.create(index=INDEX_NAME, body=INDEX_MAPPING)
66. client.cluster.health(index=INDEX_NAME, wait_for_status="yellow", timeout="30s")
67. print(f"Created index '{INDEX_NAME}'")
70. def to_float(value):
71. value = (value or "").strip()
72. if not value:
73. return None
74. try:
75. return float(value)
76. except ValueError:
77. return None
80. def read_docs(csv_path: str):
81. with open(csv_path, newline="", encoding="utf-8") as f:
82. reader = csv.DictReader(f)
83. for row in reader:
84. doc = {
85. "names": (row.get("names") or "").strip(),
86. "date_x": (row.get("date_x") or "").strip(),
87. "score": to_float(row.get("score")),
88. "genre": [g.strip() for g in (row.get("genre") or "").split(",") if g.strip()],
89. "overview": (row.get("overview") or "").strip(),
90. "crew": (row.get("crew") or "").strip(),
91. "orig_title": (row.get("orig_title") or "").strip(),
92. "status": (row.get("status") or "").strip(),
93. "orig_lang": (row.get("orig_lang") or "").strip(),
94. "budget_x": to_float(row.get("budget_x")),
95. "revenue": to_float(row.get("revenue")),
96. "country": (row.get("country") or "").strip(),
97. }
98. yield {"_index": INDEX_NAME, "_source": doc}
101. def main() -> None:
102. load_dotenv()
103. es_url = os.environ["ES_URL"]
104. es_api_key = os.environ["ES_API_KEY"]
106. client = build_client(es_url, es_api_key)
107. ensure_index(client)
109. try:
110. success, errors = bulk(
111. client,
112. read_docs(CSV_PATH),
113. chunk_size=BULK_CHUNK_SIZE,
114. raise_on_error=False,
115. )
116. except BulkIndexError as e:
117. print(f"Bulk indexing failed: {e}", file=sys.stderr)
118. sys.exit(1)
120. print(f"Indexed {success} documents into '{INDEX_NAME}'")
121. if errors:
122. print(f"{len(errors)} documents failed to index", file=sys.stderr)
123. for err in errors[:5]:
124. print(err, file=sys.stderr)
127. if __name__ == "__main__":
128. main()
`AI写代码收起代码块
请注意在上面,我们使用了 "inference_id": "alibaba_text_embedding"。
运行我们的程序,它就可以把我们的数据写入到 Elasticsearch 中。
创建大模型连接器
我们可以使用如下的方式来连接大模型:
我们点击链接来查看有哪些模型可以使用。这个位于 API 申请的页面:
我们查看到我们需要的模型,比如上面的 qwen_plus。
我们在连接器里针对它进行如下的配置:
其中 URL 为:
`http://default-8s7v.platform-cn-beijing.opensearch.aliyuncs.com//compatible-mode/v1/chat/completions`AI写代码
注意:你需要根据自己在 API key 申请页面中的配置进行相应的修改。
它表明我们的配置是成功的。
在 Agents 中配置并使用它
我们在 Kibana 的 Agents 中打开并使用它:
Hurray! 我们的 LLM 现在可以开始工作了。
配置 Workflow
在 9.3 的发布中,Workflow 在默认的情况下,是没有展现的。我们需要启动它:
有关更多关于 Workflows 的知识,请在链接里进行查看。
好了。我基本上把我所想要讲的都讲了。祝大家学习愉快!