METADATA 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. Metadata-Version: 2.4
  2. Name: langsmith
  3. Version: 0.4.59
  4. Summary: Client library to connect to the LangSmith Observability and Evaluation Platform.
  5. Project-URL: Homepage, https://smith.langchain.com/
  6. Project-URL: Documentation, https://docs.smith.langchain.com/
  7. Project-URL: Repository, https://github.com/langchain-ai/langsmith-sdk
  8. Author-email: LangChain <support@langchain.dev>
  9. License: MIT
  10. Keywords: evaluation,langchain,langsmith,language,llm,nlp,platform,tracing,translation
  11. Requires-Python: >=3.10
  12. Requires-Dist: httpx<1,>=0.23.0
  13. Requires-Dist: orjson>=3.9.14; platform_python_implementation != 'PyPy'
  14. Requires-Dist: packaging>=23.2
  15. Requires-Dist: pydantic<3,>=1
  16. Requires-Dist: requests-toolbelt>=1.0.0
  17. Requires-Dist: requests>=2.0.0
  18. Requires-Dist: uuid-utils<1.0,>=0.12.0
  19. Requires-Dist: zstandard>=0.23.0
  20. Provides-Extra: claude-agent-sdk
  21. Requires-Dist: claude-agent-sdk>=0.1.0; (python_version >= '3.10') and extra == 'claude-agent-sdk'
  22. Provides-Extra: langsmith-pyo3
  23. Requires-Dist: langsmith-pyo3>=0.1.0rc2; extra == 'langsmith-pyo3'
  24. Provides-Extra: openai-agents
  25. Requires-Dist: openai-agents>=0.0.3; extra == 'openai-agents'
  26. Provides-Extra: otel
  27. Requires-Dist: opentelemetry-api>=1.30.0; extra == 'otel'
  28. Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.30.0; extra == 'otel'
  29. Requires-Dist: opentelemetry-sdk>=1.30.0; extra == 'otel'
  30. Provides-Extra: pytest
  31. Requires-Dist: pytest>=7.0.0; extra == 'pytest'
  32. Requires-Dist: rich>=13.9.4; extra == 'pytest'
  33. Requires-Dist: vcrpy>=7.0.0; extra == 'pytest'
  34. Provides-Extra: vcr
  35. Requires-Dist: vcrpy>=7.0.0; extra == 'vcr'
  36. Description-Content-Type: text/markdown
  37. # LangSmith Client SDK
  38. [![Release Notes](https://img.shields.io/github/release/langchain-ai/langsmith-sdk?logo=python)](https://github.com/langchain-ai/langsmith-sdk/releases)
  39. [![Python Downloads](https://static.pepy.tech/badge/langsmith/month)](https://pepy.tech/project/langsmith)
  40. This package contains the Python client for interacting with the [LangSmith platform](https://smith.langchain.com/).
  41. To install:
  42. ```bash
  43. pip install -U langsmith
  44. export LANGSMITH_TRACING=true
  45. export LANGSMITH_API_KEY=ls_...
  46. ```
  47. Then trace:
  48. ```python
  49. import openai
  50. from langsmith.wrappers import wrap_openai
  51. from langsmith import traceable
  52. # Auto-trace LLM calls in-context
  53. client = wrap_openai(openai.Client())
  54. @traceable # Auto-trace this function
  55. def pipeline(user_input: str):
  56. result = client.chat.completions.create(
  57. messages=[{"role": "user", "content": user_input}],
  58. model="gpt-3.5-turbo"
  59. )
  60. return result.choices[0].message.content
  61. pipeline("Hello, world!")
  62. ```
  63. See the resulting nested trace [🌐 here](https://smith.langchain.com/public/b37ca9b1-60cd-4a2a-817e-3c4e4443fdc0/r).
  64. LangSmith helps you and your team develop and evaluate language models and intelligent agents. It is compatible with any LLM application.
  65. > **Cookbook:** For tutorials on how to get more value out of LangSmith, check out the [Langsmith Cookbook](https://github.com/langchain-ai/langsmith-cookbook/tree/main) repo.
  66. A typical workflow looks like:
  67. 1. Set up an account with LangSmith.
  68. 2. Log traces while debugging and prototyping.
  69. 3. Run benchmark evaluations and continuously improve with the collected data.
  70. We'll walk through these steps in more detail below.
  71. ## 1. Connect to LangSmith
  72. Sign up for [LangSmith](https://smith.langchain.com/) using your GitHub, Discord accounts, or an email address and password. If you sign up with an email, make sure to verify your email address before logging in.
  73. Then, create a unique API key on the [Settings Page](https://smith.langchain.com/settings), which is found in the menu at the top right corner of the page.
  74. > [!NOTE]
  75. > Save the API Key in a secure location. It will not be shown again.
  76. ## 2. Log Traces
  77. You can log traces natively using the LangSmith SDK or within your LangChain application.
  78. ### Logging Traces with LangChain
  79. LangSmith seamlessly integrates with the Python LangChain library to record traces from your LLM applications.
  80. 1. **Copy the environment variables from the Settings Page and add them to your application.**
  81. Tracing can be activated by setting the following environment variables or by manually specifying the LangChainTracer.
  82. ```python
  83. import os
  84. os.environ["LANGSMITH_TRACING"] = "true"
  85. os.environ["LANGSMITH_ENDPOINT"] = "https://api.smith.langchain.com"
  86. # os.environ["LANGSMITH_ENDPOINT"] = "https://eu.api.smith.langchain.com" # If signed up in the EU region
  87. os.environ["LANGSMITH_API_KEY"] = "<YOUR-LANGSMITH-API-KEY>"
  88. # os.environ["LANGSMITH_PROJECT"] = "My Project Name" # Optional: "default" is used if not set
  89. # os.environ["LANGSMITH_WORKSPACE_ID"] = "<YOUR-WORKSPACE-ID>" # Required for org-scoped API keys
  90. ```
  91. > **Tip:** Projects are groups of traces. All runs are logged to a project. If not specified, the project is set to `default`.
  92. 2. **Run an Agent, Chain, or Language Model in LangChain**
  93. If the environment variables are correctly set, your application will automatically connect to the LangSmith platform.
  94. ```python
  95. from langchain_core.runnables import chain
  96. @chain
  97. def add_val(x: dict) -> dict:
  98. return {"val": x["val"] + 1}
  99. add_val({"val": 1})
  100. ```
  101. ### Logging Traces Outside LangChain
  102. You can still use the LangSmith development platform without depending on any
  103. LangChain code.
  104. 1. **Copy the environment variables from the Settings Page and add them to your application.**
  105. ```python
  106. import os
  107. os.environ["LANGSMITH_ENDPOINT"] = "https://api.smith.langchain.com"
  108. os.environ["LANGSMITH_API_KEY"] = "<YOUR-LANGSMITH-API-KEY>"
  109. # os.environ["LANGSMITH_PROJECT"] = "My Project Name" # Optional: "default" is used if not set
  110. ```
  111. 2. **Log traces**
  112. The easiest way to log traces using the SDK is via the `@traceable` decorator. Below is an example.
  113. ```python
  114. from datetime import datetime
  115. from typing import List, Optional, Tuple
  116. import openai
  117. from langsmith import traceable
  118. from langsmith.wrappers import wrap_openai
  119. client = wrap_openai(openai.Client())
  120. @traceable
  121. def argument_generator(query: str, additional_description: str = "") -> str:
  122. return client.chat.completions.create(
  123. [
  124. {"role": "system", "content": "You are a debater making an argument on a topic."
  125. f"{additional_description}"
  126. f" The current time is {datetime.now()}"},
  127. {"role": "user", "content": f"The discussion topic is {query}"}
  128. ]
  129. ).choices[0].message.content
  130. @traceable
  131. def argument_chain(query: str, additional_description: str = "") -> str:
  132. argument = argument_generator(query, additional_description)
  133. # ... Do other processing or call other functions...
  134. return argument
  135. argument_chain("Why is blue better than orange?")
  136. ```
  137. Alternatively, you can manually log events using the `Client` directly or using a `RunTree`, which is what the traceable decorator is meant to manage for you!
  138. A RunTree tracks your application. Each RunTree object is required to have a `name` and `run_type`. These and other important attributes are as follows:
  139. - `name`: `str` - used to identify the component's purpose
  140. - `run_type`: `str` - Currently one of "llm", "chain" or "tool"; more options will be added in the future
  141. - `inputs`: `dict` - the inputs to the component
  142. - `outputs`: `Optional[dict]` - the (optional) returned values from the component
  143. - `error`: `Optional[str]` - Any error messages that may have arisen during the call
  144. ```python
  145. from langsmith.run_trees import RunTree
  146. parent_run = RunTree(
  147. name="My Chat Bot",
  148. run_type="chain",
  149. inputs={"text": "Summarize this morning's meetings."},
  150. # project_name= "Defaults to the LANGSMITH_PROJECT env var"
  151. )
  152. parent_run.post()
  153. # .. My Chat Bot calls an LLM
  154. child_llm_run = parent_run.create_child(
  155. name="My Proprietary LLM",
  156. run_type="llm",
  157. inputs={
  158. "prompts": [
  159. "You are an AI Assistant. The time is XYZ."
  160. " Summarize this morning's meetings."
  161. ]
  162. },
  163. )
  164. child_llm_run.post()
  165. child_llm_run.end(
  166. outputs={
  167. "generations": [
  168. "I should use the transcript_loader tool"
  169. " to fetch meeting_transcripts from XYZ"
  170. ]
  171. }
  172. )
  173. child_llm_run.patch()
  174. # .. My Chat Bot takes the LLM output and calls
  175. # a tool / function for fetching transcripts ..
  176. child_tool_run = parent_run.create_child(
  177. name="transcript_loader",
  178. run_type="tool",
  179. inputs={"date": "XYZ", "content_type": "meeting_transcripts"},
  180. )
  181. child_tool_run.post()
  182. # The tool returns meeting notes to the chat bot
  183. child_tool_run.end(outputs={"meetings": ["Meeting1 notes.."]})
  184. child_tool_run.patch()
  185. child_chain_run = parent_run.create_child(
  186. name="Unreliable Component",
  187. run_type="tool",
  188. inputs={"input": "Summarize these notes..."},
  189. )
  190. child_chain_run.post()
  191. try:
  192. # .... the component does work
  193. raise ValueError("Something went wrong")
  194. child_chain_run.end(outputs={"output": "foo"}
  195. child_chain_run.patch()
  196. except Exception as e:
  197. child_chain_run.end(error=f"I errored again {e}")
  198. child_chain_run.patch()
  199. pass
  200. # .. The chat agent recovers
  201. parent_run.end(outputs={"output": ["The meeting notes are as follows:..."]})
  202. res = parent_run.patch()
  203. res.result()
  204. ```
  205. ## Create a Dataset from Existing Runs
  206. Once your runs are stored in LangSmith, you can convert them into a dataset.
  207. For this example, we will do so using the Client, but you can also do this using
  208. the web interface, as explained in the [LangSmith docs](https://docs.smith.langchain.com/).
  209. ```python
  210. from langsmith import Client
  211. client = Client()
  212. dataset_name = "Example Dataset"
  213. # We will only use examples from the top level AgentExecutor run here,
  214. # and exclude runs that errored.
  215. runs = client.list_runs(
  216. project_name="my_project",
  217. execution_order=1,
  218. error=False,
  219. )
  220. dataset = client.create_dataset(dataset_name, description="An example dataset")
  221. for run in runs:
  222. client.create_example(
  223. inputs=run.inputs,
  224. outputs=run.outputs,
  225. dataset_id=dataset.id,
  226. )
  227. ```
  228. ## Evaluating Runs
  229. Check out the [LangSmith Testing & Evaluation dos](https://docs.smith.langchain.com/evaluation) for up-to-date workflows.
  230. For generating automated feedback on individual runs, you can run evaluations directly using the LangSmith client.
  231. ```python
  232. from typing import Optional
  233. from langsmith.evaluation import StringEvaluator
  234. def jaccard_chars(output: str, answer: str) -> float:
  235. """Naive Jaccard similarity between two strings."""
  236. prediction_chars = set(output.strip().lower())
  237. answer_chars = set(answer.strip().lower())
  238. intersection = prediction_chars.intersection(answer_chars)
  239. union = prediction_chars.union(answer_chars)
  240. return len(intersection) / len(union)
  241. def grader(run_input: str, run_output: str, answer: Optional[str]) -> dict:
  242. """Compute the score and/or label for this run."""
  243. if answer is None:
  244. value = "AMBIGUOUS"
  245. score = 0.5
  246. else:
  247. score = jaccard_chars(run_output, answer)
  248. value = "CORRECT" if score > 0.9 else "INCORRECT"
  249. return dict(score=score, value=value)
  250. evaluator = StringEvaluator(evaluation_name="Jaccard", grading_function=grader)
  251. runs = client.list_runs(
  252. project_name="my_project",
  253. execution_order=1,
  254. error=False,
  255. )
  256. for run in runs:
  257. client.evaluate_run(run, evaluator)
  258. ```
  259. ## Integrations
  260. LangSmith easily integrates with your favorite LLM framework.
  261. ## OpenAI SDK
  262. <!-- markdown-link-check-disable -->
  263. We provide a convenient wrapper for the [OpenAI SDK](https://platform.openai.com/docs/api-reference).
  264. In order to use, you first need to set your LangSmith API key.
  265. ```shell
  266. export LANGSMITH_API_KEY=<your-api-key>
  267. ```
  268. Next, you will need to install the LangSmith SDK:
  269. ```shell
  270. pip install -U langsmith
  271. ```
  272. After that, you can wrap the OpenAI client:
  273. ```python
  274. from openai import OpenAI
  275. from langsmith import wrappers
  276. client = wrappers.wrap_openai(OpenAI())
  277. ```
  278. Now, you can use the OpenAI client as you normally would, but now everything is logged to LangSmith!
  279. ```python
  280. client.chat.completions.create(
  281. model="gpt-4",
  282. messages=[{"role": "user", "content": "Say this is a test"}],
  283. )
  284. ```
  285. Oftentimes, you use the OpenAI client inside of other functions.
  286. You can get nested traces by using this wrapped client and decorating those functions with `@traceable`.
  287. See [this documentation](https://docs.smith.langchain.com/tracing/faq/logging_and_viewing) for more documentation how to use this decorator
  288. ```python
  289. from langsmith import traceable
  290. @traceable(name="Call OpenAI")
  291. def my_function(text: str):
  292. return client.chat.completions.create(
  293. model="gpt-4",
  294. messages=[{"role": "user", "content": f"Say {text}"}],
  295. )
  296. my_function("hello world")
  297. ```
  298. ## Instructor
  299. We provide a convenient integration with [Instructor](https://jxnl.github.io/instructor/), largely by virtue of it essentially just using the OpenAI SDK.
  300. In order to use, you first need to set your LangSmith API key.
  301. ```shell
  302. export LANGSMITH_API_KEY=<your-api-key>
  303. ```
  304. Next, you will need to install the LangSmith SDK:
  305. ```shell
  306. pip install -U langsmith
  307. ```
  308. After that, you can wrap the OpenAI client:
  309. ```python
  310. from openai import OpenAI
  311. from langsmith import wrappers
  312. client = wrappers.wrap_openai(OpenAI())
  313. ```
  314. After this, you can patch the OpenAI client using `instructor`:
  315. ```python
  316. import instructor
  317. client = instructor.patch(OpenAI())
  318. ```
  319. Now, you can use `instructor` as you normally would, but now everything is logged to LangSmith!
  320. ```python
  321. from pydantic import BaseModel
  322. class UserDetail(BaseModel):
  323. name: str
  324. age: int
  325. user = client.chat.completions.create(
  326. model="gpt-3.5-turbo",
  327. response_model=UserDetail,
  328. messages=[
  329. {"role": "user", "content": "Extract Jason is 25 years old"},
  330. ]
  331. )
  332. ```
  333. Oftentimes, you use `instructor` inside of other functions.
  334. You can get nested traces by using this wrapped client and decorating those functions with `@traceable`.
  335. See [this documentation](https://docs.smith.langchain.com/tracing/faq/logging_and_viewing) for more documentation how to use this decorator
  336. ```python
  337. @traceable()
  338. def my_function(text: str) -> UserDetail:
  339. return client.chat.completions.create(
  340. model="gpt-3.5-turbo",
  341. response_model=UserDetail,
  342. messages=[
  343. {"role": "user", "content": f"Extract {text}"},
  344. ]
  345. )
  346. my_function("Jason is 25 years old")
  347. ```
  348. ## Pytest Plugin
  349. The LangSmith pytest plugin lets Python developers define their datasets and evaluations as pytest test cases.
  350. See [online docs](https://docs.smith.langchain.com/evaluation/how_to_guides/pytest) for more information.
  351. This plugin is installed as part of the LangSmith SDK, and is enabled by default.
  352. See also official pytest docs: [How to install and use plugins](https://docs.pytest.org/en/stable/how-to/plugins.html)
  353. ## Additional Documentation
  354. To learn more about the LangSmith platform, check out the [docs](https://docs.smith.langchain.com/).
  355. # License
  356. The LangSmith SDK is licensed under the [MIT License](../LICENSE).
  357. The copyright information for certain dependencies' are reproduced in their corresponding COPYRIGHT.txt files in this repo, including the following:
  358. - [uuid-utils](docs/templates/uuid-utils/COPYRIGHT.txt)
  359. - [zstandard](docs/templates/zstandard/COPYRIGHT.txt)