Compare commits

...

128 Commits

Author SHA1 Message Date
Eugene Yurtsev 0e971b367f Release 0.0.30 (#250)
See release notes
2023-11-20 17:06:39 -05:00
jakerachleff eef38b532d add auto metadata logging for stream log (#249) 2023-11-20 14:04:52 -08:00
jakerachleff b60b52daf6 add default configs for all served runnables (#209)
Configures the run name to be the path, and some information about the
associated repo to be in the metadata of the traced run

---------

Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-11-20 13:59:36 -08:00
Nuno Campos eb78a3f78d Use pytest asyncio auto mode (#247) 2023-11-20 13:07:21 -05:00
Eugene Yurtsev 798739c406 v0.0.29 (#244)
See release notes
2023-11-17 10:39:15 -05:00
Eugene Yurtsev d8ffff9926 Update pydantic compatibility message, and add one to openapi docs as well (#243)
Surfacing the pydantic compatibility message in open api docs as well to
help users!

This PR adds a warning message to the openapi docs when using pydantic
v2:

![image](https://github.com/langchain-ai/langserve/assets/3205522/729eeeea-7fbd-49d7-b21a-62b5903d9714)
2023-11-17 10:37:10 -05:00
jakerachleff 286d254c72 remove eager mode on feedback (#216)
Eager mode is not a preferred option for langsmith APIs. We thus change
the `/feedback` to use the regular submission of feedback flow.
2023-11-16 14:15:29 -08:00
Erick Friis 0adf0e7e3a Fix python docs build (#242)
Docusaurus build doesn't like that the `img` tags don't have a closing
tag. I think adding the `/>` to the end will fix it.
2023-11-16 10:53:36 -08:00
Eugene Yurtsev 22831cabed Reorganize readme, add documentation to config hash endpoints (#241)
* Re organize some sections in the readme
* Use more highlighting in the readme for sections where attention is
required
* Expand doc-strings for config hash endpoints 
 

![image](https://github.com/langchain-ai/langserve/assets/3205522/9cfb8039-b9e6-4079-b677-d8a298575763)
2023-11-16 12:44:02 -05:00
Eugene Yurtsev 078453f2c4 update README with screenshots (#240)
* Add screenshot for sharing in playground
2023-11-16 12:18:17 -05:00
Eugene Yurtsev a01f547694 Update examples (#239)
* Additional example updates -- remove configurable key (no longer
required)
* Use pydantic v1 compatibility layer correctly
2023-11-16 11:16:46 -05:00
Eugene Yurtsev b53fa466b0 Update conversational retriever chain example (#238)
Update conversational retriever example
2023-11-16 11:01:40 -05:00
Eugene Yurtsev 4b62a4660d Release 0.0.28 (#237)
Release v0.0.28
2023-11-16 10:15:29 -05:00
Eugene Yurtsev f0ed9830b0 Add support for API route via prefix (#236)
* Fix serving of playground assets when using an API router with a
custom prefix

---------

Co-authored-by: Andreas Hildebrandt <andreas.hildebrandt@uni-mainz.de>
2023-11-16 10:10:29 -05:00
Eugene Yurtsev 65dfbceac4 Update .clabot (#235)
https://github.com/langchain-ai/langserve/issues/233 -- signed cla bot
2023-11-16 10:01:06 -05:00
Craig Dennis 9ee157e91c bug: typo in README and slight cognitive overload terminology lift (#226)
Just a quick fix from `/chain/invoke` in the TypeScript example.

Also tried to do a little clarity lift on the endpoint name. `chain`
felt a little vague for the endpoint, and I think misses the point.

Thanks for the project all!

Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-11-15 15:52:30 -05:00
Eugene Yurtsev 1b61b04922 Empty commit (#232)
Empty commit for cla bot
2023-11-15 15:52:04 -05:00
Eugene Yurtsev f656c5f565 Update .clabot (#231) 2023-11-15 15:47:47 -05:00
Erick Friis e6323afadf restrict fastapi, lock langsmith higher version (#227)
2 changes:
- restrict fastapi version to <1, so it doesn't break the cli test
release (test.pypi.org has a fastapi==1 version that is unrelated to
real fastapi)
- upgrade langsmith in the lockfile to 0.0.64 (from 0.0.62, which was
yanked)

Some unrelated lockfile changes also happened. Happy to try to revert
those but a bit unclear how.
2023-11-15 15:46:01 -05:00
Eugene Yurtsev 7372bcff3a Version 0.0.27 (#225)
See release notes
2023-11-13 14:43:25 -05:00
Eugene Yurtsev abe9bb79ea Minor: language update in splash screen (#224)
Minor language update
2023-11-13 14:34:15 -05:00
Eugene Yurtsev 2f4bcdd144 Update Splash Screen with warning about openapi docs (#221)
Update the splash screen to output a warning about OpenAPI docs missing
when using pydantic v2.
2023-11-13 14:29:40 -05:00
Eugene Yurtsev 38b935644f Apply noqa to specific statement rather than entire file (#223)
Apply noqa to specific statement rather than entire file
2023-11-13 14:26:47 -05:00
Eugene Yurtsev d591be4dce Enable configurable by default langserve side (#219)
* Enable configurable key by default
* Should be safe to enable by default since the user is already marking
the runnable as configurable (when they make it configurable)
* Raise an client side error if the client specifies a `configurable`
key but the server does not accept it (will help in debugging)
2023-11-13 14:26:38 -05:00
Eugene Yurtsev ea7bb5d970 Minor: Update names to not include Test prefix (#222)
This triggers a warning from pytest collection when running tests since
the namespaces begin with `Test`
2023-11-13 13:58:02 -05:00
Eugene Yurtsev d8d3262987 Do not enable langsmith tracer globally (#205)
Fixes test to not enable langsmith tracer globally
2023-11-13 11:04:02 -05:00
Eugene Yurtsev fe3abc8914 Version 0.0.26 (#211) 2023-11-10 21:42:39 -05:00
Eugene Yurtsev c93e3fde2c RemoteClient should handle metadata event on streaming (#210)
* Handle metadata event on streaming
* Make sure not to duplicate logger error messages

Resolve: https://github.com/langchain-ai/langserve/issues/208
2023-11-10 21:36:24 -05:00
Eugene Yurtsev 7e1a1a17c7 Add feedback created id (#206)
Add feedback created id
2023-11-09 23:02:51 -05:00
Eugene Yurtsev 13dcfb4b26 Vesion 0.0.25 release (#201)
See release notes
2023-11-09 21:30:15 -05:00
Eugene Yurtsev 6f917431bb Build playground (#204)
Build playground
2023-11-09 21:24:37 -05:00
David Duong e8f441774a Fix playground crash, provide output to autocomplete history (#202)
Closes #177
2023-11-09 21:19:27 -05:00
Eugene Yurtsev f5a97a6db3 Build playground assets (#199)
build playground assets
2023-11-09 15:16:40 -05:00
Eugene Yurtsev 4de13afe0e Delegate to orjson on the encoding path (#195)
Using orjson on the encoding path. This will encode well known types
like uuid, datetime, date, time etc.

This PR does not handle the decoding path as decoding can only be done
properly once we take into account the jsonschema.

Rolling this out partially seems fine since:

1) Handling the encoding side is probably more important for well known
objects -- users can still roll out decoding code using RunnableLambda
and pydantic or we can add run time coercion to runnables.
2) The encoding format will NOT change once we incorporate more changes
(i.e., we're using a standard representation of the well known types)
2023-11-09 15:01:46 -05:00
Eugene Yurtsev c2606efdbb Change relative link to absolute links to examples (#200)
Use absolute so it works when shown on langchain docs
2023-11-09 15:01:34 -05:00
David Duong 35b31cf39a Only trigger iframe view if search param is present (#194)
Needed for integrating playground within other apps via iframe

Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-11-09 14:46:40 -05:00
Bagatur 8e2e9a03b5 Update README.md (#198)
match langchain + langsmith
2023-11-09 14:22:18 -05:00
jakerachleff 98edac4097 upgrade langchain dependency for proper project tracing logic (#196)
We need to rely on langchain >= 0.333 to make sure langchain uses the
langsmith sdk for figuring out the right project to trace to

Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-11-09 11:04:15 -08:00
Eugene Yurtsev 1078a86017 Bump timeout to 5 seconds (#197)
Bumping timeout to 5 seconds -- hopefully it'll identify the same test
as the culprit
2023-11-09 13:56:29 -05:00
jakerachleff 2eb2ed9d76 enable eager mode for feedback from langserve (#182)
We want to ensure that langsmith feedback is only submitted for existing
runs, as it makes the UI much easier to manage, as it knows that a
successful `/feedback` request equates to successfully submitted
feedback.

### Testing
I spun up a server and made sure I could submit feedback on an existing
run:
<img width="988" alt="Screenshot 2023-11-07 at 11 22 37 AM"
src="https://github.com/langchain-ai/langserve/assets/9028897/c0685fd7-1e97-463e-bf37-3dd341a104fd">


And that a non existing run retries 3 times then fails:
<img width="978" alt="Screenshot 2023-11-07 at 11 22 26 AM"
src="https://github.com/langchain-ai/langserve/assets/9028897/c3de6869-3929-4527-a401-0db33c33cd14">
2023-11-09 09:47:56 -08:00
Eugene Yurtsev e188f2e643 Create a module for pydantic v1 (#187)
Create a module for pydantic v1 code, so we don't have to worry about
conditional imports or try/except blocks in the codebase.
2023-11-08 21:40:19 -05:00
Eugene Yurtsev 5b46eabed4 Add timeouts to pytest (#191)
* Add timeouts to pytest.
* Timeout is very generous due to time it takes to set up app
2023-11-08 21:31:22 -05:00
Eugene Yurtsev c1a77fcad3 Add timeout to github actions (#192)
Add timeout to CI and pydantic actions
2023-11-08 21:31:11 -05:00
Eugene Yurtsev 33b3f14b4b Update examples to use pydantic v1 for safety (#188)
This PR updates all exmaples to use langchain pydantic v1 namespace when
using pydantic.

The reason is that most of langchain objects are still using on pydantic
v1 and
code should not mix v1 and v2.
2023-11-08 07:04:40 -05:00
Eugene Yurtsev b1479d601e Add pydantic guidelines to README (#189)
Add pydantic guidelines to README.md
2023-11-07 22:03:00 -05:00
Eugene Yurtsev 87f4a1f6c7 Update README with pydantic information (#186) 2023-11-07 21:48:13 -05:00
Eugene Yurtsev 6ffef8aa60 Version 0.0.24 (#185)
Version 0.0.24
2023-11-07 21:05:26 -05:00
Eugene Yurtsev 0dd55c8b94 Add pydantic v2 support (#181)
This PR adds pydantic v2 support to LangServe.

With pydantic v2 all endpoints will work, but openapi docs will not be
generated for these endpoints. (At least at the moment.)

---------

Co-authored-by: jakerachleff <jake@langchain.dev>
2023-11-07 21:02:27 -05:00
Jacob Lee 2f8d0469f6 Update example URLs with trailing slashes (#184)
Some browsers don't have redirects, so this is more accurate CC
@eyurtsev
2023-11-07 20:56:06 -05:00
Eugene Yurtsev 3db248f870 Use repository specific clabot config (#183)
Swapping to using repository specific clabot config.

I have not found a way of supporting multiple configurations through a
single organizational clabot-config repo.
2023-11-07 16:05:39 -05:00
jakerachleff cf6935d7ef add metadata event to /stream for collecting run_id of individual runs (#180)
Adds a new event with type `metadata` that can return metadata about a
run. This can be used for getting a run_id from the `/stream` API

### Testing
- Unit Tests: added in `test_server_client`
- Manual Tests: I ran `examples/llm/server.py` locally and ensured the
returned run_id from the metadata event matched the one logged to
langsmith
2023-11-07 09:40:27 -08:00
jakerachleff d054a4004b Allow dynamic modification of RunnableConfig based on request properties (#161)
Users may want to modify the properties of the RunnableConfig based on
the incoming request. This is useful if the end user is serving, for
example, an Azure OpenAI model, and they have a token in their request
header.
2023-11-06 22:02:31 -08:00
Erick Friis eaaac09431 Remove packages functions (#179)
Enabled by https://github.com/langchain-ai/langchain/pull/12945
2023-11-06 22:17:58 -05:00
Eugene Yurtsev 5fbd1332e7 Version 0.0.23 (#176)
Version 0.0.23
2023-11-06 11:38:19 -05:00
David Duong 77f1741262 Show AI function messages in editable input, fix empty initial message (#175) 2023-11-06 11:31:43 -05:00
Nuno Campos cfafce1e42 Unpack input recursively, to ensure that sub-types that are expected … (#174)
…to remain as BaseModel do

This fixes input types such as 

```
class AgentInput(BaseModel):
    messages: Sequence[AnyMessage] = Field(..., extra={"widget": {"type": "chat"}})
```

---------

Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-11-06 10:13:52 -05:00
Nuno Campos b0ff0c3bed Fix playground crash on undefined schema (#173) 2023-11-05 11:24:38 +00:00
Nuno Campos ac9d4d4840 Update frontend build (#172) 2023-11-05 10:22:14 +00:00
Nuno Campos e1aa00a1aa Preserve whitespace in playground output (#163) 2023-11-05 10:16:07 +00:00
Nuno Campos 8c5d448543 Merge pull request #169 from langchain-ai/nc/ruff-format
Replace black with ruff format
2023-11-05 10:10:32 +00:00
Nuno Campos 6e6accb7d4 ... 2023-11-05 10:09:09 +00:00
Nuno Campos 1347385616 Haha 2023-11-05 10:07:58 +00:00
Nuno Campos 8a332b076d Replace black with ruff format
To match langchain repo
2023-11-04 18:48:27 +00:00
David Duong 180694e8e0 Add autofill of chat history, fix turnstile chat history (#157)
https://github.com/langchain-ai/langserve/assets/1443449/8cdae247-8197-4877-aa4c-0a4bcdf8d7d2

- [x] Handle function calls and additional kwargs in List[*Message]
- [x] Handle Tuple[message,message] alongside Tuple[role, message]
2023-11-04 00:07:45 +01:00
Erick Friis a97d870f82 Update cli install command (#166)
Merge after releasing CLI 0.0.14
2023-11-03 12:09:55 -07:00
Eugene Yurtsev 8382871128 Update README.md with badgets / links (#165)
Update README to include various badges
2023-11-03 11:49:03 -04:00
Eugene Yurtsev 443bdc746d Use utf-8 encoding when opening playground assets (#164)
Specify use utf-8 encoding when opening files for playground assets. On
some platforms the default encoding is not utf-8 (e.g., windows).
2023-11-03 10:20:31 -04:00
jakerachleff 92af3116cc Add Feedback Endpoint to LangServe (#153)
This PR adds an endpoint to LangServe servers called `/feedback` which
will take in feedback in the same schema as LangSmith feedback, and
forward along said feedback to LangSmith. If the server does not have
LangSmith enabled, then the `/feedback` endpoint will return a 400.

---------

Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-11-02 19:00:47 -07:00
Eugene Yurtsev a8e954ec9f 0.0.22 (#159)
See release notes for details
2023-11-02 21:41:58 -04:00
Eugene Yurtsev ce17cc4241 Fix bug in streaming associated with additive chunks (#158)
- Fix issue in stream/astream endpoint associated with addable types

- Have not been able to figure how to run sync unit tests yet with
pytest:
- fastapi app is async so there's an event loop that's created somewhere
  - within fastapi sse_starlette also deals with an event loop for the
    streaming endpoint
- This results in a failure when running all unit tests together
(https://github.com/sysid/sse-starlette/issues/68)
2023-11-02 21:39:53 -04:00
Eugene Yurtsev 876201e7f3 Remove names/tags from undocumented versions of endpoints (#155)
Forgot to remove these -- these cause a user warning when viewing docs
2023-11-02 14:46:54 -04:00
Nuno Campos 15816981fd Revert "Remove original playground code" (#152)
Reverts langchain-ai/langserve#151
2023-11-01 18:46:24 +00:00
Nuno Campos dc7da56416 Remove original playground code (#151)
This was moved to other folder weeks ago
2023-11-01 14:27:25 -04:00
Erick Friis 8d8bb49a9d Readme update for new cli (#150)
Fixes #149
2023-11-01 12:40:52 -04:00
jakerachleff cc2f9b886f Return run IDs from invoke/batch endpoints (#148)
Clients of LangServe may be interested in the run_id of each parent run
of LangChain. This can be used, for example, for external tracing
applications like LangSmith. In this PR, we introduce a new dictionary
in the response for the invoke/batch endpoints called "metadata" where
we put the run_id (or run_ids for batch).

### Notes
- Stream is not currently supported since we do not have callbacks set
up around streaming, we can add that later if needed

---------

Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-11-01 09:36:32 -07:00
Eugene Yurtsev 4a7e8d5317 Update examples (#146)
Update examples
2023-10-31 22:14:44 -04:00
Eugene Yurtsev b7639f72c4 Add link to langserve hub templates (#147)
Add link to langserve hub templates
2023-10-31 22:14:19 -04:00
Eugene Yurtsev fdcb53e35b Add image of playground (#145) 2023-10-31 16:06:00 -04:00
Eugene Yurtsev 16da208c7e Bump lock file (#142)
Bump lock file
2023-10-31 14:05:50 -04:00
Eugene Yurtsev 4f6c855f42 Version 0.0.21 (#140)
Release 0.0.21
2023-10-31 13:18:38 -04:00
Eugene Yurtsev 9d69e37c18 Build new version of playground (#139)
Build playground assets
2023-10-31 13:15:41 -04:00
David Duong 6e4967ac31 Fix autotype history fix (#138) 2023-10-31 12:39:47 -04:00
David Duong 9b8e9a46e0 Add number of intermediate steps recorded, disable button (#136)
Closes #120
2023-10-31 12:34:48 -04:00
Brace Sproul 0ddf4b1a02 Fix disabled button state (#124)
Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-10-31 12:33:59 -04:00
Eugene Yurtsev 43df917456 Dynamic validation for streaming endpoints (#133)
- [x] Add test to verify that client side errors are now raised for
streaming endpoints
- [x] Add more tests to verify that config and inputs are being
validated properly -- or introduce more pydantic models
2023-10-31 11:46:01 -04:00
Nuno Campos 4e8a72374d Group routes in API docs by path (#135)
<img width="1264" alt="Screenshot 2023-10-31 at 11 43 31"
src="https://github.com/langchain-ai/langserve/assets/56902/15348bde-d1f0-4b64-b869-9d342584bb77">
2023-10-31 15:32:08 +00:00
Nuno Campos 865140abac Fix crash when mounting same chain twice in same app (#134)
The crash was due to Config.configurable pydantic base model not being
renamed, fixed by recursively renaming field annotations which are
themselves base models
2023-10-31 09:51:46 -04:00
Nuno Campos 4a4ccb7235 Parse input dynamically to ensure new keys arent filtered out by pydantic (#79)
* Adds dynamic input parsing to invoke and batch endpoints
* Separate documentation from validation -- create dummy endpoints for
documentation using pydantic, and handle validation using our own logic
(our validation is more involved)

---------

Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-10-30 22:15:07 -04:00
Eugene Yurtsev 5f2bad663e Version 0.0.20 (#132)
Version 0.0.20
2023-10-30 22:12:33 -04:00
Harrison Chase dcee6ec12e add hosted signup form (#131)
Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-10-30 14:00:42 -07:00
Eugene Yurtsev cb3de13fea Fix bug for adding routes to APIRouter (#130)
-- Disables the startup logs and the check for re-used paths for API
routers.
-- API Router is unhashable, so we'll disable some non-essential
features for API routers
2023-10-30 14:01:24 -04:00
William FH a94b66696f Enforce trailing slash in the client (#126)
Would resolve the error in #125

---------

Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-10-29 22:25:48 -04:00
Jacob Lee 7be2927518 Add logs on startup, global handler method (#123)
We can also add more global one-off endpoints (like a meta/directory UI)
in the handler in the future.

<img width="714" alt="Screenshot 2023-10-27 at 3 27 04 PM"
src="https://github.com/langchain-ai/langserve/assets/6952323/a7f43632-0e24-4ad8-8d52-447b702f929e">
2023-10-28 07:11:34 -07:00
Eugene Yurtsev 1ddf554f9d 0.0.19 (#121)
This release includes some playground fixes
2023-10-27 14:37:08 -04:00
David Duong f10509bb5a Playground UX fixes (#119)
- [x] Reset button
 - [x] Remove default single message
 - [x] Remove default `anyOf` handling
 - [x] `additional_kwargs` are not shown in the output
 - [x] Cmd+Enter on submit
 - [x] Loading spinner

Closes #105, #110
2023-10-27 14:27:49 -04:00
Eugene Yurtsev 14eb1a6ea4 Update README (#117)
Add inforamtion about widgets, input and output types
2023-10-26 22:09:16 -04:00
Eugene Yurtsev d6f4a58d99 Merge pull request #116
* bump version
2023-10-26 21:27:28 -04:00
Eugene Yurtsev 17eda1e85d Widgets (#91)
Add examples for widgets for playground

---------

Co-authored-by: Bagatur <22008038+baskaryan@users.noreply.github.com>
Co-authored-by: Nuno Campos <nuno@boringbits.io>
Co-authored-by: Tat Dat Duong <david@duong.cz>
2023-10-27 00:43:12 +02:00
Eugene Yurtsev 44dc693217 Add a custom user type (#115)
Add a custom user type
2023-10-26 15:31:13 -04:00
Eugene Yurtsev 3a3a1deed6 Add working with files to README.md (#114)
Add working with files
2023-10-26 14:52:51 -04:00
Eugene Yurtsev ef0018823b Add file processing example (#113)
Add file processing example
2023-10-26 14:21:47 -04:00
Eugene Yurtsev 77276eac89 version 0.0.17 (#111)
Release 0.0.17
2023-10-25 21:23:22 -04:00
Eugene Yurtsev 93ab04854d Error on path collisions (#109)
Error on path collisions.
2023-10-25 17:24:53 -04:00
Eugene Yurtsev 20e5f46697 Update input and output type logic if specified via add_routes (#107)
Update logic if specified via add routes
2023-10-25 17:10:42 -04:00
Eugene Yurtsev a0ffcf068a Error on missing / (#108)
Error on missing `/`
2023-10-25 17:10:26 -04:00
Eugene Yurtsev b91d84ac01 Use get config list for batch endpoint (#103)
Use get config list
2023-10-25 15:24:47 -04:00
Eugene Yurtsev b828fb7bae Test playground endpoint (#102)
Test playground file serve
2023-10-25 14:40:27 -04:00
Eugene Yurtsev 96239f87bf Security notice to README (#100)
Add security notice to README
2023-10-25 14:13:13 -04:00
Eugene Yurtsev 03c1fd981f Bump pytest (#101)
Bump pytest
2023-10-25 13:10:55 -04:00
Eugene Yurtsev 21238be7a0 Bump version (#99)
Bump version
2023-10-25 10:59:25 -04:00
David Duong b629689f3b Fix parent root escape (#98) 2023-10-25 10:55:41 -04:00
Nuno Campos 135c0c3ad6 Slash (#97) 2023-10-25 15:19:03 +01:00
Eugene Yurtsev b3166958c8 Serialization fix for callbacks (#95)
- Fix serialization of callbacks to add an LLMResults with concrete generation types
2023-10-25 05:52:04 -04:00
Eugene Yurtsev 94e08e7972 Add server side callback event handling to client (#92)
This PR adds the ability to handle server side events by the remote
runnables.

Prior to landing:

- Blocked on 2 changes in langchain to be released
- Should add ChatGeneration, Generation... to list of well known lc
types (otherwise traces with llms won't work correctly)
2023-10-24 21:21:12 -04:00
Bagatur 20875e0362 very important (#93)
Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-10-24 16:09:31 -04:00
David Duong 73737949f9 New JS build (#90) 2023-10-24 15:56:53 +02:00
David Duong 7f6a23e9c1 Handle streamed message chunks in playground (#76) 2023-10-24 15:52:21 +02:00
David Duong 85c5acf1f6 Chat Messages input in Playground (#80)
https://github.com/langchain-ai/langserve/assets/1443449/a6053321-b4ee-409e-996d-2ff91e88acbb
2023-10-24 15:41:09 +02:00
Eugene Yurtsev 366feed79e Add callback events from server (#88)
This PR allows the server to send callback events to the client.

Limited to the invoke and batch end points for the time being.

This PR does NOT include the client code to use the events (will be
included in a separate PR to keep things simple).

Also updating the serializer to use an interface -- placeholder for
future code to accommodate user adding their own custom pydantic objects.
2023-10-23 22:29:36 -04:00
Erick Friis 26a4495a53 Add package routes (#87)
Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-10-23 15:16:00 -07:00
Nuno Campos ff6f20d9e1 Remove usage of locals from example (#86)
Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-10-23 13:33:52 -04:00
Eugene Yurtsev c448042d3d Start handling errors on stream/astream/astream_log (#83)
This PR introduces error handling for stream/astream/astream_log
endpoints.

The error handling is incomplete as client side errors aren't handled
yet.

1) When an exception is encountered while streaming the server sents an
error event in the stream with data:

- status code: int
- message: str

2) Client code is updated to handle this

In addition this PR, proposes that the client with log an error instead
of raising when encountering an unsupported event. This will allow us to
ship additional events without breaking older clients. Useful for sending
over callback events.
2023-10-20 15:43:58 -04:00
Eugene Yurtsev 0db97cf565 Update readme (#81)
Update readme
2023-10-20 09:16:31 -04:00
Eugene Yurtsev ea6b3867f6 Account for custom input and output types (#56)
Account for custom input and output types
2023-10-19 22:23:09 -04:00
Nuno Campos 3027ecab3d 0.0.15 (#77) 2023-10-19 20:07:13 +01:00
Nuno Campos 80108338db 0.0.14 (#74) 2023-10-19 20:03:04 +01:00
Nuno Campos a4497911fd Refetch input schema on config change aka. support configurable prompts (#66) 2023-10-19 20:01:41 +01:00
Nuno Campos b93ccf9b90 Add documentation for playground (#73) 2023-10-19 18:30:14 +01:00
65 changed files with 7247 additions and 1518 deletions
+4
View File
@@ -0,0 +1,4 @@
{
"contributors": ["eyurtsev", "hwchase17", "nfcampos", "efriis", "jacoblee93", "dqbd", "kreneskyp", "adarsh-jha-dev", "harris", "baskaryan", "hinthornw", "bracesproul", "jakerachleff", "craigsdennis", "anhi"],
"message": "Thank you for your pull request and welcome to our community. We require contributors to sign our Contributor License Agreement, and we don't seem to have the username {{usersWithoutCLA}} on file. In order for us to review and merge your code, please complete the Individual Contributor License Agreement here https://forms.gle/Ljhqvt9Gdi1N385W6 .\n\nThis process is done manually on our side, so after signing the form one of the maintainers will add you to the contributors list.\n\nFor more details about why we have a CLA and other contribution guidelines please see: https://github.com/langchain-ai/langserve/blob/main/CONTRIBUTING.md."
}
@@ -13,6 +13,7 @@ env:
jobs:
build:
timeout-minutes: 5
defaults:
run:
working-directory: ${{ inputs.working-directory }}
+10 -1
View File
@@ -11,8 +11,10 @@ on:
- '.github/workflows/_test.yml'
- '.github/workflows/langserve_ci.yml'
- 'langserve/**'
- 'tests/**'
- 'examples/**'
- 'pyproject.toml'
- 'poetry.lock'
- 'Makefile'
workflow_dispatch: # Allows to trigger the workflow manually in GitHub UI
@@ -38,7 +40,14 @@ jobs:
working-directory: .
secrets: inherit
pydantic-compatibility:
uses:
./.github/workflows/_pydantic_compatibility.yml
with:
working-directory: .
secrets: inherit
test:
timeout-minutes: 5
runs-on: ubuntu-latest
defaults:
run:
@@ -50,7 +59,7 @@ jobs:
- "3.9"
- "3.10"
- "3.11"
name: Python ${{ matrix.python-version }} extended tests
name: Python ${{ matrix.python-version }} tests
steps:
- uses: actions/checkout@v3
+2 -2
View File
@@ -33,10 +33,10 @@ lint_diff format_diff: PYTHON_FILES=$(shell git diff --relative=. --name-only --
lint lint_diff:
poetry run ruff .
poetry run black $(PYTHON_FILES) --check
poetry run ruff format $(PYTHON_FILES) --check
format format_diff:
poetry run black $(PYTHON_FILES)
poetry run ruff format $(PYTHON_FILES)
poetry run ruff --select I --fix $(PYTHON_FILES)
spell_check:
+241 -33
View File
@@ -1,4 +1,11 @@
# LangServe 🦜️🔗
# 🦜️🏓 LangServe
[![Release Notes](https://img.shields.io/github/release/langchain-ai/langserve)](https://github.com/langchain-ai/langserve/releases)
[![Downloads](https://static.pepy.tech/badge/langserve/month)](https://pepy.tech/project/langserve)
[![Open Issues](https://img.shields.io/github/issues-raw/langchain-ai/langserve)](https://github.com/langchain-ai/langserve/issues)
[![](https://dcbadge.vercel.app/api/server/6adMQxSpJS?compact=true&style=flat)](https://discord.com/channels/1038097195422978059/1170024642245832774)
🚩 We will be releasing a hosted version of LangServe for one-click deployments of LangChain applications. [Sign up here](https://airtable.com/app0hN6sd93QcKubv/shrAjst60xXa6quV2) to get on the waitlist.
## Overview
@@ -15,32 +22,55 @@ A javascript client is available in [LangChainJS](https://js.langchain.com/docs/
- API docs page with JSONSchema and Swagger (insert example link)
- Efficient `/invoke`, `/batch` and `/stream` endpoints with support for many concurrent requests on a single server
- `/stream_log` endpoint for streaming all (or some) intermediate steps from your chain/agent
- Playground page at `/playground` with streaming output and intermediate steps
- Built-in (optional) tracing to [LangSmith](https://www.langchain.com/langsmith), just add your API key (see [Instructions](https://docs.smith.langchain.com/)])
- All built with battle-tested open-source Python libraries like FastAPI, Pydantic, uvloop and asyncio.
- Use the client SDK to call a LangServe server as if it was a Runnable running locally (or call the HTTP API directly)
- [LangServe Hub](https://github.com/langchain-ai/langchain/blob/master/templates/README.md)
### Limitations
- Client callbacks are not yet supported for events that originate on the server
- Does not work with [pydantic v2 yet](https://github.com/tiangolo/fastapi/issues/10360)
- OpenAPI docs will not be generated when using Pydantic V2. Fast API does not support [mixing pydantic v1 and v2 namespaces](https://github.com/tiangolo/fastapi/issues/10360). See section below for more details.
## LangChain CLI 🛠️
## Hosted LangServe
We will be releasing a hosted version of LangServe for one-click deployments of LangChain applications. [Sign up here](https://airtable.com/app0hN6sd93QcKubv/shrAjst60xXa6quV2) to get on the waitlist.
## Security
* Vulnerability in Versions 0.0.13 - 0.0.15 -- playground endpoint allows accessing arbitrary files on server. [Resolved in 0.0.16](https://github.com/langchain-ai/langserve/pull/98).
## Installation
For both client and server:
```bash
pip install "langserve[all]"
```
or `pip install "langserve[client]"` for client code, and `pip install "langserve[server]"` for server code.
## LangChain CLI 🛠️
Use the `LangChain` CLI to bootstrap a `LangServe` project quickly.
To use the langchain CLI make sure that you have a recent version of `langchain` installed
and also `typer`. (`pip install langchain typer` or `pip install "langchain[cli]"`)
To use the langchain CLI make sure that you have a recent version of `langchain-cli`
installed. You can install it with `pip install -U langchain-cli`.
```sh
langchain ../path/to/directory
langchain app new ../path/to/directory
```
And follow the instructions...
## Examples
For more examples, see the [examples](./examples) directory.
Get your LangServe instance started quickly with
[LangChain Templates](https://github.com/langchain-ai/langchain/blob/master/templates/README.md).
For more examples, see the templates
[index](https://github.com/langchain-ai/langchain/blob/master/templates/docs/INDEX.md)
or the [examples](https://github.com/langchain-ai/langserve/tree/main/examples) directory.
### Server
@@ -78,7 +108,7 @@ prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
add_routes(
app,
prompt | model,
path="/chain",
path="/joke",
)
if __name__ == "__main__":
@@ -91,10 +121,17 @@ if __name__ == "__main__":
If you've deployed the server above, you can view the generated OpenAPI docs using:
> ⚠️ If using pydantic v2, docs will not be generated for invoke/batch/stream/stream_log. See [Pydantic](#pydantic) section below for more details.
```sh
curl localhost:8000/docs
```
make sure to **add** the `/docs` suffix.
> ⚠️ Index page `/` is not defined by **design**, so `curl localhost:8000` or visiting the URL
> will return a 404. If you want content at `/` define an endpoint `@app.get("/")`.
### Client
Python SDK
@@ -108,7 +145,7 @@ from langserve import RemoteRunnable
openai = RemoteRunnable("http://localhost:8000/openai/")
anthropic = RemoteRunnable("http://localhost:8000/anthropic/")
joke_chain = RemoteRunnable("http://localhost:8000/chain/")
joke_chain = RemoteRunnable("http://localhost:8000/joke/")
joke_chain.invoke({"topic": "parrots"})
@@ -116,18 +153,18 @@ joke_chain.invoke({"topic": "parrots"})
await joke_chain.ainvoke({"topic": "parrots"})
prompt = [
SystemMessage(content='Act like either a cat or a parrot.'),
SystemMessage(content='Act like either a cat or a parrot.'),
HumanMessage(content='Hello!')
]
# Supports astream
async for msg in anthropic.astream(prompt):
print(msg, end="", flush=True)
prompt = ChatPromptTemplate.from_messages(
[("system", "Tell me a long story about {topic}")]
)
# Can define custom chains
chain = prompt | RunnableMap({
"openai": openai,
@@ -142,9 +179,11 @@ In TypeScript (requires LangChain.js version 0.0.166 or later):
```typescript
import { RemoteRunnable } from "langchain/runnables/remote";
const chain = new RemoteRunnable({ url: `http://localhost:8000/chain/invoke/` });
const chain = new RemoteRunnable({
url: `http://localhost:8000/joke/`,
});
const result = await chain.invoke({
"topic": "cats",
topic: "cats",
});
```
@@ -153,7 +192,7 @@ Python using `requests`:
```python
import requests
response = requests.post(
"http://localhost:8000/chain/invoke/",
"http://localhost:8000/joke/invoke/",
json={'input': {'topic': 'cats'}}
)
response.json()
@@ -162,7 +201,7 @@ response.json()
You can also use `curl`:
```sh
curl --location --request POST 'http://localhost:8000/chain/invoke/' \
curl --location --request POST 'http://localhost:8000/joke/invoke/' \
--header 'Content-Type: application/json' \
--data-raw '{
"input": {
@@ -171,8 +210,7 @@ curl --location --request POST 'http://localhost:8000/chain/invoke/' \
}'
```
## Endpoints
## Endpoints
The following code:
@@ -195,15 +233,27 @@ adds of these endpoints to the server:
- `GET /my_runnable/output_schema` - json schema for output of the runnable
- `GET /my_runnable/config_schema` - json schema for config of the runnable
## Installation
These endpoints match the [LangChain Expression Language interface](https://python.langchain.com/docs/expression_language/interface) -- please reference this documentation for more details.
For both client and server:
## Playground
```bash
pip install "langserve[all]"
```
You can find a playground page for your runnable at `/my_runnable/playground`. This exposes a simple UI to [configure](https://python.langchain.com/docs/expression_language/how_to/configure) and invoke your runnable with streaming output and intermediate steps.
or `pip install "langserve[client]"` for client code, and `pip install "langserve[server]"` for server code.
<p align="center">
<img src="https://github.com/langchain-ai/langserve/assets/3205522/5ca56e29-f1bb-40f4-84b5-15916384a276" width="50%"/>
</p>
### Widgets
The playground supports [widgets](#playground-widgets) and can be used to test your runnable with different inputs.
In addition, for configurable runnables, the playground will allow you to configure the runnable and share a link with the configuration:
### Sharing
<p align="center">
<img src="https://github.com/langchain-ai/langserve/assets/3205522/86ce9c59-f8e4-4d08-9fa3-62030e0f521d" width="50%"/>
</p>
## Legacy Chains
@@ -212,13 +262,6 @@ However, some of the input schemas for legacy chains may be incomplete/incorrect
This can be fixed by updating the `input_schema` property of those chains in LangChain.
If you encounter any errors, please open an issue on THIS repo, and we will work to address it.
## Handling Authentication
If you need to add authentication to your server,
please reference FastAPI's [security documentation](https://fastapi.tiangolo.com/tutorial/security/)
and [middleware documentation](https://fastapi.tiangolo.com/tutorial/middleware/).
## Deployment
### Deploy to GCP
@@ -228,3 +271,168 @@ You can deploy to GCP Cloud Run using the following command:
```
gcloud run deploy [your-service-name] --source . --port 8001 --allow-unauthenticated --region us-central1 --set-env-vars=OPENAI_API_KEY=your_key
```
## Pydantic
LangServe provides support for Pydantic 2 with some limitations.
1. OpenAPI docs will not be generated for invoke/batch/stream/stream_log when using Pydantic V2. Fast API does not support [mixing pydantic v1 and v2 namespaces].
2. LangChain uses the v1 namespace in Pydantic v2. Please read the [following guidelines to ensure compatibility with LangChain](https://github.com/langchain-ai/langchain/discussions/9337)
Except for these limitations, we expect the API endpoints, the playground and any other features to work as expected.
## Advanced
## Handling Authentication
If you need to add authentication to your server,
please reference FastAPI's [security documentation](https://fastapi.tiangolo.com/tutorial/security/)
and [middleware documentation](https://fastapi.tiangolo.com/tutorial/middleware/).
### Files
LLM applications often deal with files. There are different architectures
that can be made to implement file processing; at a high level:
1. The file may be uploaded to the server via a dedicated endpoint and processed using a separate endpoint
2. The file may be uploaded by either value (bytes of file) or reference (e.g., s3 url to file content)
3. The processing endpoint may be blocking or non-blocking
4. If significant processing is required, the processing may be offloaded to a dedicated process pool
You should determine what is the appropriate architecture for your application.
Currently, to upload files by value to a runnable, use base64 encoding for the
file (`multipart/form-data` is not supported yet).
Here's an [example](https://github.com/langchain-ai/langserve/tree/main/examples/file_processing) that shows
how to use base64 encoding to send a file to a remote runnable.
Remember, you can always upload files by reference (e.g., s3 url) or upload them as
multipart/form-data to a dedicated endpoint.
### Custom Input and Output Types
Input and Output types are defined on all runnables.
You can access them via the `input_schema` and `output_schema` properties.
`LangServe` uses these types for validation and documentation.
If you want to override the default inferred types, you can use the `with_types` method.
Here's a toy example to illustrate the idea:
```python
from typing import Any
from fastapi import FastAPI
from langchain.schema.runnable import RunnableLambda
app = FastAPI()
def func(x: Any) -> int:
"""Mistyped function that should accept an int but accepts anything."""
return x + 1
runnable = RunnableLambda(func).with_types(
input_schema=int,
)
add_routes(app, runnable)
```
### Custom User Types
Inherit from `CustomUserType` if you want the data to de-serialize into a
pydantic model rather than the equivalent dict representation.
At the moment, this type only works *server* side and is used
to specify desired *decoding* behavior. If inheriting from this type
the server will keep the decoded type as a pydantic model instead
of converting it into a dict.
```python
from fastapi import FastAPI
from langchain.schema.runnable import RunnableLambda
from langserve import add_routes
from langserve.schema import CustomUserType
app = FastAPI()
class Foo(CustomUserType):
bar: int
def func(foo: Foo) -> int:
"""Sample function that expects a Foo type which is a pydantic model"""
assert isinstance(foo, Foo)
return foo.bar
# Note that the input and output type are automatically inferred!
# You do not need to specify them.
# runnable = RunnableLambda(func).with_types( # <-- Not needed in this case
# input_schema=Foo,
# output_schema=int,
#
add_routes(app, RunnableLambda(func), path="/foo")
```
### Playground Widgets
The playground allows you to define custom widgets for your runnable from the backend.
- A widget is specified at the field level and shipped as part of the JSON schema of the input type
- A widget must contain a key called `type` with the value being one of a well known list of widgets
- Other widget keys will be associated with values that describe paths in a JSON object
General schema:
```typescript
type JsonPath = number | string | (number | string)[];
type NameSpacedPath = { title: string; path: JsonPath }; // Using title to mimick json schema, but can use namespace
type OneOfPath = { oneOf: JsonPath[] };
type Widget = {
type: string // Some well known type (e.g., base64file, chat etc.)
[key: string]: JsonPath | NameSpacedPath | OneOfPath;
};
```
#### File Upload Widget
Allows creation of a file upload input in the UI playground for files
that are uploaded as base64 encoded strings. Here's the full [example](https://github.com/langchain-ai/langserve/tree/main/examples/file_processing).
Snippet:
```python
try:
from pydantic.v1 import Field
except ImportError:
from pydantic import Field
from langserve import CustomUserType
# ATTENTION: Inherit from CustomUserType instead of BaseModel otherwise
# the server will decode it into a dict instead of a pydantic model.
class FileProcessingRequest(CustomUserType):
"""Request including a base64 encoded file."""
# The extra field is used to specify a widget for the playground UI.
file: str = Field(..., extra={"widget": {"type": "base64file"}})
num_chars: int = 100
```
Example widget:
<p align="center">
<img src="https://github.com/langchain-ai/langserve/assets/3205522/52199e46-9464-4c2e-8be8-222250e08c3f" width="50%"/>
</p>
+13 -17
View File
@@ -18,16 +18,19 @@
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"execution_count": 1,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"{'output': {'output': 'Eugene thinks that cats like fish.'}}"
"{'output': {'output': 'Eugene thinks that cats like fish.'},\n",
" 'callback_events': []}"
]
},
"execution_count": 7,
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
@@ -50,7 +53,7 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 2,
"metadata": {
"tags": []
},
@@ -70,7 +73,7 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 3,
"metadata": {
"tags": []
},
@@ -81,7 +84,7 @@
"{'output': 'Hello! How can I assist you today?'}"
]
},
"execution_count": 4,
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
@@ -92,7 +95,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 6,
"metadata": {
"tags": []
},
@@ -103,7 +106,7 @@
"{'output': 'Eugene thinks that cats like fish.'}"
]
},
"execution_count": 5,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
@@ -111,13 +114,6 @@
"source": [
"remote_runnable.invoke({\"input\": \"what does eugene think of cats?\"})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
@@ -136,7 +132,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.1"
"version": "3.9.6"
}
},
"nbformat": 4,
+2 -2
View File
@@ -7,9 +7,9 @@ from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser
from langchain.chat_models import ChatOpenAI
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.pydantic_v1 import BaseModel
from langchain.tools.render import format_tool_to_openai_function
from langchain.vectorstores import FAISS
from pydantic import BaseModel
from langserve import add_routes
@@ -74,7 +74,7 @@ class Output(BaseModel):
# /invoke
# /batch
# /stream
add_routes(app, agent_executor, input_type=Input, output_type=Output)
add_routes(app, agent_executor.with_types(input_type=Input, output_type=Output))
if __name__ == "__main__":
import uvicorn
-191
View File
@@ -1,191 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Client\n",
"\n",
"Demo of client interacting with the simple chain server, which deploys a chain that tells jokes about a particular topic."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can interact with this via API directly"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'output': {'content': \"Why don't scientists trust atoms when playing sports? \\n\\nBecause they make up everything!\",\n",
" 'additional_kwargs': {},\n",
" 'type': 'ai',\n",
" 'example': False}}"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import requests\n",
"\n",
"inputs = {\"input\": {\"topic\": \"sports\"}}\n",
"response = requests.post(\"http://localhost:8000/invoke\", json=inputs)\n",
"\n",
"response.json()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also interact with this via the RemoteRunnable interface (to use in other chains)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langserve import RemoteRunnable\n",
"\n",
"remote_runnable = RemoteRunnable(\"http://localhost:8000/\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Remote runnable has the same interface as local runnables"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"response = await remote_runnable.ainvoke({\"topic\": \"sports\"})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The client can also execute langchain code synchronously, and pass in configs"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"[AIMessage(content='Why did the football coach go to the bank?\\n\\nBecause he wanted to get his quarterback!', additional_kwargs={}, example=False),\n",
" AIMessage(content='Why did the car bring a sweater to the race?\\n\\nBecause it wanted to have a \"car-digan\" finish!', additional_kwargs={}, example=False)]"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from langchain.schema.runnable.config import RunnableConfig\n",
"\n",
"remote_runnable.batch([{\"topic\": \"sports\"}, {\"topic\": \"cars\"}])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The server supports streaming (using HTTP server-side events), which can help interact with long responses in real time"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Ah, indulge me in this lighthearted endeavor, dear interlocutor! Allow me to regale you with a rather verbose jest concerning our hirsute friends of the wilderness, the bears!\n",
"\n",
"Once upon a time, in the vast expanse of a verdant forest, there existed a most erudite and sagacious bear, renowned for his prodigious intellect and unabated curiosity. This bear, with his inquisitive disposition, embarked on a quest to uncover the secrets of humor, for he believed that laughter possessed the power to unite and uplift the spirits of all creatures, great and small.\n",
"\n",
"Upon his journey, our erudite bear encountered a group of mischievous woodland creatures, who, captivated by his exalted intelligence, dared to challenge him to create a jest that would truly encompass the majestic essence of the bear. Our sagacious bear, never one to back down from a challenge, took a moment to ponder, his profound thoughts swirling amidst the verdant canopy above.\n",
"\n",
"After much contemplation, the bear delivered his jest, thusly: \"Pray, dear friends, envision a most estimable gathering of bears, replete with their formidable bulk and majestic presence. In this symposium of ursine brilliance, one bear, with a prodigious appetite, sauntered forth to procure his daily sustenance. Alas, upon reaching his intended destination, he encountered a dapper gentleman, clad in a most resplendent suit, hitherto unseen in the realm of the forest.\n",
"\n",
"The gentleman, possessing an air of sophistication, addressed the bear with an air of candor, remarking, 'Good sir, I must confess that your corporeal form inspires awe and admiration in equal measure. However, I beseech you, kindly abstain from consuming the berries that grow in this territory, for they possess a most deleterious effect upon the digestive systems of bears.'\n",
"\n",
"In response, the bear, known for his indomitable spirit, replied in a most eloquent manner, 'Dearest sir, I appreciate your concern and your eloquent admonition, yet I must humbly convey that the allure of these succulent berries is simply irresistible. The culinary satisfaction they bring far outweighs the potential discomfort they may inflict upon my digestive faculties. Therefore, I am compelled to disregard your sage counsel and indulge in their delectable essence.'\n",
"\n",
"And so, dear listener, the bear, driven by his insatiable hunger, proceeded to relish the berries with unmitigated gusto, heedless of the gentleman's cautions. After partaking in his feast, the bear, much to his chagrin, soon discovered the veracity of the gentleman's warning, as his digestive faculties embarked upon an unrestrained journey of turmoil and trepidation.\n",
"\n",
"In the aftermath of his ill-fated indulgence, the bear, with a countenance of utmost regret, turned to the gentleman and uttered, 'Verily, good sir, your counsel was indeed sagacious and prescient. I find myself ensnared in a maelstrom of gastrointestinal distress, beseeching the heavens for respite from this discomfort.'\n",
"\n",
"And thus, dear interlocutor, we find ourselves at the crux of this jest, whereupon the bear, in his most vulnerable state, beseeches the heavens for relief from his gastrointestinal plight. In this moment of levity, we are reminded that even the most erudite and sagacious among us can succumb to the allure of temptation, and the consequences that follow serve as a timeless lesson for all creatures within the realm of nature.\"\n",
"\n",
"Oh, the whimsy of the bear's gastronomic misadventure! May it serve as a reminder that, even amidst the grandeur of the natural world, we must exercise prudence and contemplate the ramifications of our actions."
]
}
],
"source": [
"async for chunk in remote_runnable.astream({\"topic\": \"bears, but super verbose\"}):\n",
" print(chunk.content, end=\"\", flush=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
-67
View File
@@ -1,67 +0,0 @@
#!/usr/bin/env python
"""Example LangChain server exposes a chain composed of a prompt and an LLM."""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate
# from typing_extensions import TypedDict
from langchain.pydantic_v1 import BaseModel
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import ConfigurableField
from langserve import add_routes
model = ChatOpenAI(temperature=0.5).configurable_alternatives(
ConfigurableField(id="llm", name="LLM"),
high_temp=ChatOpenAI(temperature=0.9),
low_temp=ChatOpenAI(temperature=0.1, max_tokens=1),
default_key="medium_temp",
)
prompt = PromptTemplate.from_template(
"tell me a joke about {topic}."
).configurable_fields(
template=ConfigurableField(
id="prompt",
name="Prompt",
description="The prompt to use. Must contain {topic}",
)
)
chain = prompt | model | StrOutputParser()
app = FastAPI(
title="LangChain Server",
version="1.0",
description="Spin up a simple api server using Langchain's Runnable interfaces",
)
# Set all CORS enabled origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"],
)
# The input type is automatically inferred from the runnable
# interface; however, if you want to override it, you can do so
# by passing in the input_type argument to add_routes.
class ChainInput(BaseModel):
"""The input to the chain."""
topic: str
add_routes(app, chain, input_type=ChainInput, config_keys=["configurable"])
# Alternatively, you can rely on langchain's type inference
# to infer the input type from the runnable interface.
# add_routes(app, chain)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="localhost", port=8000)
+289
View File
@@ -0,0 +1,289 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Client\n",
"\n",
"Demo of client interacting with the simple chain server, which deploys a chain that tells jokes about a particular topic."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can interact with this via API directly"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import requests\n",
"\n",
"inputs = {\"input\": {\"topic\": \"sports\"}}\n",
"response = requests.post(\"http://localhost:8000/configurable_temp/invoke\", json=inputs)\n",
"\n",
"response.json()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also interact with this via the RemoteRunnable interface (to use in other chains)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langserve import RemoteRunnable\n",
"\n",
"remote_runnable = RemoteRunnable(\"http://localhost:8000/configurable_temp\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Remote runnable has the same interface as local runnables"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"response = await remote_runnable.ainvoke({\"topic\": \"sports\"})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The client can also execute langchain code synchronously, and pass in configs"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain.schema.runnable.config import RunnableConfig\n",
"\n",
"remote_runnable.batch([{\"topic\": \"sports\"}, {\"topic\": \"cars\"}])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The server supports streaming (using HTTP server-side events), which can help interact with long responses in real time"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"async for chunk in remote_runnable.astream({\"topic\": \"bears, but a bit verbose\"}):\n",
" print(chunk, end=\"\", flush=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Configurability\n",
"\n",
"The server chains have been exposed as configurable chains!\n",
"\n",
"```python \n",
"\n",
"model = ChatOpenAI(temperature=0.5).configurable_alternatives(\n",
" ConfigurableField(\n",
" id=\"llm\",\n",
" name=\"LLM\",\n",
" description=(\n",
" \"Decide whether to use a high or a low temperature parameter for the LLM.\"\n",
" ),\n",
" ),\n",
" high_temp=ChatOpenAI(temperature=0.9),\n",
" low_temp=ChatOpenAI(temperature=0.1),\n",
" default_key=\"medium_temp\",\n",
")\n",
"prompt = PromptTemplate.from_template(\n",
" \"tell me a joke about {topic}.\"\n",
").configurable_fields( # Example of a configurable field\n",
" template=ConfigurableField(\n",
" id=\"prompt\",\n",
" name=\"Prompt\",\n",
" description=(\"The prompt to use. Must contain {topic}.\"),\n",
" )\n",
")\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can now use the configurability of the runnable in the API!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"await remote_runnable.ainvoke(\n",
" {\"topic\": \"sports\"},\n",
" config={\n",
" \"configurable\": {\"prompt\": \"how to say {topic} in french\", \"llm\": \"low_temp\"}\n",
" },\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Configurability Based on Request Properties\n",
"\n",
"If you want to change your chain invocation based on your request's properties,\n",
"you can do so with `add_routes`'s `per_req_config_modifier` method as follows:\n",
"\n",
"```python \n",
"\n",
"# Add another example route where you can configure the model based\n",
"# on properties of the request. This is useful for passing in API\n",
"# keys from request headers (WITH CAUTION) or using other properties\n",
"# of the request to configure the model.\n",
"def fetch_api_key_from_header(config: Dict[str, Any], req: Request) -> Dict[str, Any]:\n",
" if \"x-api-key\" in req.headers:\n",
" config[\"configurable\"][\"openai_api_key\"] = req.headers[\"x-api-key\"]\n",
" return config\n",
"\n",
"dynamic_auth_model = ChatOpenAI(openai_api_key='placeholder').configurable_fields(\n",
" openai_api_key=ConfigurableField(\n",
" id=\"openai_api_key\",\n",
" name=\"OpenAI API Key\",\n",
" description=(\n",
" \"API Key for OpenAI interactions\"\n",
" ),\n",
" ),\n",
")\n",
"\n",
"dynamic_auth_chain = dynamic_auth_model | StrOutputParser()\n",
"\n",
"add_routes(\n",
" app, \n",
" dynamic_auth_chain, \n",
" path=\"/auth_from_header\",\n",
" config_keys=[\"configurable\"], \n",
" per_req_config_modifier=fetch_api_key_from_header\n",
")\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, we can see that our request to the model will only work if we have a specific request\n",
"header set:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The model will fail with an auth error\n",
"unauthenticated_response = requests.post(\n",
" \"http://localhost:8000/auth_from_header/invoke\", json={\"input\": \"hello\"}\n",
")\n",
"unauthenticated_response.json()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, ensure that you have run the following locally on your shell\n",
"```bash\n",
"export TEST_API_KEY=<INSERT MY KEY HERE>\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The model will succeed as long as the above shell script is run previously\n",
"import os\n",
"\n",
"test_key = os.environ[\"TEST_API_KEY\"]\n",
"authenticated_response = requests.post(\n",
" \"http://localhost:8000/auth_from_header/invoke\",\n",
" json={\"input\": \"hello\"},\n",
" headers={\"x-api-key\": test_key},\n",
")\n",
"authenticated_response.json()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.9.18"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python
"""Example of configurable runnables.
This example shows how to use two options for configuration of runnables:
1) Configurable Fields: Use this to specify values for a given initialization parameter
2) Configurable Alternatives: Use this to specify complete alternative runnables
"""
from typing import Any, Dict
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import ConfigurableField
from langserve import add_routes
app = FastAPI(
title="LangChain Server",
version="1.0",
description="Spin up a simple api server using Langchain's Runnable interfaces",
)
# Set all CORS enabled origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"],
)
###############################################################################
# EXAMPLE 1: Configure fields based on RunnableConfig #
###############################################################################
model = ChatOpenAI(temperature=0.5).configurable_alternatives(
ConfigurableField(
id="llm",
name="LLM",
description=(
"Decide whether to use a high or a low temperature parameter for the LLM."
),
),
high_temp=ChatOpenAI(temperature=0.9),
low_temp=ChatOpenAI(temperature=0.1),
default_key="medium_temp",
)
prompt = PromptTemplate.from_template(
"tell me a joke about {topic}."
).configurable_fields( # Example of a configurable field
template=ConfigurableField(
id="prompt",
name="Prompt",
description="The prompt to use. Must contain {topic}.",
)
)
chain = prompt | model | StrOutputParser()
add_routes(app, chain, path="/configurable_temp")
###############################################################################
# EXAMPLE 2: Configure fields based on Request metadata #
###############################################################################
# Add another example route where you can configure the model based
# on properties of the request. This is useful for passing in API
# keys from request headers (WITH CAUTION) or using other properties
# of the request to configure the model.
def fetch_api_key_from_header(config: Dict[str, Any], req: Request) -> Dict[str, Any]:
if "x-api-key" in req.headers:
config["configurable"]["openai_api_key"] = req.headers["x-api-key"]
else:
raise HTTPException(401, "No API key provided")
return config
dynamic_auth_model = ChatOpenAI(openai_api_key="placeholder").configurable_fields(
openai_api_key=ConfigurableField(
id="openai_api_key",
name="OpenAI API Key",
description=("API Key for OpenAI interactions"),
),
)
dynamic_auth_chain = dynamic_auth_model | StrOutputParser()
add_routes(
app,
dynamic_auth_chain,
path="/auth_from_header",
per_req_config_modifier=fetch_api_key_from_header,
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="localhost", port=8000)
@@ -18,16 +18,23 @@
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"execution_count": 11,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"{'output': {'answer': 'Cats like fish.'}}"
"{'output': {'content': 'Based on the given context, the information we have about Harrison is that he worked at Kensho.',\n",
" 'additional_kwargs': {},\n",
" 'type': 'ai',\n",
" 'example': False},\n",
" 'callback_events': [],\n",
" 'metadata': {'run_id': '3455df2b-93f8-4e67-b1a3-27f90670cf7b'}}"
]
},
"execution_count": 2,
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
@@ -35,7 +42,7 @@
"source": [
"import requests\n",
"\n",
"inputs = {\"input\": {\"question\": \"what do cats like?\", \"chat_history\": \"\"}}\n",
"inputs = {\"input\": {\"question\": \"what do you know about harrison\", \"chat_history\": []}}\n",
"response = requests.post(\"http://localhost:8000/invoke\", json=inputs)\n",
"\n",
"response.json()"
@@ -50,7 +57,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 12,
"metadata": {
"tags": []
},
@@ -70,7 +77,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 13,
"metadata": {
"tags": []
},
@@ -78,21 +85,21 @@
{
"data": {
"text/plain": [
"{'answer': 'Cats like fish.'}"
"AIMessage(content='Based on the given context, the only information we have about Harrison is that he worked at Kensho.')"
]
},
"execution_count": 7,
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"await remote_runnable.ainvoke({\"question\": \"what do cats like?\", \"chat_history\": \"\"})"
"await remote_runnable.ainvoke({\"question\": \"what do you know about harrison\", \"chat_history\": []})"
]
},
{
"cell_type": "code",
"execution_count": 10,
"execution_count": 14,
"metadata": {
"tags": []
},
@@ -100,26 +107,501 @@
{
"data": {
"text/plain": [
"{'answer': 'Cats like fish.'}"
"AIMessage(content='Harrison worked at Kensho.')"
]
},
"execution_count": 10,
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"await remote_runnable.ainvoke(\n",
" {\"question\": \"what do cats like?\", \"chat_history\": [(\"hi\", \"hi\")]}\n",
" {\"question\": \"what do you know about harrison\", \"chat_history\": [(\"hi\", \"hi\")]}\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 16,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"content=''\n",
"content='H'\n",
"content='arrison'\n",
"content=' worked'\n",
"content=' at'\n",
"content=' Kens'\n",
"content='ho'\n",
"content='.'\n",
"content=''\n"
]
}
],
"source": [
"async for chunk in remote_runnable.astream(\n",
" {\"question\": \"what do you know about harrison\", \"chat_history\": [(\"hi\", \"hi\")]}\n",
"):\n",
" print(chunk)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"outputs": [],
"source": []
"source": [
"stream log shows all intermediate steps as well!"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"RunLogPatch({'op': 'replace',\n",
" 'path': '',\n",
" 'value': {'final_output': None,\n",
" 'id': '2ff5a98d-49f0-40ae-92fe-489c3047d1c3',\n",
" 'logs': {},\n",
" 'streamed_output': []}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/RunnableParallel',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': 'ffdda3c9-a0ba-49a6-af18-c01748c31801',\n",
" 'metadata': {},\n",
" 'name': 'RunnableParallel',\n",
" 'start_time': '2023-11-16T15:59:23.348',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['seq:step:1'],\n",
" 'type': 'chain'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/RunnableSequence',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': 'a9da3f2c-f3ae-44c1-a2f4-1035faa0d1c2',\n",
" 'metadata': {},\n",
" 'name': 'RunnableSequence',\n",
" 'start_time': '2023-11-16T15:59:23.349',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['map:key:standalone_question'],\n",
" 'type': 'chain'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/RunnableParallel:2',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': '4d32b08f-a989-4c01-8068-479bed506d99',\n",
" 'metadata': {},\n",
" 'name': 'RunnableParallel',\n",
" 'start_time': '2023-11-16T15:59:23.349',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['seq:step:1'],\n",
" 'type': 'chain'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/<lambda>',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': 'c7b9bd78-cbb4-41f9-b31a-50a5f8940a8d',\n",
" 'metadata': {},\n",
" 'name': '<lambda>',\n",
" 'start_time': '2023-11-16T15:59:23.350',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['map:key:chat_history'],\n",
" 'type': 'chain'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/<lambda>/final_output',\n",
" 'value': {'output': '\\nHuman: hi\\nAssistant: hi'}},\n",
" {'op': 'add',\n",
" 'path': '/logs/<lambda>/end_time',\n",
" 'value': '2023-11-16T15:59:23.350'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/RunnableParallel:2/final_output',\n",
" 'value': {'chat_history': '\\nHuman: hi\\nAssistant: hi'}},\n",
" {'op': 'add',\n",
" 'path': '/logs/RunnableParallel:2/end_time',\n",
" 'value': '2023-11-16T15:59:23.351'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/PromptTemplate',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': 'ef9f8729-2d4a-4887-86a8-a284d64f5882',\n",
" 'metadata': {},\n",
" 'name': 'PromptTemplate',\n",
" 'start_time': '2023-11-16T15:59:23.351',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['seq:step:2'],\n",
" 'type': 'prompt'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/PromptTemplate/final_output',\n",
" 'value': StringPromptValue(text='Given the following conversation and a follow up question, rephrase the \\nfollow up question to be a standalone question, in its original language.\\n\\nChat History:\\n\\nHuman: hi\\nAssistant: hi\\nFollow Up Input: what do you know about harrison\\nStandalone question:')},\n",
" {'op': 'add',\n",
" 'path': '/logs/PromptTemplate/end_time',\n",
" 'value': '2023-11-16T15:59:23.351'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': '7cda5923-ed2a-42ea-aee7-a2391371ff2f',\n",
" 'metadata': {},\n",
" 'name': 'ChatOpenAI',\n",
" 'start_time': '2023-11-16T15:59:23.352',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['seq:step:3'],\n",
" 'type': 'llm'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/StrOutputParser',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': '6a0e199d-51fa-4306-8a7d-054444c6855f',\n",
" 'metadata': {},\n",
" 'name': 'StrOutputParser',\n",
" 'start_time': '2023-11-16T15:59:24.613',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['seq:step:4'],\n",
" 'type': 'parser'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/RunnableParallel:3',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': '74a13de1-c2d1-43c0-813a-7ce0246118b3',\n",
" 'metadata': {},\n",
" 'name': 'RunnableParallel',\n",
" 'start_time': '2023-11-16T15:59:24.616',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['seq:step:2'],\n",
" 'type': 'chain'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/RunnableSequence:2',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': '625e2183-7ee5-4f1f-8f47-56541afc96ee',\n",
" 'metadata': {},\n",
" 'name': 'RunnableSequence',\n",
" 'start_time': '2023-11-16T15:59:24.619',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['map:key:context'],\n",
" 'type': 'chain'}})\n",
"RunLogPatch({'op': 'add', 'path': '/logs/ChatOpenAI/streamed_output_str/-', 'value': ''})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI/streamed_output_str/-',\n",
" 'value': 'What'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI/streamed_output_str/-',\n",
" 'value': ' information'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI/streamed_output_str/-',\n",
" 'value': ' do'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI/streamed_output_str/-',\n",
" 'value': ' you'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI/streamed_output_str/-',\n",
" 'value': ' have'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI/streamed_output_str/-',\n",
" 'value': ' about'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI/streamed_output_str/-',\n",
" 'value': ' Harrison'})\n",
"RunLogPatch({'op': 'add', 'path': '/logs/ChatOpenAI/streamed_output_str/-', 'value': '?'})\n",
"RunLogPatch({'op': 'add', 'path': '/logs/ChatOpenAI/streamed_output_str/-', 'value': ''})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI/final_output',\n",
" 'value': LLMResult(generations=[[ChatGenerationChunk(text='What information do you have about Harrison?', generation_info={'finish_reason': 'stop'}, message=AIMessageChunk(content='What information do you have about Harrison?'))]], llm_output=None, run=None)},\n",
" {'op': 'add',\n",
" 'path': '/logs/ChatOpenAI/end_time',\n",
" 'value': '2023-11-16T15:59:24.832'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/StrOutputParser/final_output',\n",
" 'value': {'output': 'What information do you have about Harrison?'}},\n",
" {'op': 'add',\n",
" 'path': '/logs/StrOutputParser/end_time',\n",
" 'value': '2023-11-16T15:59:24.833'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/RunnableSequence/final_output',\n",
" 'value': {'output': 'What information do you have about Harrison?'}},\n",
" {'op': 'add',\n",
" 'path': '/logs/RunnableSequence/end_time',\n",
" 'value': '2023-11-16T15:59:24.834'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/RunnableParallel/final_output',\n",
" 'value': {'standalone_question': 'What information do you have about '\n",
" 'Harrison?'}},\n",
" {'op': 'add',\n",
" 'path': '/logs/RunnableParallel/end_time',\n",
" 'value': '2023-11-16T15:59:24.835'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/RunnableLambda',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': '71b2e8dc-753f-4bf2-83de-b87b26828370',\n",
" 'metadata': {},\n",
" 'name': 'RunnableLambda',\n",
" 'start_time': '2023-11-16T15:59:24.837',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['seq:step:1'],\n",
" 'type': 'chain'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/RunnableLambda/final_output',\n",
" 'value': {'output': 'What information do you have about Harrison?'}},\n",
" {'op': 'add',\n",
" 'path': '/logs/RunnableLambda/end_time',\n",
" 'value': '2023-11-16T15:59:24.837'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/Retriever',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': 'd3d6254d-d073-478f-b00b-bc27eafa24fd',\n",
" 'metadata': {},\n",
" 'name': 'Retriever',\n",
" 'start_time': '2023-11-16T15:59:24.839',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['seq:step:2', 'FAISS', 'OpenAIEmbeddings'],\n",
" 'type': 'retriever'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/<lambda>:2',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': '77f7132a-d98f-4121-89cf-10e462c26496',\n",
" 'metadata': {},\n",
" 'name': '<lambda>',\n",
" 'start_time': '2023-11-16T15:59:24.839',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['map:key:question'],\n",
" 'type': 'chain'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/<lambda>:2/final_output',\n",
" 'value': {'output': 'What information do you have about Harrison?'}},\n",
" {'op': 'add',\n",
" 'path': '/logs/<lambda>:2/end_time',\n",
" 'value': '2023-11-16T15:59:24.840'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/Retriever/final_output',\n",
" 'value': {'documents': [Document(page_content='harrison worked at kensho')]}},\n",
" {'op': 'add',\n",
" 'path': '/logs/Retriever/end_time',\n",
" 'value': '2023-11-16T15:59:25.074'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/_combine_documents',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': '82aecf3e-ca9d-4b48-a281-03f8e834ea62',\n",
" 'metadata': {},\n",
" 'name': '_combine_documents',\n",
" 'start_time': '2023-11-16T15:59:25.075',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['seq:step:3'],\n",
" 'type': 'chain'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/_combine_documents/final_output',\n",
" 'value': {'output': 'harrison worked at kensho'}},\n",
" {'op': 'add',\n",
" 'path': '/logs/_combine_documents/end_time',\n",
" 'value': '2023-11-16T15:59:25.075'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/RunnableSequence:2/final_output',\n",
" 'value': {'output': 'harrison worked at kensho'}},\n",
" {'op': 'add',\n",
" 'path': '/logs/RunnableSequence:2/end_time',\n",
" 'value': '2023-11-16T15:59:25.075'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/RunnableParallel:3/final_output',\n",
" 'value': {'context': 'harrison worked at kensho',\n",
" 'question': 'What information do you have about Harrison?'}},\n",
" {'op': 'add',\n",
" 'path': '/logs/RunnableParallel:3/end_time',\n",
" 'value': '2023-11-16T15:59:25.076'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatPromptTemplate',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': 'b37f36ce-3a27-4402-81c4-6893f03ec179',\n",
" 'metadata': {},\n",
" 'name': 'ChatPromptTemplate',\n",
" 'start_time': '2023-11-16T15:59:25.076',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['seq:step:3'],\n",
" 'type': 'prompt'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatPromptTemplate/final_output',\n",
" 'value': {'messages': [HumanMessage(content='Answer the question based only on the following context:\\nharrison worked at kensho\\n\\nQuestion: What information do you have about Harrison?\\n')]}},\n",
" {'op': 'add',\n",
" 'path': '/logs/ChatPromptTemplate/end_time',\n",
" 'value': '2023-11-16T15:59:25.077'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2',\n",
" 'value': {'end_time': None,\n",
" 'final_output': None,\n",
" 'id': 'b1179088-eb7c-49c5-af1e-bd09c48408bf',\n",
" 'metadata': {},\n",
" 'name': 'ChatOpenAI',\n",
" 'start_time': '2023-11-16T15:59:25.078',\n",
" 'streamed_output_str': [],\n",
" 'tags': ['seq:step:4'],\n",
" 'type': 'llm'}})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content='')})\n",
"RunLogPatch({'op': 'add', 'path': '/logs/ChatOpenAI:2/streamed_output_str/-', 'value': ''})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content='Based')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': 'Based'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' on')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' on'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' the')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' the'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' given')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' given'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' context')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' context'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=',')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ','})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' the')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' the'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' only')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' only'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' information')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' information'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' we')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' we'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' have')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' have'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' about')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' about'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' Harrison')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' Harrison'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' is')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' is'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' that')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' that'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' he')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' he'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' worked')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' worked'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' at')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' at'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content=' Kens')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': ' Kens'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content='ho')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': 'ho'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content='.')})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/streamed_output_str/-',\n",
" 'value': '.'})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/streamed_output/-',\n",
" 'value': AIMessageChunk(content='')})\n",
"RunLogPatch({'op': 'add', 'path': '/logs/ChatOpenAI:2/streamed_output_str/-', 'value': ''})\n",
"RunLogPatch({'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/final_output',\n",
" 'value': LLMResult(generations=[[ChatGenerationChunk(text='Based on the given context, the only information we have about Harrison is that he worked at Kensho.', generation_info={'finish_reason': 'stop'}, message=AIMessageChunk(content='Based on the given context, the only information we have about Harrison is that he worked at Kensho.'))]], llm_output=None, run=None)},\n",
" {'op': 'add',\n",
" 'path': '/logs/ChatOpenAI:2/end_time',\n",
" 'value': '2023-11-16T15:59:26.547'})\n",
"RunLogPatch({'op': 'replace',\n",
" 'path': '/final_output',\n",
" 'value': {'output': AIMessageChunk(content='Based on the given context, the only information we have about Harrison is that he worked at Kensho.')}})\n"
]
}
],
"source": [
"async for chunk in remote_runnable.astream_log(\n",
" {\"question\": \"what do you know about harrison\", \"chat_history\": [(\"hi\", \"hi\")]}\n",
"):\n",
" print(chunk)"
]
}
],
"metadata": {
@@ -138,7 +620,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.1"
"version": "3.9.6"
}
},
"nbformat": 4,
@@ -1,21 +1,99 @@
#!/usr/bin/env python
"""Example LangChain server exposes a conversational retrieval chain."""
"""Example LangChain server exposes a conversational retrieval chain.
Follow the reference here:
https://python.langchain.com/docs/expression_language/cookbook/retrieval#conversational-retrieval-chain
To run this example, you will need to install the following packages:
pip install langchain openai faiss-cpu tiktoken
""" # noqa: F401
from operator import itemgetter
from typing import List, Tuple
from fastapi import FastAPI
from langchain.chains import ConversationalRetrievalChain
from langchain.chat_models import ChatOpenAI
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts import ChatPromptTemplate
from langchain.prompts.prompt import PromptTemplate
from langchain.schema import format_document
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import RunnableMap, RunnablePassthrough
from langchain.vectorstores import FAISS
from langserve import add_routes
from langserve.pydantic_v1 import BaseModel, Field
_TEMPLATE = """Given the following conversation and a follow up question, rephrase the
follow up question to be a standalone question, in its original language.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:"""
CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_TEMPLATE)
ANSWER_TEMPLATE = """Answer the question based only on the following context:
{context}
Question: {question}
"""
ANSWER_PROMPT = ChatPromptTemplate.from_template(ANSWER_TEMPLATE)
DEFAULT_DOCUMENT_PROMPT = PromptTemplate.from_template(template="{page_content}")
def _combine_documents(
docs, document_prompt=DEFAULT_DOCUMENT_PROMPT, document_separator="\n\n"
):
"""Combine documents into a single string."""
doc_strings = [format_document(doc, document_prompt) for doc in docs]
return document_separator.join(doc_strings)
def _format_chat_history(chat_history: List[Tuple]) -> str:
"""Format chat history into a string."""
buffer = ""
for dialogue_turn in chat_history:
human = "Human: " + dialogue_turn[0]
ai = "Assistant: " + dialogue_turn[1]
buffer += "\n" + "\n".join([human, ai])
return buffer
vectorstore = FAISS.from_texts(
["cats like fish", "dogs like sticks"], embedding=OpenAIEmbeddings()
["harrison worked at kensho"], embedding=OpenAIEmbeddings()
)
retriever = vectorstore.as_retriever()
model = ChatOpenAI()
_inputs = RunnableMap(
standalone_question=RunnablePassthrough.assign(
chat_history=lambda x: _format_chat_history(x["chat_history"])
)
| CONDENSE_QUESTION_PROMPT
| ChatOpenAI(temperature=0)
| StrOutputParser(),
)
_context = {
"context": itemgetter("standalone_question") | retriever | _combine_documents,
"question": lambda x: x["standalone_question"],
}
chain = ConversationalRetrievalChain.from_llm(model, retriever)
# User input
class ChatHistory(BaseModel):
"""Chat history with the bot."""
chat_history: List[Tuple[str, str]] = Field(
...,
extra={"widget": {"type": "chat", "input": "question", "output": "answer"}},
)
question: str
conversational_qa_chain = _inputs | _context | ANSWER_PROMPT | ChatOpenAI()
chain = conversational_qa_chain.with_types(input_type=ChatHistory)
app = FastAPI(
title="LangChain Server",
+156
View File
@@ -0,0 +1,156 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# File processing\n",
"\n",
"This client will be uploading a PDF file to the langserve server which will read the PDF and extract content from the first page."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's load the file in base64 encoding:"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import base64\n",
"\n",
"with open(\"sample.pdf\", \"rb\") as f:\n",
" data = f.read()\n",
"\n",
"encoded_data = base64.b64encode(data).decode(\"utf-8\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using raw requests"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"{'output': 'If youre reading this you might be using LangServe 🦜🏓!\\n\\nThis is a sample PDF!\\n\\n\\x0c',\n",
" 'callback_events': []}"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import requests\n",
"\n",
"requests.post(\n",
" \"http://localhost:8000/pdf/invoke/\", json={\"input\": {\"file\": encoded_data}}\n",
").json()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using the SDK"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langserve import RemoteRunnable\n",
"\n",
"runnable = RemoteRunnable(\"http://localhost:8000/pdf/\")"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"'If youre reading this you might be using LangServe 🦜🏓!\\n\\nThis is a sample PDF!\\n\\n\\x0c'"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"runnable.invoke({\"file\": encoded_data})"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"['If youre reading this you might be using LangServe 🦜🏓!\\n\\nThis is a sample PDF!\\n\\n\\x0c',\n",
" 'If youre ']"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"runnable.batch([{\"file\": encoded_data}, {\"file\": encoded_data, \"num_chars\": 10}])"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Binary file not shown.
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python
"""Example that shows how to upload files and process files in the server.
This example uses a very simple architecture for dealing with file uploads
and processing.
The main issue with this approach is that processing is done in
the same process rather than offloaded to a process pool. A smaller
issue is that the base64 encoding incurs an additional encoding/decoding
overhead.
This example also specifies a "base64file" widget, which will create a widget
allowing one to upload a binary file using the langserve playground UI.
"""
import base64
from fastapi import FastAPI
from langchain.document_loaders.blob_loaders import Blob
from langchain.document_loaders.parsers.pdf import PDFMinerParser
from langchain.pydantic_v1 import Field
from langchain.schema.runnable import RunnableLambda
from langserve import CustomUserType, add_routes
app = FastAPI(
title="LangChain Server",
version="1.0",
description="Spin up a simple api server using Langchain's Runnable interfaces",
)
# ATTENTION: Inherit from CustomUserType instead of BaseModel otherwise
# the server will decode it into a dict instead of a pydantic model.
class FileProcessingRequest(CustomUserType):
"""Request including a base64 encoded file."""
# The extra field is used to specify a widget for the playground UI.
file: str = Field(..., extra={"widget": {"type": "base64file"}})
num_chars: int = 100
def _process_file(request: FileProcessingRequest) -> str:
"""Extract the text from the first page of the PDF."""
content = base64.b64decode(request.file.encode("utf-8"))
blob = Blob(data=content)
documents = list(PDFMinerParser().lazy_parse(blob))
content = documents[0].page_content
return content[: request.num_chars]
add_routes(
app,
RunnableLambda(_process_file).with_types(input_type=FileProcessingRequest),
config_keys=["configurable"],
path="/pdf",
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="localhost", port=8000)
+3 -8
View File
@@ -229,7 +229,7 @@
"metadata": {},
"outputs": [],
"source": [
"from langchain.schema.runnable import PutLocalVar, GetLocalVar"
"from langchain.schema.runnable import RunnablePassthrough"
]
},
{
@@ -266,13 +266,8 @@
")\n",
"\n",
"\n",
"chain = (\n",
" comedian_chain\n",
" | PutLocalVar(\"joke\")\n",
" | {\"joke\": GetLocalVar(\"joke\")}\n",
" | joke_classifier_chain\n",
" | PutLocalVar(\"classification\")\n",
" | {\"joke\": GetLocalVar(\"joke\"), \"classification\": GetLocalVar(\"classification\")}\n",
"chain = {\"joke\": comedian_chain} | RunnablePassthrough.assign(\n",
" classification=joke_classifier_chain\n",
")"
]
},
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python
"""Endpoint shows off available playground widgets."""
import base64
from json import dumps
from typing import Any, Dict, List, Tuple
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from langchain.document_loaders.blob_loaders import Blob
from langchain.document_loaders.parsers.pdf import PDFMinerParser
from langchain.pydantic_v1 import BaseModel, Field
from langchain.schema.messages import (
AIMessage,
BaseMessage,
FunctionMessage,
)
from langchain.schema.runnable import RunnableLambda
from langserve.server import add_routes
app = FastAPI(
title="LangChain Server",
version="1.0",
description="Spin up a simple api server using Langchain's Runnable interfaces",
)
# Set all CORS enabled origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"],
)
class ChatHistory(BaseModel):
chat_history: List[Tuple[str, str]] = Field(
...,
examples=[[("a", "aa")]],
extra={"widget": {"type": "chat", "input": "question", "output": "answer"}},
)
question: str
class ChatHistoryMessage(BaseModel):
chat_history: List[BaseMessage] = Field(
...,
extra={"widget": {"type": "chat", "input": "location", "output": "output"}},
)
location: str
class FileProcessingRequest(BaseModel):
file: bytes = Field(..., extra={"widget": {"type": "base64file"}})
num_chars: int = 100
def chat_with_bot(input: Dict[str, Any]) -> Dict[str, Any]:
"""Bot that repeats the question twice."""
return {
"answer": input["question"] * 2,
"woof": "its so bad to woof, meow is better",
}
def chat_message_bot(input: Dict[str, Any]) -> List[BaseMessage]:
"""Bot that repeats the question twice."""
return [
AIMessage(
content="",
additional_kwargs={
"function_call": {
"name": "get_weather",
"arguments": dumps({"location": input["location"]}),
}
},
),
FunctionMessage(name="get_weather", content='{"value": 32}'),
AIMessage(content=f"Weather in {input['location']}: 32"),
]
def process_file(input: Dict[str, Any]) -> str:
"""Extract the text from the first page of the PDF."""
content = base64.decodebytes(input["file"])
blob = Blob(data=content)
documents = list(PDFMinerParser().lazy_parse(blob))
content = documents[0].page_content
return content[: input["num_chars"]]
add_routes(
app,
RunnableLambda(chat_with_bot).with_types(input_type=ChatHistory),
config_keys=["configurable"],
path="/chat",
)
add_routes(
app,
RunnableLambda(process_file).with_types(input_type=FileProcessingRequest),
config_keys=["configurable"],
path="/pdf",
)
add_routes(
app,
RunnableLambda(chat_message_bot).with_types(input_type=ChatHistoryMessage),
config_keys=["configurable"],
path="/chat_message",
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="localhost", port=8000)
+7 -2
View File
@@ -1,7 +1,12 @@
"""Main entrypoint into package."""
"""Main entrypoint into package.
This is the ONLY public interface into the package. All other modules are
to be considered private and subject to change without notice.
"""
from langserve.client import RemoteRunnable
from langserve.schema import CustomUserType
from langserve.server import add_routes
from langserve.version import __version__
__all__ = ["RemoteRunnable", "add_routes", "__version__"]
__all__ = ["RemoteRunnable", "add_routes", "__version__", "CustomUserType"]
+475
View File
@@ -0,0 +1,475 @@
from __future__ import annotations
import uuid
from typing import Any, Dict, List, Optional, Sequence
from uuid import UUID
from langchain.callbacks.base import AsyncCallbackHandler
from langchain.callbacks.manager import (
BaseRunManager,
ahandle_event,
handle_event,
)
from langchain.schema import AgentAction, AgentFinish, BaseMessage, Document, LLMResult
from typing_extensions import TypedDict
class CallbackEventDict(TypedDict, total=False):
"""A dictionary representation of a callback event."""
type: str
parent_run_id: Optional[UUID]
run_id: UUID
class AsyncEventAggregatorCallback(AsyncCallbackHandler):
"""A callback handler that aggregates all the events that have been called.
This callback handler aggregates all the events that have been called placing
them in a single mutable list.
This callback handler is not threading safe, and is meant to be used in an async
context only.
"""
def __init__(self) -> None:
"""Get a list of all the callback events that have been called."""
super().__init__()
# Callback events is a mutable state that is used only in an async context,
# so it should be safe to mutate without the usage of a lock.
self.callback_events: List[CallbackEventDict] = []
def log_callback(self, event: CallbackEventDict) -> None:
"""Log the callback event."""
self.callback_events.append(event)
async def on_chat_model_start(
self,
serialized: Dict[str, Any],
messages: List[List[BaseMessage]],
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Any:
"""Attempt to serialize the callback event."""
self.log_callback(
{
"type": "on_chat_model_start",
"serialized": serialized,
"messages": messages,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"metadata": metadata,
"kwargs": kwargs,
}
)
async def on_chain_start(
self,
serialized: Dict[str, Any],
inputs: Dict[str, Any],
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> None:
"""Attempt to serialize the callback event."""
self.log_callback(
{
"type": "on_chain_start",
"serialized": serialized,
"inputs": inputs,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"metadata": metadata,
"kwargs": kwargs,
}
)
async def on_chain_end(
self,
outputs: Any,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
**kwargs: Any,
) -> None:
self.log_callback(
{
"type": "on_chain_end",
"outputs": outputs,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"kwargs": kwargs,
}
)
async def on_chain_error(
self,
error: BaseException,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
**kwargs: Any,
) -> None:
self.log_callback(
{
"type": "on_chain_error",
"error": error,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"kwargs": kwargs,
}
)
async def on_retriever_start(
self,
serialized: Dict[str, Any],
query: str,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> None:
self.log_callback(
{
"type": "on_retriever_start",
"serialized": serialized,
"query": query,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"metadata": metadata,
"kwargs": kwargs,
}
)
async def on_retriever_end(
self,
documents: Sequence[Document],
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
**kwargs: Any,
) -> None:
self.log_callback(
{
"type": "on_retriever_end",
"documents": documents,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"kwargs": kwargs,
}
)
async def on_retriever_error(
self,
error: BaseException,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
**kwargs: Any,
) -> None:
self.log_callback(
{
"type": "on_retriever_error",
"error": error,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"kwargs": kwargs,
}
)
async def on_tool_start(
self,
serialized: Dict[str, Any],
input_str: str,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> None:
self.log_callback(
{
"type": "on_tool_start",
"serialized": serialized,
"input_str": input_str,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"metadata": metadata,
"kwargs": kwargs,
}
)
async def on_tool_end(
self,
output: str,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
**kwargs: Any,
) -> None:
self.log_callback(
{
"type": "on_tool_end",
"output": output,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"kwargs": kwargs,
}
)
async def on_tool_error(
self,
error: BaseException,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
**kwargs: Any,
) -> None:
self.log_callback(
{
"type": "on_tool_error",
"error": error,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"kwargs": kwargs,
}
)
async def on_agent_action(
self,
action: AgentAction,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
**kwargs: Any,
) -> None:
self.log_callback(
{
"type": "on_agent_action",
"action": action,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"kwargs": kwargs,
}
)
async def on_agent_finish(
self,
finish: AgentFinish,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
**kwargs: Any,
) -> None:
self.log_callback(
{
"type": "on_agent_finish",
"finish": finish,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"kwargs": kwargs,
}
)
async def on_llm_start(
self,
serialized: Dict[str, Any],
prompts: List[str],
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> None:
self.log_callback(
{
"type": "on_llm_start",
"serialized": serialized,
"prompts": prompts,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"metadata": metadata,
"kwargs": kwargs,
}
)
async def on_llm_end(
self,
response: LLMResult,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
**kwargs: Any,
) -> None:
self.log_callback(
{
"type": "on_llm_end",
"response": response,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"kwargs": kwargs,
}
)
async def on_llm_error(
self,
error: BaseException,
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
**kwargs: Any,
) -> None:
self.log_callback(
{
"type": "on_llm_error",
"error": error,
"run_id": run_id,
"parent_run_id": parent_run_id,
"tags": tags,
"kwargs": kwargs,
}
)
def replace_uuids(
callback_events: Sequence[CallbackEventDict],
) -> List[CallbackEventDict]:
"""Replace uids in the event callbacks with new uids.
This function mutates the event callback events in place.
Args:
callback_events: A list of event callbacks.
"""
# Create a dictionary to store mappings from old UID to new UID
uid_mapping: dict = {}
updated_events = []
# Iterate through the list of event callbacks
for event in callback_events:
updated_event = event.copy()
# Replace UIDs in the 'run_id' field
if "run_id" in updated_event and updated_event["run_id"] is not None:
if updated_event["run_id"] not in uid_mapping:
# Generate a new UUID
new_uid = uuid.uuid4()
uid_mapping[updated_event["run_id"]] = new_uid
# Replace the old UID with the new one
updated_event["run_id"] = uid_mapping[updated_event["run_id"]]
# Replace UIDs in the 'parent_run_id' field if it's not None
if (
"parent_run_id" in updated_event
and updated_event["parent_run_id"] is not None
):
if updated_event["parent_run_id"] not in uid_mapping:
# Generate a new UUID
new_uid = uuid.uuid4()
uid_mapping[updated_event["parent_run_id"]] = new_uid
# Replace the old UID with the new one
updated_event["parent_run_id"] = uid_mapping[updated_event["parent_run_id"]]
updated_events.append(updated_event)
return updated_events
# Mapping from event name to ignore condition name
NAME_TO_IGNORE_CONDITION = {
"on_retry": "ignore_retry",
"on_text": None,
"on_agent_action": "ignore_agent",
"on_agent_finish": "ignore_agent",
"on_llm_start": "ignore_llm",
"on_llm_end": "ignore_llm",
"on_llm_error": "ignore_llm",
"on_chain_start": "ignore_chain",
"on_chain_end": "ignore_chain",
"on_chain_error": "ignore_chain",
"on_chat_model_start": "ignore_chat_model",
"on_tool_start": "ignore_agent",
"on_tool_end": "ignore_agent",
"on_tool_error": "ignore_agent",
"on_retriever_start": "ignore_retriever",
"on_retriever_end": "ignore_retriever",
"on_retriever_error": "ignore_retriever",
}
async def ahandle_callbacks(
callback_manager: BaseRunManager,
callback_events: Sequence[CallbackEventDict],
) -> None:
"""Invoke all the callback handlers with the given callback events."""
callback_events = replace_uuids(callback_events)
# 1. Do I need inheritable handlers
for event in callback_events:
if event["parent_run_id"] is None: # How do we make sure it's None!?
event["parent_run_id"] = callback_manager.run_id
event_data = {key: value for key, value in event.items() if key != "type"}
await ahandle_event(
# Unpacking like this may not work
callback_manager.handlers,
event["type"],
ignore_condition_name=NAME_TO_IGNORE_CONDITION.get(event["type"], None),
**event_data,
)
def handle_callbacks(
callback_manager: BaseRunManager,
callback_events: Sequence[CallbackEventDict],
) -> None:
"""Invoke all the callback handlers with the given callback events."""
callback_events = replace_uuids(callback_events)
for event in callback_events:
if event["parent_run_id"] is None: # How do we make sure it's None!?
event["parent_run_id"] = callback_manager.run_id
event_data = {key: value for key, value in event.items() if key != "type"}
handle_event(
# Unpacking like this may not work
callback_manager.handlers,
event["type"],
ignore_condition_name=NAME_TO_IGNORE_CONDITION.get(event["type"], None),
**event_data,
)
+269 -44
View File
@@ -1,8 +1,12 @@
from __future__ import annotations
import asyncio
import copy
import json
import logging
import weakref
from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache
from typing import (
Any,
AsyncIterator,
@@ -11,12 +15,17 @@ from typing import (
List,
Optional,
Sequence,
Tuple,
Union,
)
from urllib.parse import urljoin
import httpx
from httpx._types import AuthTypes, CertTypes, CookieTypes, HeaderTypes, VerifyTypes
from langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
)
from langchain.callbacks.tracers.log_stream import RunLogPatch
from langchain.load.dump import dumpd
from langchain.schema.runnable import Runnable
@@ -26,9 +35,16 @@ from langchain.schema.runnable.config import (
get_async_callback_manager_for_config,
get_callback_manager_for_config,
)
from langchain.schema.runnable.utils import Input, Output
from langchain.schema.runnable.utils import AddableDict, Input, Output
from langserve.serialization import simple_dumpd, simple_loads
from langserve.callbacks import CallbackEventDict, ahandle_callbacks, handle_callbacks
from langserve.serialization import (
Serializer,
WellKnownLCSerializer,
load_events,
)
logger = logging.getLogger(__name__)
def _without_callbacks(config: Optional[RunnableConfig]) -> RunnableConfig:
@@ -37,6 +53,35 @@ def _without_callbacks(config: Optional[RunnableConfig]) -> RunnableConfig:
return {k: v for k, v in _config.items() if k != "callbacks"}
@lru_cache(maxsize=1_000) # Will accommodate up to 1_000 different error messages
def _log_error_message_once(error_message: str) -> None:
"""Log an error message once."""
logger.error(error_message)
def _sanitize_request(request: httpx.Request) -> httpx.Request:
"""Remove sensitive headers from the request."""
accept_headers = {
"accept",
"content-type",
"user-agent",
"connection",
"content-length",
"accept-encoding",
"host",
}
new_headers = request.headers.copy()
for key, value in new_headers.items():
if key.lower() not in accept_headers:
new_headers[key] = "<redacted>"
else:
new_headers[key] = value
new_request = copy.copy(request)
new_request.headers = new_headers
return new_request
def _raise_for_status(response: httpx.Response) -> None:
"""Re-raise with a more informative message.
@@ -58,7 +103,7 @@ def _raise_for_status(response: httpx.Response) -> None:
raise httpx.HTTPStatusError(
message=message,
request=e.request,
request=_sanitize_request(e.request),
response=e.response,
)
@@ -94,6 +139,62 @@ def _close_clients(sync_client: httpx.Client, async_client: httpx.AsyncClient) -
asyncio.run(async_client.aclose())
def _raise_exception_from_data(data: str, request: httpx.Request) -> None:
"""Raise an httpx exception from the given error event data."""
try:
decoded_data = json.loads(data)
except json.JSONDecodeError:
raise httpx.HTTPStatusError(
message="invalid json in error event sent from server",
request=_sanitize_request(request),
response=httpx.Response(status_code=500, text=data),
)
raise httpx.HTTPStatusError(
message=decoded_data["message"],
request=_sanitize_request(request),
response=httpx.Response(
status_code=decoded_data["status_code"],
text=decoded_data["message"],
),
)
def _decode_response(
serializer: Serializer,
response: httpx.Response,
*,
is_batch: bool = False,
) -> Tuple[Any, Union[List[CallbackEventDict], List[List[CallbackEventDict]]]]:
"""Decode the response."""
_raise_for_status(response)
obj = response.json()
if not isinstance(obj, dict):
raise ValueError(f"Expected a dictionary, got {obj}")
if "output" not in obj:
raise ValueError("Key `output` not found in")
output = serializer.loadd(obj["output"])
if "callback_events" in obj:
if is_batch:
if not isinstance(obj["callback_events"], list):
raise ValueError(
f"Expected a list of callback events, got {obj['callback_events']}"
)
else:
callback_events = [
load_events(callback_events)
for callback_events in obj["callback_events"]
]
else:
callback_events = load_events(obj["callback_events"])
else:
callback_events = []
return output, callback_events
class RemoteRunnable(Runnable[Input, Output]):
"""A RemoteRunnable is a runnable that is executed on a remote server.
@@ -103,8 +204,6 @@ class RemoteRunnable(Runnable[Input, Output]):
- `batch` with `return_exceptions=True` since we do not support exception
translation from the server.
- Callbacks via the `config` argument as serialization of callbacks is not
supported.
"""
def __init__(
@@ -118,6 +217,7 @@ class RemoteRunnable(Runnable[Input, Output]):
verify: VerifyTypes = True,
cert: Optional[CertTypes] = None,
client_kwargs: Optional[Dict[str, Any]] = None,
use_server_callback_events: bool = True,
) -> None:
"""Initialize the client.
@@ -130,7 +230,9 @@ class RemoteRunnable(Runnable[Input, Output]):
verify: Whether to verify SSL certificates
cert: SSL certificate to use for requests
client_kwargs: If provided will be unpacked as kwargs to both the sync
and async httpx clients
and async httpx clients
use_server_callback_events: Whether to invoke callbacks on any
callback events returned by the server.
"""
_client_kwargs = client_kwargs or {}
self.url = url
@@ -157,21 +259,32 @@ class RemoteRunnable(Runnable[Input, Output]):
# Register cleanup handler once RemoteRunnable is garbage collected
weakref.finalize(self, _close_clients, self.sync_client, self.async_client)
self._lc_serializer = WellKnownLCSerializer()
self._use_server_callback_events = use_server_callback_events
def _invoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
self,
input: Input,
run_manager: CallbackManagerForChainRun,
config: Optional[RunnableConfig] = None,
**kwargs: Any,
) -> Output:
"""Invoke the runnable with the given input and config."""
response = self.sync_client.post(
"/invoke",
json={
"input": simple_dumpd(input),
"input": self._lc_serializer.dumpd(input),
"config": _without_callbacks(config),
"kwargs": kwargs,
},
)
_raise_for_status(response)
return simple_loads(response.text)["output"]
output, callback_events = _decode_response(
self._lc_serializer, response, is_batch=False
)
if self._use_server_callback_events and callback_events:
handle_callbacks(run_manager, callback_events)
return output
def invoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
@@ -181,18 +294,27 @@ class RemoteRunnable(Runnable[Input, Output]):
return self._call_with_config(self._invoke, input, config=config)
async def _ainvoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
self,
input: Input,
run_manager: AsyncCallbackManagerForChainRun,
config: Optional[RunnableConfig] = None,
**kwargs: Any,
) -> Output:
"""Invoke the runnable with the given input and config."""
response = await self.async_client.post(
"/invoke",
json={
"input": simple_dumpd(input),
"input": self._lc_serializer.dumpd(input),
"config": _without_callbacks(config),
"kwargs": kwargs,
},
)
_raise_for_status(response)
return simple_loads(response.text)["output"]
output, callback_events = _decode_response(
self._lc_serializer, response, is_batch=False
)
if self._use_server_callback_events and callback_events:
handle_callbacks(run_manager, callback_events)
return output
async def ainvoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
@@ -204,6 +326,7 @@ class RemoteRunnable(Runnable[Input, Output]):
def _batch(
self,
inputs: List[Input],
run_manager: List[CallbackManagerForChainRun],
config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,
*,
return_exceptions: bool = False,
@@ -224,13 +347,28 @@ class RemoteRunnable(Runnable[Input, Output]):
response = self.sync_client.post(
"/batch",
json={
"inputs": simple_dumpd(inputs),
"inputs": self._lc_serializer.dumpd(inputs),
"config": _config,
"kwargs": kwargs,
},
)
_raise_for_status(response)
return simple_loads(response.text)["output"]
outputs, corresponding_callback_events = _decode_response(
self._lc_serializer, response, is_batch=True
)
# Now handle callbacks if any were returned
if self._use_server_callback_events and corresponding_callback_events:
for run_manager_, callback_events in zip(
run_manager, corresponding_callback_events
):
handle_callbacks(run_manager_, callback_events)
return outputs
def _enforce_trailing_slash(self, url: str) -> str:
if url.endswith("/"):
return url
return url + "/"
def batch(
self,
@@ -245,6 +383,7 @@ class RemoteRunnable(Runnable[Input, Output]):
async def _abatch(
self,
inputs: List[Input],
run_manager: List[AsyncCallbackManagerForChainRun],
config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,
*,
return_exceptions: bool = False,
@@ -266,13 +405,27 @@ class RemoteRunnable(Runnable[Input, Output]):
response = await self.async_client.post(
"/batch",
json={
"inputs": simple_dumpd(inputs),
"inputs": self._lc_serializer.dumpd(inputs),
"config": _config,
"kwargs": kwargs,
},
)
_raise_for_status(response)
return simple_loads(response.text)["output"]
outputs, corresponding_callback_events = _decode_response(
self._lc_serializer, response, is_batch=True
)
# Now handle callbacks
if self._use_server_callback_events and corresponding_callback_events:
tasks = []
for run_manager_, callback_events in zip(
run_manager, corresponding_callback_events
):
tasks.append(ahandle_callbacks(run_manager_, callback_events))
# Execute coroutines concurrently
await asyncio.gather(*tasks)
return outputs
async def abatch(
self,
@@ -300,18 +453,19 @@ class RemoteRunnable(Runnable[Input, Output]):
callback_manager = get_callback_manager_for_config(config)
final_output: Optional[Output] = None
final_output_supported = True
run_manager = callback_manager.on_chain_start(
dumpd(self),
simple_dumpd(input),
self._lc_serializer.dumpd(input),
name=config.get("run_name"),
)
data = {
"input": simple_dumpd(input),
"input": self._lc_serializer.dumpd(input),
"config": _without_callbacks(config),
"kwargs": kwargs,
}
endpoint = urljoin(self.url, "stream")
endpoint = urljoin(self._enforce_trailing_slash(self.url), "stream")
try:
from httpx_sse import connect_sse
@@ -327,17 +481,48 @@ class RemoteRunnable(Runnable[Input, Output]):
) as event_source:
for sse in event_source.iter_sse():
if sse.event == "data":
chunk = simple_loads(sse.data)
chunk = self._lc_serializer.loads(sse.data)
if isinstance(chunk, dict):
# Any dict returned from streaming end point
# is assumed to follow additive semantics
# and will be converted to an AddableDict
# automatically
chunk = AddableDict(chunk)
yield chunk
if final_output:
final_output += chunk
else:
final_output = chunk
if final_output_supported:
# here we attempt to aggregate the final output
# from the stream.
# the final output is used for the final callback
# event (`on_chain_end`)
# Aggregating the final output is only supported
# if the output is additive (e.g., string or
# AddableDict, etc.)
# We attempt to aggregate it on best effort basis.
if final_output is None:
final_output = chunk
else:
try:
final_output = final_output + chunk
except TypeError:
final_output = None
final_output_supported = False
elif sse.event == "error":
# This can only be a server side error
_raise_exception_from_data(
sse.data, httpx.Request(method="POST", url=endpoint)
)
elif sse.event == "metadata":
# Nothing to do for metadata for the regular remote client.
continue
elif sse.event == "end":
break
else:
raise NotImplementedError(f"Unknown event {sse.event}")
_log_error_message_once(
f"Encountered an unsupported event type: `{sse.event}`. "
f"Try upgrading the remote client to the latest version."
f"Ignoring events of type `{sse.event}`."
)
except BaseException as e:
run_manager.on_chain_error(e)
raise
@@ -354,18 +539,19 @@ class RemoteRunnable(Runnable[Input, Output]):
callback_manager = get_async_callback_manager_for_config(config)
final_output: Optional[Output] = None
final_output_supported = True
run_manager = await callback_manager.on_chain_start(
dumpd(self),
simple_dumpd(input),
self._lc_serializer.dumpd(input),
name=config.get("run_name"),
)
data = {
"input": simple_dumpd(input),
"input": self._lc_serializer.dumpd(input),
"config": _without_callbacks(config),
"kwargs": kwargs,
}
endpoint = urljoin(self.url, "stream")
endpoint = urljoin(self._enforce_trailing_slash(self.url), "stream")
try:
from httpx_sse import aconnect_sse
@@ -378,18 +564,49 @@ class RemoteRunnable(Runnable[Input, Output]):
) as event_source:
async for sse in event_source.aiter_sse():
if sse.event == "data":
chunk = simple_loads(sse.data)
chunk = self._lc_serializer.loads(sse.data)
if isinstance(chunk, dict):
# Any dict returned from streaming end point
# is assumed to follow additive semantics
# and will be converted to an AddableDict
# automatically
chunk = AddableDict(chunk)
yield chunk
if final_output:
final_output += chunk
else:
final_output = chunk
if final_output_supported:
# here we attempt to aggregate the final output
# from the stream.
# the final output is used for the final callback
# event (`on_chain_end`)
# Aggregating the final output is only supported
# if the output is additive (e.g., string or
# AddableDict, etc.)
# We attempt to aggregate it on best effort basis.
if final_output is None:
final_output = chunk
else:
try:
final_output = final_output + chunk
except TypeError:
final_output = None
final_output_supported = False
elif sse.event == "error":
# This can only be a server side error
_raise_exception_from_data(
sse.data, httpx.Request(method="POST", url=endpoint)
)
elif sse.event == "metadata":
# Nothing to do for metadata for the regular remote client.
continue
elif sse.event == "end":
break
else:
raise NotImplementedError(f"Unknown event {sse.event}")
_log_error_message_once(
f"Encountered an unsupported event type: `{sse.event}`. "
f"Try upgrading the remote client to the latest version."
f"Ignoring events of type `{sse.event}`."
)
except BaseException as e:
await run_manager.on_chain_error(e)
raise
@@ -428,11 +645,11 @@ class RemoteRunnable(Runnable[Input, Output]):
run_manager = await callback_manager.on_chain_start(
dumpd(self),
simple_dumpd(input),
self._lc_serializer.dumpd(input),
name=config.get("run_name"),
)
data = {
"input": simple_dumpd(input),
"input": self._lc_serializer.dumpd(input),
"config": _without_callbacks(config),
"kwargs": kwargs,
"diff": True,
@@ -456,19 +673,27 @@ class RemoteRunnable(Runnable[Input, Output]):
) as event_source:
async for sse in event_source.aiter_sse():
if sse.event == "data":
data = simple_loads(sse.data)
data = self._lc_serializer.loads(sse.data)
chunk = RunLogPatch(*data["ops"])
yield chunk
if final_output:
final_output += chunk
else:
final_output = chunk
elif sse.event == "error":
# This can only be a server side error
_raise_exception_from_data(
sse.data, httpx.Request(method="POST", url=endpoint)
)
elif sse.event == "end":
break
else:
raise NotImplementedError(f"Unknown event {sse.event}")
_log_error_message_once(
f"Encountered an unsupported event type: `{sse.event}`. "
f"Try upgrading the remote client to the latest version."
f"Ignoring events of type `{sse.event}`."
)
except BaseException as e:
await run_manager.on_chain_error(e)
raise
+36 -25
View File
@@ -2,15 +2,12 @@ import json
import mimetypes
import os
from string import Template
from typing import List, Type
from typing import Sequence, Type
from fastapi.responses import Response
from langchain.schema.runnable import Runnable
try:
from pydantic.v1 import BaseModel
except ImportError:
from pydantic import BaseModel
from langserve.pydantic_v1 import BaseModel
class PlaygroundTemplate(Template):
@@ -20,28 +17,42 @@ class PlaygroundTemplate(Template):
async def serve_playground(
runnable: Runnable,
input_schema: Type[BaseModel],
config_keys: List[str],
config_keys: Sequence[str],
base_url: str,
file_path: str,
) -> Response:
local_file_path = os.path.join(
os.path.dirname(__file__),
"./playground/dist",
file_path or "index.html",
"""Serve the playground."""
local_file_path = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
"./playground/dist",
file_path or "index.html",
)
)
with open(local_file_path) as f:
mime_type = mimetypes.guess_type(local_file_path)[0]
if mime_type in ("text/html", "text/css", "application/javascript"):
res = PlaygroundTemplate(f.read()).substitute(
LANGSERVE_BASE_URL=base_url[1:]
if base_url.startswith("/")
else base_url,
LANGSERVE_CONFIG_SCHEMA=json.dumps(
runnable.config_schema(include=config_keys).schema()
),
LANGSERVE_INPUT_SCHEMA=json.dumps(input_schema.schema()),
)
else:
res = f.buffer.read()
return Response(res, media_type=mime_type)
base_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), "./playground/dist")
)
if base_dir != os.path.commonpath((base_dir, local_file_path)):
return Response("Not Found", status_code=404)
try:
with open(local_file_path, encoding="utf-8") as f:
mime_type = mimetypes.guess_type(local_file_path)[0]
if mime_type in ("text/html", "text/css", "application/javascript"):
response = PlaygroundTemplate(f.read()).substitute(
LANGSERVE_BASE_URL=base_url[1:]
if base_url.startswith("/")
else base_url,
LANGSERVE_CONFIG_SCHEMA=json.dumps(
runnable.config_schema(include=config_keys).schema()
),
LANGSERVE_INPUT_SCHEMA=json.dumps(input_schema.schema()),
)
else:
response = f.buffer.read()
except FileNotFoundError:
return Response("Not Found", status_code=404)
return Response(response, media_type=mime_type)
+3 -1
View File
@@ -23,4 +23,6 @@ dist-ssr
*.sln
*.sw?
.yarn
.yarn
!dist
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -5,8 +5,8 @@
<link rel="icon" href="/____LANGSERVE_BASE_URL/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Playground</title>
<script type="module" crossorigin src="/____LANGSERVE_BASE_URL/assets/index-6c8f83bb.js"></script>
<link rel="stylesheet" href="/____LANGSERVE_BASE_URL/assets/index-5008c8a8.css">
<script type="module" crossorigin src="/____LANGSERVE_BASE_URL/assets/index-32c8d712.js"></script>
<link rel="stylesheet" href="/____LANGSERVE_BASE_URL/assets/index-c6cde0dd.css">
</head>
<body>
<div id="root"></div>
+2 -1
View File
@@ -20,15 +20,16 @@
"@mui/icons-material": "^5.14.11",
"@mui/material": "^5.14.11",
"@mui/x-date-pickers": "^6.16.0",
"@radix-ui/react-toggle-group": "^1.0.4",
"clsx": "^2.0.0",
"dayjs": "^1.11.10",
"fast-json-patch": "^3.1.1",
"json-schema-defaults": "^0.4.0",
"lodash": "^4.17.21",
"lz-string": "^1.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"tailwind-merge": "^1.14.0",
"use-debounce": "^9.0.4",
"vaul": "^0.7.3"
},
"devDependencies": {
+289 -185
View File
@@ -1,13 +1,11 @@
import "./App.css";
import React, { useEffect, useRef, useState } from "react";
import defaults from "json-schema-defaults";
import { useEffect, useMemo, useRef, useState } from "react";
import defaults from "./utils/defaults";
import { JsonForms } from "@jsonforms/react";
import {
materialAllOfControlTester,
MaterialAllOfRenderer,
materialAnyOfControlTester,
MaterialAnyOfRenderer,
MaterialObjectRenderer,
materialOneOfControlTester,
MaterialOneOfRenderer,
@@ -17,7 +15,6 @@ import utc from "dayjs/plugin/utc";
import relativeDate from "dayjs/plugin/relativeTime";
import SendIcon from "./assets/SendIcon.svg?react";
import ShareIcon from "./assets/ShareIcon.svg?react";
import ChevronRight from "./assets/ChevronRight.svg?react";
import { compressToEncodedURIComponent } from "lz-string";
import {
@@ -42,9 +39,10 @@ import {
vanillaRenderers,
InputControl,
} from "@jsonforms/vanilla-renderers";
import { useSchemas } from "./useSchemas";
import { RunState, useStreamLog } from "./useStreamLog";
import { useStreamLog } from "./useStreamLog";
import { StreamCallback } from "./types";
import { AppCallbackContext } from "./useStreamCallback";
import {
JsonFormsCore,
RankedTester,
@@ -59,18 +57,30 @@ import CustomArrayControlRenderer, {
} from "./components/CustomArrayControlRenderer";
import CustomTextAreaCell from "./components/CustomTextAreaCell";
import JsonTextAreaCell from "./components/JsonTextAreaCell";
import { cn } from "./utils/cn";
import { getStateFromUrl, ShareDialog } from "./components/ShareDialog";
import {
chatMessagesTester,
ChatMessagesControlRenderer,
} from "./components/ChatMessagesControlRenderer";
import {
ChatMessageTuplesControlRenderer,
chatMessagesTupleTester,
} from "./components/ChatMessageTuplesControlRenderer";
import {
fileBase64Tester,
FileBase64ControlRenderer,
} from "./components/FileBase64Tester";
import { IntermediateSteps } from "./components/IntermediateSteps";
import { StreamOutput } from "./components/StreamOutput";
import {
customAnyOfTester,
CustomAnyOfRenderer,
} from "./components/CustomAnyOfRenderer";
import { cn } from "./utils/cn";
dayjs.extend(relativeDate);
dayjs.extend(utc);
function str(o: unknown): React.ReactNode {
return typeof o === "object"
? JSON.stringify(o, null, 2)
: (o as React.ReactNode);
}
const isObjectWithPropertiesControl = rankWith(
2,
and(
@@ -85,26 +95,33 @@ const isObjectWithPropertiesControl = rankWith(
const isObject = rankWith(1, and(uiTypeIs("Control"), schemaTypeIs("object")));
const isElse = rankWith(1, and(uiTypeIs("Control")));
const renderers = [
export const renderers = [
...vanillaRenderers,
// use material renderers to handle objects and json schema references
// they should yield the rendering to simpler cells
{ tester: isObjectWithPropertiesControl, renderer: MaterialObjectRenderer },
{ tester: materialAllOfControlTester, renderer: MaterialAllOfRenderer },
{ tester: materialAnyOfControlTester, renderer: MaterialAnyOfRenderer },
{ tester: materialOneOfControlTester, renderer: MaterialOneOfRenderer },
{ tester: customAnyOfTester, renderer: CustomAnyOfRenderer },
// custom renderers
{ tester: materialArrayControlTester, renderer: CustomArrayControlRenderer },
{ tester: isObject, renderer: InputControl },
{ tester: chatMessagesTester, renderer: ChatMessagesControlRenderer },
{
tester: chatMessagesTupleTester,
renderer: ChatMessageTuplesControlRenderer,
},
{ tester: fileBase64Tester, renderer: FileBase64ControlRenderer },
];
const nestedArrayControlTester: RankedTester = rankWith(1, (_, jsonSchema) => {
return jsonSchema.type === "array";
});
const cells = [
export const cells = [
{ tester: booleanCellTester, cell: BooleanCell },
{ tester: dateCellTester, cell: DateCell },
{ tester: dateTimeCellTester, cell: DateTimeCell },
@@ -119,43 +136,10 @@ const cells = [
{ tester: isElse, cell: JsonTextAreaCell },
];
function IntermediateSteps(props: { latest: RunState }) {
const [expanded, setExpanded] = useState(false);
return (
<div className="flex flex-col border border-divider-700 rounded-2xl bg-background">
<button
className="font-medium text-left p-4 flex items-center justify-between"
onClick={() => setExpanded((open) => !open)}
>
<span>Intermediate steps</span>
<ChevronRight
className={cn("transition-all", expanded && "rotate-90")}
/>
</button>
{expanded && (
<div className="flex flex-col gap-5 p-4 pt-0 divide-solid divide-y divide-divider-700 rounded-b-xl">
{Object.values(props.latest.logs).map((log) => (
<div
className="gap-3 flex-col min-w-0 flex bg-background pt-3 first-of-type:pt-0"
key={log.id}
>
<div className="flex items-center justify-between">
<strong className="text-sm font-medium">{log.name}</strong>
<p className="text-sm">{dayjs.utc(log.start_time).fromNow()}</p>
</div>
<pre className="break-words whitespace-pre-wrap min-w-0 text-sm bg-ls-gray-400 rounded-lg p-3">
{str(log.final_output) ?? "..."}
</pre>
</div>
))}
</div>
)}
</div>
);
}
function App() {
const [isIframe] = useState(() => window.self !== window.top);
const [isEmbedded] = useState(() =>
window.location.search.includes("embeded=true")
);
// it is possible that defaults are being applied _after_
// the initial update message has been sent from the parent window
@@ -164,14 +148,14 @@ function App() {
// store form state
const [configData, setConfigData] = useState<
Pick<JsonFormsCore, "data" | "errors">
>({ data: {}, errors: [] });
Pick<JsonFormsCore, "data" | "errors"> & { defaults: boolean }
>({ data: {}, errors: [], defaults: true });
const [inputData, setInputData] = useState<
Pick<JsonFormsCore, "data" | "errors">
>({ data: null, errors: [] });
// fetch input and config schemas from the server
const schemas = useSchemas();
const schemas = useSchemas(configData);
// apply defaults defined in each schema
useEffect(() => {
if (schemas.config) {
@@ -182,13 +166,39 @@ function App() {
initConfigData.current ??
defaults(schemas.config),
errors: [],
defaults: true,
});
setInputData({ data: null, errors: [] });
setInputData({ data: defaults(schemas.input), errors: [] });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [schemas.config]);
// callbacks handling
const callbacks = useRef<{
onStart: Exclude<StreamCallback["onStart"], undefined>[];
onSuccess: Exclude<StreamCallback["onSuccess"], undefined>[];
onError: Exclude<StreamCallback["onError"], undefined>[];
}>({ onStart: [], onSuccess: [], onError: [] });
// the runner
const { startStream, stopStream, latest } = useStreamLog();
const { startStream, stopStream, latest } = useStreamLog({
onStart(...args) {
for (const callback of callbacks.current.onStart) {
callback(...args);
}
},
onSuccess(...args) {
for (const callback of callbacks.current.onSuccess) {
callback(...args);
}
},
onError(...args) {
for (const callback of callbacks.current.onError) {
callback(...args);
}
},
});
useEffect(() => {
window.parent?.postMessage({ type: "init" }, "*");
@@ -204,7 +214,11 @@ function App() {
const value: { config: JsonFormsCore["data"] } = message.value;
if (Object.keys(value.config).length > 0) {
initConfigData.current = value.config;
setConfigData({ data: value.config, errors: [] });
setConfigData({
data: value.config,
errors: [],
defaults: false,
});
break;
}
}
@@ -217,152 +231,242 @@ function App() {
return () => window.removeEventListener("message", listener);
}, []);
return schemas.config && schemas.input ? (
<div className="flex items-center flex-col text-ls-black bg-gradient-to-b from-[#F9FAFB] to-[#EFF8FF] min-h-[100dvh] dark:from-[#0C111C] dark:to-[#0C111C]">
<div className="flex flex-col flex-grow gap-4 px-4 pt-6 max-w-[800px] w-full">
<h1 className="text-2xl text-left">
<strong>🦜 LangServe</strong> Playground
</h1>
<div className="flex flex-col gap-3">
{!isIframe && <h2 className="text-xl font-semibold">Configure</h2>}
const isInputResetable = useMemo(() => {
if (!schemas.input) return false;
return (
JSON.stringify(defaults(schemas.input)) !== JSON.stringify(inputData.data)
);
}, [schemas.input, inputData.data]);
<JsonForms
schema={schemas.config}
data={configData.data}
renderers={renderers}
cells={cells}
onChange={({ data, errors }) =>
data ? setConfigData({ data, errors }) : undefined
}
/>
{!!configData.errors?.length && configData.data && (
<div className="bg-background rounded-xl">
<div className="bg-red-500/10 text-red-700 dark:text-red-300 rounded-xl p-3">
<strong className="font-bold">Validation Errors</strong>
<ul className="list-disc pl-5">
{configData.errors?.map((e, i) => (
<li key={i}>{e.message}</li>
))}
</ul>
function onSubmit() {
if (
!stopStream &&
(!!inputData.errors?.length || !!configData.errors?.length)
) {
return;
}
if (stopStream) {
stopStream();
} else {
startStream(inputData.data, configData.data);
}
}
const submitRef = useRef<(() => void) | null>(null);
submitRef.current = onSubmit;
useEffect(() => {
window.addEventListener("keydown", (e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
submitRef.current?.();
}
});
}, []);
const isSendDisabled =
!stopStream && (!!inputData.errors?.length || !!configData.errors?.length);
if (!schemas.config || !schemas.input) {
return <></>;
}
return (
<AppCallbackContext.Provider value={callbacks}>
<div className="flex items-center flex-col text-ls-black bg-gradient-to-b from-[#F9FAFB] to-[#EFF8FF] min-h-[100dvh] dark:from-[#0C111C] dark:to-[#0C111C]">
<div className="flex flex-col flex-grow gap-4 px-4 pt-6 max-w-[800px] w-full">
<h1 className="text-2xl text-left">
<strong>🦜 LangServe</strong> Playground
</h1>
{Object.keys(schemas.config).length > 0 && (
<div className="flex flex-col gap-3 [&:has(.content>.vertical-layout:first-child:last-child:empty)]:hidden">
{!isEmbedded && (
<h2 className="text-xl font-semibold">Configure</h2>
)}
<div className="content flex flex-col gap-3">
<JsonForms
schema={schemas.config}
data={configData.data}
renderers={renderers}
cells={cells}
onChange={({ data, errors }) =>
data
? setConfigData({ data, errors, defaults: false })
: undefined
}
/>
{!!configData.errors?.length && configData.data && (
<div className="bg-background rounded-xl">
<div className="bg-red-500/10 text-red-700 dark:text-red-300 rounded-xl p-3">
<strong className="font-bold">Validation Errors</strong>
<ul className="list-disc pl-5">
{configData.errors?.map((e, i) => (
<li key={i}>{e.message}</li>
))}
</ul>
</div>
</div>
)}
</div>
</div>
)}
</div>
{!isIframe && (
<div className="flex flex-col gap-3">
<h2 className="text-xl font-semibold">Try it</h2>
{!isEmbedded && (
<div className="flex flex-col gap-3">
<h2 className="text-xl font-semibold">Try it</h2>
<div className="p-4 border border-divider-700 flex flex-col gap-3 rounded-2xl bg-background">
<h3 className="font-medium">Inputs</h3>
<div className="p-4 border border-divider-700 flex flex-col gap-3 rounded-2xl bg-background">
<div className="flex items-center justify-between">
<h3 className="font-medium">Inputs</h3>
{isInputResetable && (
<button
type="button"
className="text-sm px-1 -mr-1 py-0.5 rounded-md hover:bg-divider-500/50 active:bg-divider-500 text-ls-gray-100"
onClick={() =>
setInputData({
data: defaults(schemas.input),
errors: [],
})
}
>
Reset
</button>
)}
</div>
<JsonForms
schema={schemas.input}
data={inputData.data}
renderers={renderers}
cells={cells}
onChange={({ data, errors }) => setInputData({ data, errors })}
/>
{!!inputData.errors?.length && inputData.data && (
<div className="bg-red-500/10 text-red-700 dark:text-red-300 rounded-xl p-3">
<strong className="font-bold">Validation Errors</strong>
<ul className="list-disc pl-5">
{inputData.errors?.map((e, i) => (
<li key={i}>{e.message}</li>
))}
</ul>
<JsonForms
schema={schemas.input}
data={inputData.data}
renderers={renderers}
cells={cells}
onChange={({ data, errors }) =>
setInputData({ data, errors })
}
/>
{!!inputData.errors?.length && inputData.data && (
<div className="bg-red-500/10 text-red-700 dark:text-red-300 rounded-xl p-3">
<strong className="font-bold">Validation Errors</strong>
<ul className="list-disc pl-5">
{inputData.errors?.map((e, i) => (
<li key={i}>{e.message}</li>
))}
</ul>
</div>
)}
</div>
{latest && (
<div className="flex flex-col gap-3">
<h2 className="text-xl font-semibold">Output</h2>
<div className="p-4 border border-divider-700 flex flex-col gap-3 rounded-2xl bg-background text-lg whitespace-pre-wrap break-words">
<StreamOutput streamed={latest.streamed_output} />
</div>
<IntermediateSteps latest={latest} />
</div>
)}
</div>
)}
{latest && (
<div className="flex flex-col gap-3">
<h2 className="text-xl font-semibold">Output</h2>
<div className="p-4 border border-divider-700 flex flex-col gap-3 rounded-2xl bg-background text-lg">
{latest.streamed_output.map(str).join("") || "..."}
</div>
<IntermediateSteps latest={latest} />
</div>
)}
</div>
)}
<div className="flex-grow md:hidden" />
<div className="flex-grow md:hidden" />
<div className="gap-4 grid grid-cols-2 sticky -mx-4 px-4 py-4 bottom-0 bg-background md:static md:bg-transparent">
<div className="md:hidden absolute inset-x-0 bottom-full h-5 bg-gradient-to-t from-black/5 to-black/0" />
<div className="gap-4 grid grid-cols-2 sticky -mx-4 px-4 py-4 bottom-0 bg-background md:static md:bg-transparent">
<div className="md:hidden absolute inset-x-0 bottom-full h-5 bg-gradient-to-t from-black/5 to-black/0" />
{isIframe ? (
<>
<button
type="button"
className="px-4 py-3 gap-3 font-medium border border-divider-700 rounded-full flex items-center justify-center hover:bg-divider-500/50 active:bg-divider-500 transition-colors"
onClick={() =>
window.parent?.postMessage({ type: "close" }, "*")
}
>
Cancel
</button>
<button
type="button"
className="px-4 py-3 gap-3 font-medium border border-transparent rounded-full flex items-center justify-center bg-blue-500 hover:bg-blue-600 active:bg-blue-700 disabled:opacity-50 transition-colors"
onClick={() => {
const hash = compressToEncodedURIComponent(
JSON.stringify(configData.data)
);
const state = getStateFromUrl(window.location.href);
const targetUrl = `${state.basePath}/c/${hash}`;
window.parent?.postMessage(
{
type: "apply",
value: { targetUrl, config: configData.data },
},
"*"
);
}}
>
<span className="text-white">Apply</span>
</button>
</>
) : (
<>
<ShareDialog config={configData.data}>
{isEmbedded ? (
<>
<button
type="button"
className="px-4 py-3 gap-3 font-medium border border-divider-700 rounded-full flex items-center justify-center hover:bg-divider-500/50 active:bg-divider-500 transition-colors"
onClick={() =>
window.parent?.postMessage({ type: "close" }, "*")
}
>
<ShareIcon className="flex-shrink-0" /> <span>Share</span>
Cancel
</button>
</ShareDialog>
<button
type="button"
className="px-4 py-3 gap-3 font-medium border border-transparent rounded-full flex items-center justify-center bg-blue-500 hover:bg-blue-600 active:bg-blue-700 disabled:opacity-50 transition-colors"
onClick={() => {
stopStream
? stopStream()
: startStream(inputData.data, configData.data);
}}
disabled={
!stopStream &&
(!!inputData.errors?.length || !!configData.errors?.length)
}
>
{stopStream ? (
<span className="text-white">Stop</span>
) : (
<>
<SendIcon className="flex-shrink-0" />
<span className="text-white">Start</span>
</>
)}
</button>
</>
)}
<button
type="button"
className="px-4 py-3 gap-3 font-medium border border-transparent rounded-full flex items-center justify-center bg-blue-500 hover:bg-blue-600 active:bg-blue-700 disabled:opacity-50 transition-colors"
onClick={() => {
const hash = compressToEncodedURIComponent(
JSON.stringify(configData.data)
);
const state = getStateFromUrl(window.location.href);
const targetUrl = `${state.basePath}/c/${hash}`;
window.parent?.postMessage(
{
type: "apply",
value: { targetUrl, config: configData.data },
},
"*"
);
}}
>
<span className="text-white">Apply</span>
</button>
</>
) : (
<>
<ShareDialog config={configData.data}>
<button
type="button"
className="px-4 py-3 gap-3 font-medium border border-divider-700 rounded-full flex items-center justify-center hover:bg-divider-500/50 active:bg-divider-500 transition-colors"
>
<ShareIcon className="flex-shrink-0" /> <span>Share</span>
</button>
</ShareDialog>
<button
type="button"
className={cn(
"px-4 py-3 gap-3 font-medium border border-transparent rounded-full flex items-center justify-center bg-blue-500 disabled:opacity-50 transition-colors",
!isSendDisabled
? "hover:bg-blue-600 active:bg-blue-700"
: ""
)}
onClick={onSubmit}
disabled={isSendDisabled}
>
{stopStream ? (
<>
<div role="status">
<svg
aria-hidden="true"
className="w-5 h-5 animate-spin text-white fill-ls-blue"
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="currentColor"
/>
<path
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="currentFill"
/>
</svg>
<span className="sr-only">Loading...</span>
</div>
<span className="text-white">Stop</span>
</>
) : (
<>
<SendIcon className="flex-shrink-0" />
<span className="text-white">Start</span>
</>
)}
</button>
</>
)}
</div>
</div>
</div>
</div>
) : null;
</AppCallbackContext.Provider>
);
}
export default App;
@@ -0,0 +1,6 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd"
d="M7.7588 2H16.2414C17.0464 1.99999 17.7107 1.99998 18.2519 2.04419C18.814 2.09012 19.3307 2.18868 19.8161 2.43597C20.5687 2.81947 21.1806 3.43139 21.5641 4.18404C21.8114 4.66937 21.91 5.18608 21.9559 5.74817C22.0001 6.28936 22.0001 6.95372 22.0001 7.75868V13.2413C22.0001 14.0463 22.0001 14.7106 21.9559 15.2518C21.91 15.8139 21.8114 16.3306 21.5641 16.816C21.1806 17.5686 20.5687 18.1805 19.8161 18.564C19.3307 18.8113 18.814 18.9099 18.2519 18.9558C17.7107 19 17.0464 19 16.2414 19H13.6838C13.0197 19 12.8263 19.0047 12.6504 19.0408C12.4738 19.0771 12.303 19.137 12.1425 19.219C11.9826 19.3007 11.8286 19.4178 11.31 19.8327L8.89688 21.7632C8.7132 21.9102 8.52597 22.06 8.36137 22.1689C8.20394 22.273 7.8987 22.4593 7.50172 22.4597C7.0449 22.4602 6.61276 22.2525 6.32778 21.8955C6.08012 21.5852 6.03492 21.2305 6.01785 21.0425C6 20.846 6.00005 20.6062 6.00009 20.371L6.0001 18.9918C5.60829 18.9789 5.27229 18.9461 4.96482 18.8637C3.58445 18.4938 2.50626 17.4156 2.13639 16.0353C1.9993 15.5236 1.99962 14.933 2.00005 14.1376C2.00007 14.0924 2.0001 14.0465 2.0001 14L2.0001 7.7587C2.00008 6.95373 2.00007 6.28937 2.04429 5.74817C2.09022 5.18608 2.18878 4.66937 2.43607 4.18404C2.81956 3.43139 3.43149 2.81947 4.18413 2.43597C4.66947 2.18868 5.18617 2.09012 5.74827 2.04419C6.28947 1.99998 6.95383 1.99999 7.7588 2ZM5.91113 4.03755C5.47272 4.07337 5.24852 4.1383 5.09212 4.21799C4.71579 4.40973 4.40983 4.7157 4.21808 5.09202C4.13839 5.24842 4.07347 5.47262 4.03765 5.91104C4.00087 6.36113 4.0001 6.94342 4.0001 7.8V14C4.0001 14.9944 4.00869 15.2954 4.06824 15.5176C4.25318 16.2078 4.79227 16.7469 5.48246 16.9319C5.70474 16.9914 6.00574 17 7.0001 17C7.55238 17 8.0001 17.4477 8.0001 18V19.9194L10.0606 18.271C10.0834 18.2528 10.1058 18.2348 10.1279 18.2171C10.55 17.8791 10.8691 17.6237 11.2326 17.4379C11.5536 17.274 11.8952 17.1541 12.2483 17.0817C12.6482 16.9996 13.0569 16.9998 13.5976 17C13.626 17 13.6547 17 13.6838 17H16.2001C17.0567 17 17.639 16.9992 18.0891 16.9624C18.5275 16.9266 18.7517 16.8617 18.9081 16.782C19.2844 16.5903 19.5904 16.2843 19.7821 15.908C19.8618 15.7516 19.9267 15.5274 19.9625 15.089C19.9993 14.6389 20.0001 14.0566 20.0001 13.2V7.8C20.0001 6.94342 19.9993 6.36113 19.9625 5.91104C19.9267 5.47262 19.8618 5.24842 19.7821 5.09202C19.5904 4.7157 19.2844 4.40973 18.9081 4.21799C18.7517 4.1383 18.5275 4.07337 18.0891 4.03755C17.639 4.00078 17.0567 4 16.2001 4H7.8001C6.94352 4 6.36122 4.00078 5.91113 4.03755Z"
fill="currentColor" />
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

+3 -3
View File
@@ -1,6 +1,6 @@
<svg width="19" height="13" viewBox="0 0 19 13" fill="none" xmlns="http://www.w3.org/2000/svg">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd"
d="M6.75657 0.91107C7.08201 1.23651 7.08201 1.76414 6.75657 2.08958L2.34583 6.50033L6.75657 10.9111C7.08201 11.2365 7.08201 11.7641 6.75657 12.0896C6.43114 12.415 5.9035 12.415 5.57806 12.0896L0.578062 7.08958C0.252625 6.76414 0.252625 6.23651 0.578062 5.91107L5.57806 0.91107C5.9035 0.585633 6.43114 0.585633 6.75657 0.91107ZM12.2447 0.91107C12.5702 0.585633 13.0978 0.585633 13.4232 0.91107L18.4232 5.91107C18.7487 6.23651 18.7487 6.76414 18.4232 7.08958L13.4232 12.0896C13.0978 12.415 12.5702 12.415 12.2447 12.0896C11.9193 11.7641 11.9193 11.2365 12.2447 10.9111L16.6555 6.50033L12.2447 2.08958C11.9193 1.76414 11.9193 1.23651 12.2447 0.91107Z"
fill="currentColor" fill-opacity="0.9" />
d="M8.70711 5.29289C9.09763 5.68342 9.09763 6.31658 8.70711 6.70711L3.41421 12L8.70711 17.2929C9.09763 17.6834 9.09763 18.3166 8.70711 18.7071C8.31658 19.0976 7.68342 19.0976 7.29289 18.7071L1.29289 12.7071C0.902369 12.3166 0.902369 11.6834 1.29289 11.2929L7.29289 5.29289C7.68342 4.90237 8.31658 4.90237 8.70711 5.29289ZM15.2929 5.29289C15.6834 4.90237 16.3166 4.90237 16.7071 5.29289L22.7071 11.2929C23.0976 11.6834 23.0976 12.3166 22.7071 12.7071L16.7071 18.7071C16.3166 19.0976 15.6834 19.0976 15.2929 18.7071C14.9024 18.3166 14.9024 17.6834 15.2929 17.2929L20.5858 12L15.2929 6.70711C14.9024 6.31658 14.9024 5.68342 15.2929 5.29289Z"
fill="currentColor" />
</svg>

Before

Width:  |  Height:  |  Size: 852 B

After

Width:  |  Height:  |  Size: 823 B

@@ -0,0 +1,132 @@
import { withJsonFormsControlProps } from "@jsonforms/react";
import PlusIcon from "../assets/PlusIcon.svg?react";
import TrashIcon from "../assets/TrashIcon.svg?react";
import {
rankWith,
and,
schemaMatches,
Paths,
isControl,
} from "@jsonforms/core";
import { AutosizeTextarea } from "./AutosizeTextarea";
import { isJsonSchemaExtra } from "../utils/schema";
import { useStreamCallback } from "../useStreamCallback";
import { traverseNaiveJsonPath } from "../utils/path";
type MessageTuple = [string, string];
export const chatMessagesTupleTester = rankWith(
12,
and(
isControl,
schemaMatches((schema) => {
if (schema.type !== "array") return false;
if (typeof schema.items !== "object" || schema.items == null)
return false;
if (!isJsonSchemaExtra(schema) || schema.extra.widget.type !== "chat") {
return false;
}
if ("type" in schema.items) {
return (
schema.items.type === "array" &&
schema.items.minItems === 2 &&
schema.items.maxItems === 2 &&
Array.isArray(schema.items.items) &&
schema.items.items.length === 2 &&
schema.items.items.every((schema) => schema.type === "string")
);
}
return false;
})
)
);
export const ChatMessageTuplesControlRenderer = withJsonFormsControlProps(
(props) => {
const data: Array<MessageTuple> = props.data ?? [];
useStreamCallback("onSuccess", (ctx) => {
if (!isJsonSchemaExtra(props.schema)) return;
const widget = props.schema.extra.widget;
if (!("input" in widget) && !("output" in widget)) return;
const human = traverseNaiveJsonPath(ctx.input, widget.input ?? "");
const ai = traverseNaiveJsonPath(ctx.output, widget.output ?? "");
if (typeof human === "string" && typeof ai === "string") {
props.handleChange(props.path, [...data, [human, ai]]);
}
});
return (
<div className="control">
<div className="flex items-center justify-between">
<label className="text-xs uppercase font-semibold text-ls-gray-100">
{props.label || "Messages"}
</label>
<button
className="p-1 rounded-full"
onClick={() => props.handleChange(props.path, [...data, ["", ""]])}
>
<PlusIcon className="w-5 h-5" />
</button>
</div>
<div className="flex flex-col gap-3 mt-1 empty:hidden">
{data.map(([human, ai], index) => {
const msgPath = Paths.compose(props.path, `${index}`);
return (
<div className="control group relative" key={index}>
<div className="grid gap-3">
<div className="flex-grow">
<div className="flex items-start justify-between gap-2">
<div className="text-xs uppercase font-semibold text-ls-gray-100 mb-1 ">
Human
</div>
</div>
<AutosizeTextarea
value={human}
onChange={(human) => {
props.handleChange(Paths.compose(msgPath, "0"), human);
}}
/>
</div>
<div className="flex-shrink-0 h-px bg-divider-700" />
<div className="flex-grow">
<div className="flex items-start justify-between gap-2">
<div className="text-xs uppercase font-semibold text-ls-gray-100 mb-1 ">
AI
</div>
</div>
<AutosizeTextarea
value={ai}
onChange={(ai) => {
props.handleChange(Paths.compose(msgPath, "1"), ai);
}}
/>
</div>
</div>
<button
className="absolute right-3 top-3 p-1 border rounded opacity-0 transition-opacity border-divider-700 group-focus-within:opacity-100 group-hover:opacity-100"
onClick={() => {
props.handleChange(
props.path,
data.filter((_, i) => i !== index)
);
}}
>
<TrashIcon className="w-4 h-4" />
</button>
</div>
);
})}
</div>
</div>
);
}
);
@@ -0,0 +1,349 @@
import { withJsonFormsControlProps } from "@jsonforms/react";
import PlusIcon from "../assets/PlusIcon.svg?react";
import TrashIcon from "../assets/TrashIcon.svg?react";
import CodeIcon from "../assets/CodeIcon.svg?react";
import ChatIcon from "../assets/ChatIcon.svg?react";
import {
rankWith,
and,
schemaMatches,
Paths,
isControl,
} from "@jsonforms/core";
import { AutosizeTextarea } from "./AutosizeTextarea";
import { useStreamCallback } from "../useStreamCallback";
import { traverseNaiveJsonPath } from "../utils/path";
import { isJsonSchemaExtra } from "../utils/schema";
import * as ToggleGroup from "@radix-ui/react-toggle-group";
export const chatMessagesTester = rankWith(
12,
and(
isControl,
schemaMatches((schema) => {
if (schema.type !== "array") return false;
if (typeof schema.items !== "object" || schema.items == null)
return false;
if (
"type" in schema.items &&
schema.items.type != null &&
schema.items.title != null
) {
return (
schema.items.type === "object" &&
(schema.items.title?.endsWith("Message") ||
schema.items.title?.endsWith("MessageChunk"))
);
}
if ("anyOf" in schema.items && schema.items.anyOf != null) {
return schema.items.anyOf.every((schema) => {
const isObjectMessage =
schema.type === "object" &&
(schema.title?.endsWith("Message") ||
schema.title?.endsWith("MessageChunk"));
const isTupleMessage =
schema.type === "array" &&
schema.minItems === 2 &&
schema.maxItems === 2 &&
Array.isArray(schema.items) &&
schema.items.length === 2 &&
schema.items.every((schema) => schema.type === "string");
return isObjectMessage || isTupleMessage;
});
}
return false;
})
)
);
interface MessageFields {
content: string;
additional_kwargs?: { [key: string]: unknown };
name?: string;
type?: string;
role?: string;
}
function isMessageFields(x: unknown): x is MessageFields {
if (typeof x !== "object" || x == null) return false;
if (!("content" in x) || typeof x.content !== "string") return false;
if (
"additional_kwargs" in x &&
typeof x.additional_kwargs !== "object" &&
x.additional_kwargs != null
)
return false;
if ("name" in x && typeof x.name !== "string" && x.name != null) return false;
if ("type" in x && typeof x.type !== "string" && x.type != null) return false;
if ("role" in x && typeof x.role !== "string" && x.role != null) return false;
return true;
}
function constructMessage(
x: unknown,
assumedRole: string
): Array<MessageFields> | null {
if (typeof x === "string") {
return [{ content: x, type: assumedRole }];
}
if (isMessageFields(x)) {
return [x];
}
if (Array.isArray(x) && x.every(isMessageFields)) {
return x;
}
return null;
}
function isOpenAiFunctionCall(
x: unknown
): x is { name: string; arguments: string } {
if (typeof x !== "object" || x == null) return false;
if (!("name" in x) || typeof x.name !== "string") return false;
if (!("arguments" in x) || typeof x.arguments !== "string") return false;
return true;
}
export const ChatMessagesControlRenderer = withJsonFormsControlProps(
(props) => {
const data: Array<MessageFields> = props.data ?? [];
useStreamCallback("onSuccess", (ctx) => {
if (!isJsonSchemaExtra(props.schema)) return;
const widget = props.schema.extra.widget;
if (!("input" in widget) && !("output" in widget)) return;
const human = traverseNaiveJsonPath(ctx.input, widget.input ?? "");
const ai = traverseNaiveJsonPath(ctx.output, widget.output ?? "");
const humanMsg = constructMessage(human, "human");
const aiMsg = constructMessage(ai, "ai");
let newMessages = undefined;
if (humanMsg != null) {
newMessages ??= [...data];
newMessages.push(...humanMsg);
}
if (aiMsg != null) {
newMessages ??= [...data];
newMessages.push(...aiMsg);
}
if (newMessages != null) {
props.handleChange(props.path, newMessages);
}
});
return (
<div className="control">
<div className="flex items-center justify-between">
<label className="text-xs uppercase font-semibold text-ls-gray-100">
{props.label || "Messages"}
</label>
<button
className="p-1 rounded-full"
onClick={() => {
const lastRole = data.length ? data[data.length - 1].type : "ai";
props.handleChange(props.path, [
...data,
{ content: "", type: lastRole === "human" ? "ai" : "human" },
]);
}}
>
<PlusIcon className="w-5 h-5" />
</button>
</div>
<div className="flex flex-col gap-3 mt-1 empty:hidden">
{data.map((message, index) => {
const msgPath = Paths.compose(props.path, `${index}`);
const type = message.type ?? "chat";
const isAiFunctionCall = isOpenAiFunctionCall(
message.additional_kwargs?.function_call
);
return (
<div className="control group" key={index}>
<div className="flex items-start justify-between gap-2">
<select
className="-ml-1 min-w-[100px]"
value={type}
onChange={(e) => {
props.handleChange(
Paths.compose(msgPath, "type"),
e.target.value
);
}}
>
<option value="human">Human</option>
<option value="ai">AI</option>
<option value="system">System</option>
<option value="function">Function</option>
<option value="chat">Chat</option>
</select>
<div className="flex items-center gap-2">
{message.type === "ai" && (
<ToggleGroup.Root
type="single"
aria-label="Message Type"
className="opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100"
value={isAiFunctionCall ? "function" : "text"}
onValueChange={(value) => {
switch (value) {
case "function": {
props.handleChange(
Paths.compose(msgPath, "additional_kwargs"),
{
function_call: {
name: "",
arguments: "{}",
},
}
);
break;
}
case "text": {
props.handleChange(
Paths.compose(msgPath, "additional_kwargs"),
{}
);
break;
}
}
}}
>
<ToggleGroup.Item
className="rounded-s border border-divider-700 px-2.5 py-1 data-[state=on]:bg-divider-500/50"
value="text"
aria-label="Text message"
>
<ChatIcon className="w-4 h-4" />
</ToggleGroup.Item>
<ToggleGroup.Item
className="rounded-e border border-l-0 border-divider-700 px-2.5 py-1 data-[state=on]:bg-divider-500/50"
value="function"
aria-label="Function call"
>
<CodeIcon className="w-4 h-4" />
</ToggleGroup.Item>
</ToggleGroup.Root>
)}
<button
className="p-1 border rounded opacity-0 transition-opacity border-divider-700 group-focus-within:opacity-100 group-hover:opacity-100"
onClick={() => {
props.handleChange(
props.path,
data.filter((_, i) => i !== index)
);
}}
>
<TrashIcon className="w-4 h-4" />
</button>
</div>
</div>
{type === "chat" && (
<input
className="mb-1"
placeholder="Role"
value={message.role ?? ""}
onChange={(e) => {
props.handleChange(
Paths.compose(msgPath, "role"),
e.target.value
);
}}
/>
)}
{type === "function" && (
<input
className="mb-1"
placeholder="Function Name"
value={message.name ?? ""}
onChange={(e) => {
props.handleChange(
Paths.compose(msgPath, "name"),
e.target.value
);
}}
/>
)}
{type === "ai" &&
isOpenAiFunctionCall(
message.additional_kwargs?.function_call
) ? (
<>
<input
className="mb-1"
placeholder="Function Name"
value={
message.additional_kwargs?.function_call.name ?? ""
}
onChange={(e) => {
console.log(
Paths.compose(
msgPath,
"additional_kwargs.function_call.name"
)
);
props.handleChange(
Paths.compose(
msgPath,
"additional_kwargs.function_call.name"
),
e.target.value
);
}}
/>
<AutosizeTextarea
value={
message.additional_kwargs?.function_call?.arguments ??
""
}
onChange={(content) => {
props.handleChange(
Paths.compose(
msgPath,
"additional_kwargs.function_call.arguments"
),
content
);
}}
/>
</>
) : (
<AutosizeTextarea
value={message.content}
onChange={(content) => {
props.handleChange(
Paths.compose(msgPath, "content"),
content
);
}}
/>
)}
</div>
);
})}
</div>
</div>
);
}
);
@@ -0,0 +1,37 @@
import { JsonFormsDispatch, withJsonFormsAnyOfProps } from "@jsonforms/react";
import {
rankWith,
createCombinatorRenderInfos,
JsonSchema,
isAnyOfControl,
} from "@jsonforms/core";
import { renderers, cells } from "../App";
export const CustomAnyOfRenderer = withJsonFormsAnyOfProps((props) => {
const anyOfRenderInfos = createCombinatorRenderInfos(
(props.schema as JsonSchema).anyOf!,
props.rootSchema,
"anyOf",
props.uischema,
props.path,
props.uischemas
);
// just assume the last type is the selected one
// for `anyOf` caused by passing inputs from LLMs/Chat Models
// this will result in showing the Message renderer
const selectedIndex = anyOfRenderInfos.length - 1;
const selectedAnyOfRenderInfo = anyOfRenderInfos[selectedIndex];
return (
<JsonFormsDispatch
schema={selectedAnyOfRenderInfo.schema}
uischema={selectedAnyOfRenderInfo.uischema}
path={props.path}
renderers={renderers}
cells={cells}
/>
);
});
export const customAnyOfTester = rankWith(3, isAnyOfControl);
@@ -84,7 +84,7 @@ export const MaterialArrayControlRenderer = (props: ArrayLayoutProps) => {
// eslint-disable-next-line react-refresh/only-export-components
export const materialArrayControlTester: RankedTester = rankWith(
999,
11,
or(isObjectArrayControl, isPrimitiveArrayControl, isObjectArrayWithNesting)
);
@@ -92,7 +92,7 @@ const generateCells = (
enabled: boolean,
cells?: JsonFormsCellRendererRegistryEntry[]
) => {
if (schema.type === "object") {
if (schema?.type === "object") {
return getValidColumnProps(schema).map((prop) => {
const cellPath = Paths.compose(rowPath, prop);
const props = {
@@ -381,7 +381,7 @@ interface TableRowsProp {
const TableRows = ({
data,
path,
schema,
schema = {},
openDeleteDialog,
moveUp,
moveDown,
@@ -444,7 +444,7 @@ export class MaterialTableControl extends React.Component<
const {
label,
path,
schema,
schema = {},
rootSchema,
uischema,
errors,
@@ -456,7 +456,7 @@ export class MaterialTableControl extends React.Component<
} = this.props;
const controlElement = uischema as ControlElement;
const isObjectSchema = schema.type === "object";
const isObjectSchema = schema?.type === "object";
const headerCells: any = isObjectSchema
? generateCells(TableHeaderCell as any, schema, path, enabled, cells)
: undefined;
@@ -0,0 +1,44 @@
import { ChangeEvent } from "react";
import { withJsonFormsControlProps } from "@jsonforms/react";
import { rankWith, and, schemaMatches, isControl } from "@jsonforms/core";
import { isJsonSchemaExtra } from "../utils/schema";
export const fileBase64Tester = rankWith(
12,
and(
isControl,
schemaMatches((schema) => {
if (!isJsonSchemaExtra(schema)) return false;
return schema.extra.widget.type === "base64file";
})
)
);
export const FileBase64ControlRenderer = withJsonFormsControlProps((props) => {
const handleFileUpload = (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
const base64String = reader.result as string | null;
if (base64String != null) {
const prefix = base64String.indexOf("base64,") + "base64,".length;
props.handleChange(props.path, base64String.slice(prefix));
}
};
reader.readAsDataURL(file);
};
return (
<div className="control">
<label className="text-xs uppercase font-semibold text-ls-gray-100">
{props.label}
</label>
<input type="file" onChange={handleFileUpload} />
</div>
);
});
@@ -0,0 +1,53 @@
import { useState } from "react";
import dayjs from "dayjs";
import ChevronRight from "../assets/ChevronRight.svg?react";
import { RunState } from "../useStreamLog";
import { cn } from "../utils/cn";
import { str } from "../utils/str";
export function IntermediateSteps(props: { latest: RunState }) {
const [expanded, setExpanded] = useState(false);
const length = Object.values(props.latest.logs).length;
const disabled = length === 0;
return (
<div className="flex flex-col border border-divider-700 rounded-2xl bg-background">
<button
className="font-medium text-left p-4 flex items-center justify-between"
disabled={disabled}
onClick={() => setExpanded((open) => !open)}
>
<span>
Intermediate steps{" "}
<span className="bg-ls-gray-400 text-ls-gray-100 text-sm px-1 py-0.5 rounded-md ml-1">
{length}
</span>
</span>
<ChevronRight
className={cn(
"transition-all",
expanded && "rotate-90",
disabled && "opacity-20"
)}
/>
</button>
{expanded && (
<div className="flex flex-col gap-5 p-4 pt-0 divide-solid divide-y divide-divider-700 rounded-b-xl">
{Object.values(props.latest.logs).map((log) => (
<div
className="gap-3 flex-col min-w-0 flex bg-background pt-3 first-of-type:pt-0"
key={log.id}
>
<div className="flex items-center justify-between">
<strong className="text-sm font-medium">{log.name}</strong>
<p className="text-sm">{dayjs.utc(log.start_time).fromNow()}</p>
</div>
<pre className="break-words whitespace-pre-wrap min-w-0 text-sm bg-ls-gray-400 rounded-lg p-3">
{str(log.final_output) ?? "..."}
</pre>
</div>
))}
</div>
)}
</div>
);
}
@@ -131,7 +131,7 @@ const result = await chain.invoke({ ... });
<div className="flex flex-col gap-2 p-3 rounded-2xl dark:bg-[#2C2C2E] bg-gray-100">
<div className="flex items-center gap-3">
<div className="w-10 h-10 flex items-center justify-center text-center text-sm bg-background rounded-xl">
<CodeIcon />
<CodeIcon className="w-4 h-4" />
</div>
<span className="font-semibold">Get the code</span>
</div>
@@ -0,0 +1,108 @@
import { str } from "../utils/str";
// inlined from langchain/schema
interface BaseMessageFields {
content: string;
name?: string;
additional_kwargs?: {
[key: string]: unknown;
};
}
class AIMessageChunk {
/** The text of the message. */
content: string;
/** The name of the message sender in a multi-user chat. */
name?: string;
/** Additional keyword arguments */
additional_kwargs: NonNullable<BaseMessageFields["additional_kwargs"]>;
constructor(fields: BaseMessageFields) {
// Make sure the default value for additional_kwargs is passed into super() for serialization
if (!fields.additional_kwargs) {
// eslint-disable-next-line no-param-reassign
fields.additional_kwargs = {};
}
this.name = fields.name;
this.content = fields.content;
this.additional_kwargs = fields.additional_kwargs;
}
static _mergeAdditionalKwargs(
left: NonNullable<BaseMessageFields["additional_kwargs"]>,
right: NonNullable<BaseMessageFields["additional_kwargs"]>
): NonNullable<BaseMessageFields["additional_kwargs"]> {
const merged = { ...left };
for (const [key, value] of Object.entries(right)) {
if (merged[key] === undefined) {
merged[key] = value;
} else if (typeof merged[key] !== typeof value) {
throw new Error(
`additional_kwargs[${key}] already exists in the message chunk, but with a different type.`
);
} else if (typeof merged[key] === "string") {
merged[key] = (merged[key] as string) + value;
} else if (
!Array.isArray(merged[key]) &&
typeof merged[key] === "object"
) {
merged[key] = this._mergeAdditionalKwargs(
merged[key] as NonNullable<BaseMessageFields["additional_kwargs"]>,
value as NonNullable<BaseMessageFields["additional_kwargs"]>
);
} else {
throw new Error(
`additional_kwargs[${key}] already exists in this message chunk.`
);
}
}
return merged;
}
concat(chunk: AIMessageChunk) {
return new AIMessageChunk({
content: this.content + chunk.content,
additional_kwargs: AIMessageChunk._mergeAdditionalKwargs(
this.additional_kwargs,
chunk.additional_kwargs
),
});
}
}
function isAiMessageChunkFields(value: unknown): value is BaseMessageFields {
if (typeof value !== "object" || value == null) return false;
return "content" in value && typeof value["content"] === "string";
}
function isAiMessageChunkFieldsList(
value: unknown[]
): value is BaseMessageFields[] {
return value.length > 0 && value.every((x) => isAiMessageChunkFields(x));
}
export function StreamOutput(props: { streamed: unknown[] }) {
// check if we're streaming AIMessageChunk
if (isAiMessageChunkFieldsList(props.streamed)) {
const concat = props.streamed.reduce<AIMessageChunk | null>(
(memo, field) => {
const chunk = new AIMessageChunk(field);
if (memo == null) return chunk;
return memo.concat(chunk);
},
null
);
const functionCall = concat?.additional_kwargs?.function_call;
return (
concat?.content ||
(!!functionCall && JSON.stringify(functionCall, null, 2)) ||
"..."
);
}
return props.streamed.map(str).join("") || "...";
}
+5
View File
@@ -0,0 +1,5 @@
export interface StreamCallback {
onSuccess?: (ctx: { input: unknown; output: unknown }) => void;
onError?: () => void;
onStart?: (ctx: { input: unknown }) => void;
}
@@ -1,5 +0,0 @@
declare module "json-schema-defaults" {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function defaults(schema: any): any;
export = defaults;
}
+30 -2
View File
@@ -1,6 +1,9 @@
import { useEffect, useState } from "react";
import { resolveApiUrl } from "./utils/url";
import { simplifySchema } from "./utils/simplifySchema";
import { JsonFormsCore } from "@jsonforms/core";
import { compressToEncodedURIComponent } from "lz-string";
import { useDebounce } from "use-debounce";
declare global {
interface Window {
@@ -11,8 +14,15 @@ declare global {
}
}
export function useSchemas() {
const [schemas, setSchemas] = useState({
export function useSchemas(
configData: Pick<JsonFormsCore, "data" | "errors"> & { defaults: boolean }
) {
const [schemas, setSchemas] = useState<{
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: null | any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
input: null | any;
}>({
config: null,
input: null,
});
@@ -44,5 +54,23 @@ export function useSchemas() {
save();
}, []);
const [debouncedConfigData] = useDebounce(configData, 500);
useEffect(() => {
if (!debouncedConfigData.defaults) {
fetch(
resolveApiUrl(
`/c/${compressToEncodedURIComponent(
JSON.stringify(debouncedConfigData.data)
)}/input_schema`
)
)
.then((r) => r.json())
.then(simplifySchema)
.then((input) => setSchemas((current) => ({ ...current, input })))
.catch(() => {}); // ignore errors, eg. due to incomplete config
}
}, [debouncedConfigData]);
return schemas;
}
@@ -0,0 +1,42 @@
import {
MutableRefObject,
createContext,
useContext,
useEffect,
useRef,
} from "react";
import { StreamCallback } from "./types";
export const AppCallbackContext = createContext<MutableRefObject<{
onStart: Exclude<StreamCallback["onStart"], undefined>[];
onSuccess: Exclude<StreamCallback["onSuccess"], undefined>[];
onError: Exclude<StreamCallback["onError"], undefined>[];
}> | null>(null);
export function useStreamCallback<
Type extends "onStart" | "onSuccess" | "onError"
>(type: Type, callback: Exclude<StreamCallback[Type], undefined>) {
type CallbackType = Exclude<StreamCallback[Type], undefined>;
const appCbRef = useContext(AppCallbackContext);
const callbackRef = useRef<CallbackType>(callback);
callbackRef.current = callback;
useEffect(() => {
// @ts-expect-error Not sure why I can't expand the tuple
const current = (...args) => callbackRef.current?.(...args);
appCbRef?.current[type].push(current);
return () => {
if (!appCbRef) return;
// @ts-expect-error Assingability issues due to the tuple object
// eslint-disable-next-line react-hooks/exhaustive-deps
appCbRef.current[type] = appCbRef.current[type].filter(
(callbacks) => callbacks !== current
);
};
}, [type, appCbRef]);
}
+21 -4
View File
@@ -1,7 +1,8 @@
import { useCallback, useReducer, useState } from "react";
import { useCallback, useRef, useState } from "react";
import { applyPatch, Operation } from "fast-json-patch";
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { resolveApiUrl } from "./utils/url";
import { StreamCallback } from "./types";
export interface LogEntry {
// ID of the sub-run.
@@ -44,13 +45,26 @@ function reducer(state: RunState | null, action: Operation[]) {
return applyPatch(state, action, true, false).newDocument;
}
export function useStreamLog() {
const [latest, updateLatest] = useReducer(reducer, null);
export function useStreamLog(callbacks: StreamCallback = {}) {
const [latest, setLatest] = useState<RunState | null>(null);
const [controller, setController] = useState<AbortController | null>(null);
const startRef = useRef(callbacks.onStart);
startRef.current = callbacks.onStart;
const successRef = useRef(callbacks.onSuccess);
successRef.current = callbacks.onSuccess;
const errorRef = useRef(callbacks.onError);
errorRef.current = callbacks.onError;
const startStream = useCallback(async (input: unknown, config: unknown) => {
const controller = new AbortController();
setController(controller);
startRef.current?.({ input });
let innerLatest: RunState | null = null;
await fetchEventSource(resolveApiUrl("/stream_log").toString(), {
signal: controller.signal,
method: "POST",
@@ -58,14 +72,17 @@ export function useStreamLog() {
body: JSON.stringify({ input, config }),
onmessage(msg) {
if (msg.event === "data") {
updateLatest(JSON.parse(msg.data)?.ops);
innerLatest = reducer(innerLatest, JSON.parse(msg.data)?.ops);
setLatest(innerLatest);
}
},
onclose() {
setController(null);
successRef.current?.({ input, output: innerLatest?.final_output });
},
onerror(error) {
setController(null);
errorRef.current?.();
throw error;
},
});
+220
View File
@@ -0,0 +1,220 @@
// (c) 2015 Chute Corporation. Released under the terms of the MIT License.
// Modified to use TypeScript and handle edge cases with tuples
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable no-prototype-builtins */
"use strict";
/**
* check whether item is plain object
* @param {*} item
* @return {Boolean}
*/
const isObject = (item: unknown): item is Record<string, unknown> => {
return (
typeof item === "object" &&
item !== null &&
item.toString() === {}.toString()
);
};
/**
* deep JSON object clone
*
* @param {Object} source
* @return {Object}
*/
const cloneJSON = (source: any): any => {
return JSON.parse(JSON.stringify(source));
};
/**
* returns a result of deep merge of two objects
*
* @param {Object} target
* @param {Object} source
* @return {Object}
*/
const merge = (
target: Record<string, unknown>,
source: Record<string, unknown>
) => {
target = cloneJSON(target);
for (const key in source) {
if (source.hasOwnProperty(key)) {
const sourceKeyValue = source[key];
const targetKeyValue = target[key];
if (isObject(sourceKeyValue) && isObject(targetKeyValue)) {
target[key] = merge(targetKeyValue, sourceKeyValue);
} else {
target[key] = sourceKeyValue;
}
}
}
return target;
};
/**
* get object by reference. works only with local references that points on
* definitions object
*
* @param {String} path
* @param {Object} definitions
* @return {Object}
*/
const getLocalRef = function (
inputPath: string,
definitions: Record<string, unknown>
) {
const path = inputPath.replace(/^#\/definitions\//, "").split("/");
const find = function (path: string[], root: any): any {
const key = path.shift();
if (!key) return {};
if (!root[key]) {
return {};
} else if (!path.length) {
return root[key];
} else {
return find(path, root[key]);
}
};
const result = find(path, definitions);
if (!isObject(result)) {
return result;
}
return cloneJSON(result);
};
/**
* merge list of objects from allOf properties
* if some of objects contains $ref field extracts this reference and merge it
*
* @param {Array} allOfList
* @param {Object} definitions
* @return {Object}
*/
const mergeAllOf = function (allOfList: any[], definitions: any) {
const length = allOfList.length;
let index = -1,
result = {};
while (++index < length) {
let item = allOfList[index];
item =
typeof item.$ref !== "undefined"
? getLocalRef(item.$ref, definitions)
: item;
result = merge(result, item);
}
return result;
};
/**
* returns a object that built with default values from json schema
*
* @param {Object} schema
* @param {Object} definitions
* @return {Object}
*/
const defaults = (schema: any, definitions: Record<string, any>): unknown => {
if (typeof schema["default"] !== "undefined") {
return schema["default"];
} else if (typeof schema.allOf !== "undefined") {
const mergedItem = mergeAllOf(schema.allOf, definitions);
return defaults(mergedItem, definitions);
} else if (typeof schema.$ref !== "undefined") {
const reference = getLocalRef(schema.$ref, definitions);
return defaults(reference, definitions);
} else if (schema.type === "object") {
if (!schema.properties) {
return {};
}
for (const key in schema.properties) {
if (schema.properties.hasOwnProperty(key)) {
schema.properties[key] = defaults(schema.properties[key], definitions);
if (typeof schema.properties[key] === "undefined") {
delete schema.properties[key];
}
}
}
return schema.properties;
} else if (schema.type === "array") {
if (!schema.items) {
return [];
}
// minimum item count
const ct = schema.minItems || 0;
// tuple-typed arrays
if (schema.items.constructor === Array) {
const values = schema.items.map((item: unknown) =>
defaults(item, definitions)
);
// remove undefined items at the end (unless required by minItems)
for (let i = values.length - 1; i >= 0; i--) {
if (typeof values[i] !== "undefined") {
break;
}
if (i + 1 > ct) {
values.pop();
}
}
// if all values are undefined -> return undefined even
// if minItems is set
if (values.every((item: unknown) => typeof item === "undefined")) {
return undefined;
}
return values;
}
// object-typed arrays
const value = defaults(schema.items, definitions);
if (typeof value === "undefined") {
return [];
} else {
const values = [];
for (let i = 0; i < Math.max(0, ct); i++) {
values.push(cloneJSON(value));
}
return values;
}
}
};
/**
* main function
*
* @param {Object} schema
* @param {Object|undefined} definitions
* @return {Object}
*/
export default function (
schema: any,
definitions?: Record<string, unknown> | undefined
) {
if (typeof definitions === "undefined") {
definitions = (schema.definitions as Record<string, unknown>) || {};
} else if (isObject(schema.definitions)) {
definitions = merge(definitions, schema.definitions);
}
return defaults(cloneJSON(schema), definitions);
}
+24
View File
@@ -0,0 +1,24 @@
function isAccessibleObject(x: unknown): x is Record<string | number, unknown> {
return typeof x === "object" && x != null;
}
export function traverseNaiveJsonPath(
x: unknown,
path: string | number | Array<string | number>
) {
const queue = Array.isArray(path) ? path : [path];
let tmp: unknown = x;
while (queue.length > 0) {
const first = queue.shift()!;
if (first === "") continue;
if (Array.isArray(tmp)) {
tmp = tmp[+first];
} else if (isAccessibleObject(tmp)) {
tmp = tmp[first];
} else {
return undefined;
}
}
return tmp;
}
+28
View File
@@ -0,0 +1,28 @@
import { JsonSchema } from "@jsonforms/core";
type JsonSchemaExtra = JsonSchema & {
extra: {
widget: {
type: string;
[key: string]: string | number | Array<string | number>;
};
};
};
export function isJsonSchemaExtra(x: JsonSchema): x is JsonSchemaExtra {
if (!("extra" in x && typeof x.extra === "object" && x.extra != null)) {
return false;
}
if (
!(
"widget" in x.extra &&
typeof x.extra.widget === "object" &&
x.extra.widget != null
)
) {
return false;
}
return true;
}
+5
View File
@@ -0,0 +1,5 @@
export function str(o: unknown): React.ReactNode {
return typeof o === "object"
? JSON.stringify(o, null, 2)
: (o as React.ReactNode);
}
+2 -5
View File
@@ -1,8 +1,5 @@
export function resolveApiUrl(path: string) {
if (import.meta.env.DEV) {
return new URL(path, "http://127.0.0.1:8000");
}
const prefix = window.location.pathname.split("/playground")[0];
let prefix = window.location.pathname.split("/playground")[0];
if (prefix.endsWith("/")) prefix = prefix.slice(0, -1);
return new URL(prefix + path, window.location.origin);
}
+9
View File
@@ -6,4 +6,13 @@ import svgr from "vite-plugin-svgr";
export default defineConfig({
base: "/____LANGSERVE_BASE_URL/",
plugins: [svgr(), react()],
server: {
proxy: {
"^/____LANGSERVE_BASE_URL.*/(config_schema|input_schema|stream_log)": {
target: "http://127.0.0.1:8000",
changeOrigin: true,
rewrite: (path) => path.replace("/____LANGSERVE_BASE_URL", ""),
},
},
},
});
+63 -19
View File
@@ -736,6 +736,17 @@
dependencies:
"@babel/runtime" "^7.13.10"
"@radix-ui/react-collection@1.0.3":
version "1.0.3"
resolved "https://registry.yarnpkg.com/@radix-ui/react-collection/-/react-collection-1.0.3.tgz#9595a66e09026187524a36c6e7e9c7d286469159"
integrity sha512-3SzW+0PW7yBBoQlT8wNcGtaxaD0XSu0uLUFgrtHY08Acx05TaHaOmVLR73c0j/cqpDy53KBMO7s0dx2wmOIDIA==
dependencies:
"@babel/runtime" "^7.13.10"
"@radix-ui/react-compose-refs" "1.0.1"
"@radix-ui/react-context" "1.0.1"
"@radix-ui/react-primitive" "1.0.3"
"@radix-ui/react-slot" "1.0.2"
"@radix-ui/react-compose-refs@1.0.1":
version "1.0.1"
resolved "https://registry.yarnpkg.com/@radix-ui/react-compose-refs/-/react-compose-refs-1.0.1.tgz#7ed868b66946aa6030e580b1ffca386dd4d21989"
@@ -771,6 +782,13 @@
aria-hidden "^1.1.1"
react-remove-scroll "2.5.5"
"@radix-ui/react-direction@1.0.1":
version "1.0.1"
resolved "https://registry.yarnpkg.com/@radix-ui/react-direction/-/react-direction-1.0.1.tgz#9cb61bf2ccf568f3421422d182637b7f47596c9b"
integrity sha512-RXcvnXgyvYvBEOhCBuddKecVkoMiI10Jcm5cTI7abJRAHYfFxeu+FBQs/DvdxSYucxR5mna0dNsL6QFlds5TMA==
dependencies:
"@babel/runtime" "^7.13.10"
"@radix-ui/react-dismissable-layer@1.0.5":
version "1.0.5"
resolved "https://registry.yarnpkg.com/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.0.5.tgz#3f98425b82b9068dfbab5db5fff3df6ebf48b9d4"
@@ -833,6 +851,22 @@
"@babel/runtime" "^7.13.10"
"@radix-ui/react-slot" "1.0.2"
"@radix-ui/react-roving-focus@1.0.4":
version "1.0.4"
resolved "https://registry.yarnpkg.com/@radix-ui/react-roving-focus/-/react-roving-focus-1.0.4.tgz#e90c4a6a5f6ac09d3b8c1f5b5e81aab2f0db1974"
integrity sha512-2mUg5Mgcu001VkGy+FfzZyzbmuUWzgWkj3rvv4yu+mLw03+mTzbxZHvfcGyFp2b8EkQeMkpRQ5FiA2Vr2O6TeQ==
dependencies:
"@babel/runtime" "^7.13.10"
"@radix-ui/primitive" "1.0.1"
"@radix-ui/react-collection" "1.0.3"
"@radix-ui/react-compose-refs" "1.0.1"
"@radix-ui/react-context" "1.0.1"
"@radix-ui/react-direction" "1.0.1"
"@radix-ui/react-id" "1.0.1"
"@radix-ui/react-primitive" "1.0.3"
"@radix-ui/react-use-callback-ref" "1.0.1"
"@radix-ui/react-use-controllable-state" "1.0.1"
"@radix-ui/react-slot@1.0.2":
version "1.0.2"
resolved "https://registry.yarnpkg.com/@radix-ui/react-slot/-/react-slot-1.0.2.tgz#a9ff4423eade67f501ffb32ec22064bc9d3099ab"
@@ -841,6 +875,30 @@
"@babel/runtime" "^7.13.10"
"@radix-ui/react-compose-refs" "1.0.1"
"@radix-ui/react-toggle-group@^1.0.4":
version "1.0.4"
resolved "https://registry.yarnpkg.com/@radix-ui/react-toggle-group/-/react-toggle-group-1.0.4.tgz#f5b5c8c477831b013bec3580c55e20a68179d6ec"
integrity sha512-Uaj/M/cMyiyT9Bx6fOZO0SAG4Cls0GptBWiBmBxofmDbNVnYYoyRWj/2M/6VCi/7qcXFWnHhRUfdfZFvvkuu8A==
dependencies:
"@babel/runtime" "^7.13.10"
"@radix-ui/primitive" "1.0.1"
"@radix-ui/react-context" "1.0.1"
"@radix-ui/react-direction" "1.0.1"
"@radix-ui/react-primitive" "1.0.3"
"@radix-ui/react-roving-focus" "1.0.4"
"@radix-ui/react-toggle" "1.0.3"
"@radix-ui/react-use-controllable-state" "1.0.1"
"@radix-ui/react-toggle@1.0.3":
version "1.0.3"
resolved "https://registry.yarnpkg.com/@radix-ui/react-toggle/-/react-toggle-1.0.3.tgz#aecb2945630d1dc5c512997556c57aba894e539e"
integrity sha512-Pkqg3+Bc98ftZGsl60CLANXQBBQ4W3mTFS9EJvNxKMZ7magklKV69/id1mlAlOFDDfHvlCms0fx8fA4CMKDJHg==
dependencies:
"@babel/runtime" "^7.13.10"
"@radix-ui/primitive" "1.0.1"
"@radix-ui/react-primitive" "1.0.3"
"@radix-ui/react-use-controllable-state" "1.0.1"
"@radix-ui/react-use-callback-ref@1.0.1":
version "1.0.1"
resolved "https://registry.yarnpkg.com/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.0.1.tgz#f4bb1f27f2023c984e6534317ebc411fc181107a"
@@ -1224,13 +1282,6 @@ arg@^5.0.2:
resolved "https://registry.yarnpkg.com/arg/-/arg-5.0.2.tgz#c81433cc427c92c4dcf4865142dbca6f15acd59c"
integrity sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==
argparse@^1.0.9:
version "1.0.10"
resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911"
integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==
dependencies:
sprintf-js "~1.0.2"
argparse@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38"
@@ -1985,13 +2036,6 @@ json-parse-even-better-errors@^2.3.0:
resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d"
integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==
json-schema-defaults@^0.4.0:
version "0.4.0"
resolved "https://registry.yarnpkg.com/json-schema-defaults/-/json-schema-defaults-0.4.0.tgz#b63ee7e7aa83f29b54cb31d31ecddeb056c3306c"
integrity sha512-UsUrkDVNvHTneyeQOYHH9ZHb3+6OjwYfJ831SdO0yjtXtYZ7Jh8BKWsuJYUQW7qckP5JhHawsg4GI6A5fMaR/Q==
dependencies:
argparse "^1.0.9"
json-schema-traverse@^0.4.1:
version "0.4.1"
resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660"
@@ -2522,11 +2566,6 @@ source-map@^0.5.7:
resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc"
integrity sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==
sprintf-js@~1.0.2:
version "1.0.3"
resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c"
integrity sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==
strip-ansi@^6.0.1:
version "6.0.1"
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
@@ -2699,6 +2738,11 @@ use-callback-ref@^1.3.0:
dependencies:
tslib "^2.0.0"
use-debounce@^9.0.4:
version "9.0.4"
resolved "https://registry.yarnpkg.com/use-debounce/-/use-debounce-9.0.4.tgz#51d25d856fbdfeb537553972ce3943b897f1ac85"
integrity sha512-6X8H/mikbrt0XE8e+JXRtZ8yYVvKkdYRfmIhWZYsP8rcNs9hk3APV8Ua2mFkKRLcJKVdnX2/Vwrmg2GWKUQEaQ==
use-sidecar@^1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/use-sidecar/-/use-sidecar-1.1.2.tgz#2f43126ba2d7d7e117aa5855e5d8f0276dfe73c2"
+33
View File
@@ -0,0 +1,33 @@
from importlib import metadata
## Create namespaces for pydantic v1 and v2.
# This code must stay at the top of the file before other modules may
# attempt to import pydantic since it adds pydantic_v1 and pydantic_v2 to sys.modules.
#
# This hack is done for the following reasons:
# * Langchain will attempt to remain compatible with both pydantic v1 and v2 since
# both dependencies and dependents may be stuck on either version of v1 or v2.
# * Creating namespaces for pydantic v1 and v2 should allow us to write code that
# unambiguously uses either v1 or v2 API.
# * This change is easier to roll out and roll back.
try:
# F401: imported but unused
from pydantic.v1 import ( # noqa: F401
BaseModel,
Field,
ValidationError,
create_model,
)
except ImportError:
from pydantic import BaseModel, Field, ValidationError, create_model # noqa: F401
# This is not a pydantic v1 thing, but it feels too small to create a new module for.
PYDANTIC_VERSION = metadata.version("pydantic")
try:
_PYDANTIC_MAJOR_VERSION: int = int(PYDANTIC_VERSION.split(".")[0])
except metadata.PackageNotFoundError:
_PYDANTIC_MAJOR_VERSION = -1
+109
View File
@@ -0,0 +1,109 @@
from datetime import datetime
from typing import Dict, List, Optional, Union
from uuid import UUID
from pydantic import BaseModel # Floats between v1 and v2
from langserve.pydantic_v1 import BaseModel as BaseModelV1
class CustomUserType(BaseModelV1):
"""Inherit from this class to create a custom user type.
Use a custom user type if you want the data to de-serialize
into a pydantic model rather than the equivalent dict representation.
In general, make sure to add a `type` attribute to your class
to help pydantic to discriminate unions.
https://docs.pydantic.dev/1.10/usage/types/#discriminated-unions-aka-tagged-unions
Limitations:
At the moment, this type only works SERVER side and is used
to specify desired DECODING behavior. If inheriting from this type
the server will keep the decoded type as a pydantic model instead
of converting it into a dict.
"""
class SharedResponseMetadata(BaseModelV1):
"""
Any response metadata should inherit from this class. Response metadata
represents non-output data that may be useful to some clients, but
ignorable to most. For example, the run_ids associated with each run
kicked off by the associated request.
SharedResponseMetadata is an abstraction to represent any metadata
representing a LangServe response shared across all outputs in said
response.
"""
pass
class SingletonResponseMetadata(SharedResponseMetadata):
"""
Represents response metadata used for just single input/output LangServe
responses.
"""
# Represents the parent run id for a given request
run_id: UUID
class BatchResponseMetadata(SharedResponseMetadata):
"""
Represents response metadata used for batches of input/output LangServe
responses.
"""
# Represents each parent run id for a given request, in
# the same order in which they were received
run_ids: List[UUID]
class BaseFeedback(BaseModel):
"""
Shared information between create requests of feedback and feedback objects
"""
run_id: UUID
"""The associated run ID this feedback is logged for."""
key: str
"""The metric name, tag, or aspect to provide feedback on."""
score: Optional[Union[float, int, bool]] = None
"""Value or score to assign the run."""
value: Optional[Union[float, int, bool, str, Dict]] = None
"""The display value for the feedback if not a metric."""
comment: Optional[str] = None
"""Comment or explanation for the feedback."""
class FeedbackCreateRequest(BaseFeedback):
"""
Represents a request that creates feedback for an individual run
"""
pass
class Feedback(BaseFeedback):
"""
Represents feedback given on an individual run
"""
id: UUID
"""The unique ID of the feedback that was created."""
created_at: datetime
"""The time the feedback was created."""
modified_at: datetime
"""The time the feedback was last modified."""
correction: Optional[Dict] = None
"""Correction for the run."""
+163 -39
View File
@@ -1,11 +1,21 @@
"""Serialization module for Well Known LangChain objects.
"""Serialization for well known objects and callback events.
Specialized JSON serialization for well known LangChain objects that
can be expected to be frequently transmitted between chains.
"""
import json
from typing import Any, Union
Callback events handle well known objects together with a few other
common types like UUIDs and Exceptions that might appear in the callback.
By default, exceptions are serialized as a generic exception without
any information about the exception. This is done to prevent leaking
sensitive information from the server to the client.
"""
import abc
import logging
from functools import lru_cache
from typing import Any, Dict, List, Union
import orjson
from langchain.prompts.base import StringPromptValue
from langchain.prompts.chat import ChatPromptValueConcrete
from langchain.schema.agent import AgentAction, AgentActionMessageLog, AgentFinish
@@ -22,11 +32,23 @@ from langchain.schema.messages import (
SystemMessage,
SystemMessageChunk,
)
from langchain.schema.output import (
ChatGeneration,
ChatGenerationChunk,
Generation,
LLMResult,
)
try:
from pydantic.v1 import BaseModel, ValidationError
except ImportError:
from pydantic import BaseModel, ValidationError
from langserve.pydantic_v1 import BaseModel, ValidationError
from langserve.validation import CallbackEvent
logger = logging.getLogger(__name__)
@lru_cache(maxsize=1_000) # Will accommodate up to 1_000 different error messages
def _log_error_message_once(error_message: str) -> None:
"""Log an error message once."""
logger.error(error_message)
class WellKnownLCObject(BaseModel):
@@ -54,54 +76,156 @@ class WellKnownLCObject(BaseModel):
AgentAction,
AgentFinish,
AgentActionMessageLog,
LLMResult,
ChatGeneration,
Generation,
ChatGenerationChunk,
]
# Custom JSON Encoder
class _LangChainEncoder(json.JSONEncoder):
"""Custom JSON Encoder that can encode pydantic objects as well."""
def default(self, obj) -> Any:
if isinstance(obj, BaseModel):
return obj.dict()
return super().default(obj)
def default(obj) -> Any:
"""Default serialization for well known objects."""
if isinstance(obj, BaseModel):
return obj.dict()
return super().default(obj)
# Custom JSON Decoder
class _LangChainDecoder(json.JSONDecoder):
"""Custom JSON Decoder that handles well known LangChain objects."""
def _decode_lc_objects(value: Any) -> Any:
"""Decode the value."""
if isinstance(value, dict):
v = {key: _decode_lc_objects(v) for key, v in value.items()}
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Initialize the LangChainDecoder."""
super().__init__(object_hook=self.decoder, *args, **kwargs)
try:
obj = WellKnownLCObject.parse_obj(v)
parsed = obj.__root__
if set(parsed.dict()) != set(value):
raise ValueError("Invalid object")
return parsed
except (ValidationError, ValueError):
return v
elif isinstance(value, list):
return [_decode_lc_objects(item) for item in value]
else:
return value
def decoder(self, value) -> Any:
"""Decode the value."""
if isinstance(value, dict):
class ServerSideException(Exception):
"""Exception raised when a server side exception occurs.
The goal of this exception is to provide a way to communicate
to the client that a server side exception occurred without
revealing too much information about the exception as it may contain
sensitive information.
"""
def _decode_event_data(value: Any) -> Any:
"""Decode the event data from a JSON object representation."""
if isinstance(value, dict):
try:
obj = CallbackEvent.parse_obj(value)
return obj.__root__
except ValidationError:
try:
obj = WellKnownLCObject.parse_obj(value)
return obj.__root__
except ValidationError:
return {key: self.decoder(v) for key, v in value.items()}
elif isinstance(value, list):
return [self.decoder(item) for item in value]
else:
return value
return {key: _decode_event_data(v) for key, v in value.items()}
elif isinstance(value, list):
return [_decode_event_data(item) for item in value]
else:
return value
# PUBLIC API
def simple_dumpd(obj: Any) -> Any:
"""Convert the given object to a JSON serializable object."""
return json.loads(json.dumps(obj, cls=_LangChainEncoder))
class Serializer(abc.ABC):
@abc.abstractmethod
def dumpd(self, obj: Any) -> Any:
"""Convert the given object to a JSON serializable object."""
@abc.abstractmethod
def dumps(self, obj: Any) -> bytes:
"""Dump the given object as a JSON string."""
@abc.abstractmethod
def loads(self, s: bytes) -> Any:
"""Load the given JSON string."""
@abc.abstractmethod
def loadd(self, obj: Any) -> Any:
"""Load the given object."""
def simple_dumps(obj: Any) -> str:
"""Dump the given object as a JSON string."""
return json.dumps(obj, cls=_LangChainEncoder)
class WellKnownLCSerializer(Serializer):
def dumpd(self, obj: Any) -> Any:
"""Convert the given object to a JSON serializable object."""
return orjson.loads(orjson.dumps(obj, default=default))
def dumps(self, obj: Any) -> bytes:
"""Dump the given object as a JSON string."""
return orjson.dumps(obj, default=default)
def loadd(self, obj: Any) -> Any:
"""Load the given object."""
return _decode_lc_objects(obj)
def loads(self, s: bytes) -> Any:
"""Load the given JSON string."""
return self.loadd(orjson.loads(s))
def simple_loads(s: str) -> Any:
"""Load the given JSON string."""
return json.loads(s, cls=_LangChainDecoder)
def _project_top_level(model: BaseModel) -> Dict[str, Any]:
"""Project the top level of the model as dict."""
return {key: getattr(model, key) for key in model.__fields__}
def load_events(events: Any) -> List[Dict[str, Any]]:
"""Load and validate the event.
Args:
events: The events to load and validate.
Returns:
The loaded and validated events.
"""
if not isinstance(events, list):
_log_error_message_once(f"Expected a list got {type(events)}")
return []
decoded_events = []
for event in events:
if not isinstance(event, dict):
_log_error_message_once(f"Expected a dict got {type(event)}")
# Discard the event / potentially error
continue
# First load all inner objects
decoded_event_data = {
key: _decode_lc_objects(value) for key, value in event.items()
}
# Then validate the event
try:
full_event = CallbackEvent.parse_obj(decoded_event_data)
except ValidationError as e:
msg = f"Encountered an invalid event: {e}"
if "type" in decoded_event_data:
msg += f' of type {repr(decoded_event_data["type"])}'
_log_error_message_once(msg)
continue
decoded_event_data = _project_top_level(full_event.__root__)
if decoded_event_data["type"].endswith("_error"):
# Data is validated by this point, so we can assume that the shape
# of the data is correct
error = decoded_event_data["error"]
msg = f"{error['status_code']}: {error['message']}"
decoded_event_data["error"] = ServerSideException(msg)
decoded_events.append(decoded_event_data)
return decoded_events
+1059 -240
View File
File diff suppressed because it is too large Load Diff
+277 -1
View File
@@ -16,7 +16,18 @@ Models are created with a namespace to avoid name collisions when hosting
multiple runnables. When present the name collisions prevent fastapi from
generating OpenAPI specs.
"""
from typing import List, Optional, Sequence, Union
from typing import Any, Dict, List, Literal, Optional, Sequence, Union
from uuid import UUID
from langchain.schema import (
BaseMessage,
ChatGeneration,
Document,
Generation,
RunInfo,
)
from langserve.schema import BatchResponseMetadata, SingletonResponseMetadata
try:
from pydantic.v1 import BaseModel, Field, create_model
@@ -184,6 +195,14 @@ def create_stream_log_request_model(
return stream_log_request
class InvokeBaseResponse(BaseModel):
"""Base class for invoke request."""
class BatchBaseResponse(BaseModel):
"""Base class for batch response."""
def create_invoke_response_model(
namespace: str,
output_type: Validator,
@@ -194,6 +213,21 @@ def create_invoke_response_model(
invoke_response_type = create_model(
f"{namespace}InvokeResponse",
output=(output_type, Field(..., description="The output of the invocation.")),
callback_events=(
List[CallbackEvent],
Field(..., description="Callback events generated by the server side."),
),
metadata=(
SingletonResponseMetadata,
Field(
...,
description=(
"Metadata about the response that may be useful to "
"specific clients"
),
),
),
__base__=InvokeBaseResponse,
)
invoke_response_type.update_forward_refs()
return invoke_response_type
@@ -217,6 +251,248 @@ def create_batch_response_model(
),
),
),
callback_events=(
List[List[CallbackEvent]],
Field(
...,
description=(
"Callback events generated by the server side."
"The outer list corresponds to the inputs and the inner "
"list corresponds to the callbacks generated for that input."
),
),
),
metadata=(
BatchResponseMetadata,
Field(
...,
description=(
"Metadata about the response that may be useful to specific clients"
),
),
),
__base__=BatchBaseResponse,
)
batch_response_type.update_forward_refs()
return batch_response_type
class InvokeRequestShallowValidator(BaseModel):
"""Shallow validator for Invoke Request.
Validate basic shape of invoke request, downstream code
is expected to do further validation.
"""
input: Any = Field(..., description="The input to the runnable.")
config: Optional[Dict[str, Any]] = Field(default_factory=dict)
class BatchRequestShallowValidator(BaseModel):
"""Shallow validator for Batch Request."""
inputs: Any = Field(..., description="The inputs to the runnable.")
config: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = Field(
default_factory=dict
)
class StreamLogParameters(BaseModel):
"""Shallow validator for Stream Log Request"""
include_names: Optional[Sequence[str]] = None
include_types: Optional[Sequence[str]] = None
include_tags: Optional[Sequence[str]] = None
exclude_names: Optional[Sequence[str]] = None
exclude_types: Optional[Sequence[str]] = None
exclude_tags: Optional[Sequence[str]] = None
# Pydantic validators for callback events
# These objects may have a slightly different shape than the callback events
# used internally in langchain because they represent a serialized version
# of the callback event.
# For example, exceptions are replaced by error objects consisting of a
# status code and a message.
class OnChainStart(BaseModel):
"""On Chain Start Callback Event."""
serialized: Dict[str, Any]
inputs: Any
run_id: UUID
parent_run_id: Optional[UUID] = None
tags: Optional[List[str]] = None
metadata: Optional[Dict[str, Any]] = None
kwargs: Any = None
type: Literal["on_chain_start"] = "on_chain_start"
class OnChainEnd(BaseModel):
"""On Chain End Callback Event."""
outputs: Any
run_id: UUID
parent_run_id: Optional[UUID] = None
tags: Optional[List[str]] = None
kwargs: Any = None
type: Literal["on_chain_end"] = "on_chain_end"
class Error(BaseModel):
"""Error object that is modeled after an HTTP error format."""
status_code: int
message: str
type: Literal["error"] = "error"
class OnChainError(BaseModel):
"""On Chain Error Callback Event."""
error: Error
run_id: UUID
parent_run_id: Optional[UUID] = None
tags: Optional[List[str]] = None
kwargs: Any = None
type: Literal["on_chain_error"] = "on_chain_error"
class OnToolStart(BaseModel):
"""On Tool Start Callback Event."""
serialized: Dict[str, Any]
input_str: str
run_id: UUID
parent_run_id: Optional[UUID] = None
tags: Optional[List[str]] = None
metadata: Optional[Dict[str, Any]] = None
kwargs: Any = None
type: Literal["on_tool_start"] = "on_tool_start"
class OnToolEnd(BaseModel):
"""On Tool End Callback Event."""
output: str
run_id: UUID
parent_run_id: Optional[UUID] = None
tags: Optional[List[str]] = None
kwargs: Any = None
type: Literal["on_tool_end"] = "on_tool_end"
class OnToolError(BaseModel):
"""On Tool Error Callback Event."""
error: Error
run_id: UUID
parent_run_id: Optional[UUID] = None
tags: Optional[List[str]] = None
kwargs: Any = None
type: Literal["on_tool_error"] = "on_tool_error"
class OnChatModelStart(BaseModel):
"""On Chat Model Start Callback Event."""
serialized: Dict[str, Any]
messages: List[List[BaseMessage]]
run_id: UUID
parent_run_id: Optional[UUID] = None
tags: Optional[List[str]] = None
metadata: Optional[Dict[str, Any]] = None
kwargs: Any = None
type: Literal["on_chat_model_start"] = "on_chat_model_start"
class OnLLMStart(BaseModel):
"""On LLM Start Callback Event."""
serialized: Dict[str, Any]
prompts: List[str]
run_id: UUID
parent_run_id: Optional[UUID] = None
tags: Optional[List[str]] = None
metadata: Optional[Dict[str, Any]] = None
kwargs: Any = None
type: Literal["on_llm_start"] = "on_llm_start"
class LLMResult(BaseModel):
"""Concrete instance of LLMResult for validation only.
Must be kept in sync with langchain.schema.llm.LLMResult.
"""
generations: List[List[Union[Generation, ChatGeneration]]]
"""List of generated outputs. This is a List[List[]] because
each input could have multiple candidate generations."""
llm_output: Optional[dict] = None
"""Arbitrary LLM provider-specific output."""
run: Optional[List[RunInfo]] = None
"""List of metadata info for model call for each input."""
class OnLLMEnd(BaseModel):
"""On LLM End Callback Event."""
response: LLMResult
run_id: UUID
parent_run_id: Optional[UUID] = None
tags: Optional[List[str]] = None
kwargs: Any = None
type: Literal["on_llm_end"] = "on_llm_end"
class OnRetrieverStart(BaseModel):
"""On Retriever Start Callback Event."""
serialized: Dict[str, Any]
query: str
run_id: UUID
parent_run_id: Optional[UUID] = None
tags: Optional[List[str]] = None
metadata: Optional[Dict[str, Any]] = None
kwargs: Any = None
type: Literal["on_retriever_start"] = "on_retriever_start"
class OnRetrieverError(BaseModel):
"""On Retriever Error Callback Event."""
error: Error
run_id: UUID
parent_run_id: Optional[UUID] = None
tags: Optional[List[str]] = None
kwargs: Any = None
type: Literal["on_retriever_error"] = "on_retriever_error"
class OnRetrieverEnd(BaseModel):
"""On Retriever End Callback Event."""
documents: Sequence[Document]
run_id: UUID
parent_run_id: Optional[UUID] = None
tags: Optional[List[str]] = None
kwargs: Any = None
type: Literal["on_retriever_end"] = "on_retriever_end"
class CallbackEvent(BaseModel):
__root__: Union[
OnChainStart,
OnChainEnd,
OnChainError,
OnChatModelStart,
OnLLMStart,
OnLLMEnd,
OnToolStart,
OnToolEnd,
OnToolError,
OnRetrieverStart,
OnRetrieverEnd,
OnRetrieverError,
]
Generated
+122 -162
View File
@@ -348,50 +348,6 @@ soupsieve = ">1.2"
html5lib = ["html5lib"]
lxml = ["lxml"]
[[package]]
name = "black"
version = "23.10.0"
description = "The uncompromising code formatter."
optional = false
python-versions = ">=3.8"
files = [
{file = "black-23.10.0-cp310-cp310-macosx_10_16_arm64.whl", hash = "sha256:f8dc7d50d94063cdfd13c82368afd8588bac4ce360e4224ac399e769d6704e98"},
{file = "black-23.10.0-cp310-cp310-macosx_10_16_x86_64.whl", hash = "sha256:f20ff03f3fdd2fd4460b4f631663813e57dc277e37fb216463f3b907aa5a9bdd"},
{file = "black-23.10.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d3d9129ce05b0829730323bdcb00f928a448a124af5acf90aa94d9aba6969604"},
{file = "black-23.10.0-cp310-cp310-win_amd64.whl", hash = "sha256:960c21555be135c4b37b7018d63d6248bdae8514e5c55b71e994ad37407f45b8"},
{file = "black-23.10.0-cp311-cp311-macosx_10_16_arm64.whl", hash = "sha256:30b78ac9b54cf87bcb9910ee3d499d2bc893afd52495066c49d9ee6b21eee06e"},
{file = "black-23.10.0-cp311-cp311-macosx_10_16_x86_64.whl", hash = "sha256:0e232f24a337fed7a82c1185ae46c56c4a6167fb0fe37411b43e876892c76699"},
{file = "black-23.10.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:31946ec6f9c54ed7ba431c38bc81d758970dd734b96b8e8c2b17a367d7908171"},
{file = "black-23.10.0-cp311-cp311-win_amd64.whl", hash = "sha256:c870bee76ad5f7a5ea7bd01dc646028d05568d33b0b09b7ecfc8ec0da3f3f39c"},
{file = "black-23.10.0-cp38-cp38-macosx_10_16_arm64.whl", hash = "sha256:6901631b937acbee93c75537e74f69463adaf34379a04eef32425b88aca88a23"},
{file = "black-23.10.0-cp38-cp38-macosx_10_16_x86_64.whl", hash = "sha256:481167c60cd3e6b1cb8ef2aac0f76165843a374346aeeaa9d86765fe0dd0318b"},
{file = "black-23.10.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f74892b4b836e5162aa0452393112a574dac85e13902c57dfbaaf388e4eda37c"},
{file = "black-23.10.0-cp38-cp38-win_amd64.whl", hash = "sha256:47c4510f70ec2e8f9135ba490811c071419c115e46f143e4dce2ac45afdcf4c9"},
{file = "black-23.10.0-cp39-cp39-macosx_10_16_arm64.whl", hash = "sha256:76baba9281e5e5b230c9b7f83a96daf67a95e919c2dfc240d9e6295eab7b9204"},
{file = "black-23.10.0-cp39-cp39-macosx_10_16_x86_64.whl", hash = "sha256:a3c2ddb35f71976a4cfeca558848c2f2f89abc86b06e8dd89b5a65c1e6c0f22a"},
{file = "black-23.10.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:db451a3363b1e765c172c3fd86213a4ce63fb8524c938ebd82919bf2a6e28c6a"},
{file = "black-23.10.0-cp39-cp39-win_amd64.whl", hash = "sha256:7fb5fc36bb65160df21498d5a3dd330af8b6401be3f25af60c6ebfe23753f747"},
{file = "black-23.10.0-py3-none-any.whl", hash = "sha256:e223b731a0e025f8ef427dd79d8cd69c167da807f5710add30cdf131f13dd62e"},
{file = "black-23.10.0.tar.gz", hash = "sha256:31b9f87b277a68d0e99d2905edae08807c007973eaa609da5f0c62def6b7c0bd"},
]
[package.dependencies]
click = ">=8.0.0"
ipython = {version = ">=7.8.0", optional = true, markers = "extra == \"jupyter\""}
mypy-extensions = ">=0.4.3"
packaging = ">=22.0"
pathspec = ">=0.9.0"
platformdirs = ">=2"
tokenize-rt = {version = ">=3.2.0", optional = true, markers = "extra == \"jupyter\""}
tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""}
typing-extensions = {version = ">=4.0.1", markers = "python_version < \"3.11\""}
[package.extras]
colorama = ["colorama (>=0.4.3)"]
d = ["aiohttp (>=3.7.4)"]
jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"]
uvloop = ["uvloop (>=0.15.2)"]
[[package]]
name = "bleach"
version = "6.1.0"
@@ -827,20 +783,20 @@ tests = ["asttokens (>=2.1.0)", "coverage", "coverage-enable-subprocess", "ipyth
[[package]]
name = "fastapi"
version = "0.103.2"
version = "0.104.0"
description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production"
optional = false
python-versions = ">=3.7"
python-versions = ">=3.8"
files = [
{file = "fastapi-0.103.2-py3-none-any.whl", hash = "sha256:3270de872f0fe9ec809d4bd3d4d890c6d5cc7b9611d721d6438f9dacc8c4ef2e"},
{file = "fastapi-0.103.2.tar.gz", hash = "sha256:75a11f6bfb8fc4d2bec0bd710c2d5f2829659c0e8c0afd5560fdda6ce25ec653"},
{file = "fastapi-0.104.0-py3-none-any.whl", hash = "sha256:456482c1178fb7beb2814b88e1885bc49f9a81f079665016feffe3e1c6a7663e"},
{file = "fastapi-0.104.0.tar.gz", hash = "sha256:9c44de45693ae037b0c6914727a29c49a40668432b67c859a87851fc6a7b74c6"},
]
[package.dependencies]
anyio = ">=3.7.1,<4.0.0"
pydantic = ">=1.7.4,<1.8 || >1.8,<1.8.1 || >1.8.1,<2.0.0 || >2.0.0,<2.0.1 || >2.0.1,<2.1.0 || >2.1.0,<3.0.0"
starlette = ">=0.27.0,<0.28.0"
typing-extensions = ">=4.5.0"
typing-extensions = ">=4.8.0"
[package.extras]
all = ["email-validator (>=2.0.0)", "httpx (>=0.23.0)", "itsdangerous (>=1.1.0)", "jinja2 (>=2.11.2)", "orjson (>=3.2.1)", "pydantic-extra-types (>=2.0.0)", "pydantic-settings (>=2.0.0)", "python-multipart (>=0.0.5)", "pyyaml (>=5.3.1)", "ujson (>=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0)", "uvicorn[standard] (>=0.12.0)"]
@@ -966,7 +922,7 @@ files = [
{file = "greenlet-3.0.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:0b72b802496cccbd9b31acea72b6f87e7771ccfd7f7927437d592e5c92ed703c"},
{file = "greenlet-3.0.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:527cd90ba3d8d7ae7dceb06fda619895768a46a1b4e423bdb24c1969823b8362"},
{file = "greenlet-3.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:37f60b3a42d8b5499be910d1267b24355c495064f271cfe74bf28b17b099133c"},
{file = "greenlet-3.0.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:1482fba7fbed96ea7842b5a7fc11d61727e8be75a077e603e8ab49d24e234383"},
{file = "greenlet-3.0.0-cp311-universal2-macosx_10_9_universal2.whl", hash = "sha256:c3692ecf3fe754c8c0f2c95ff19626584459eab110eaab66413b1e7425cd84e9"},
{file = "greenlet-3.0.0-cp312-cp312-macosx_13_0_arm64.whl", hash = "sha256:be557119bf467d37a8099d91fbf11b2de5eb1fd5fc5b91598407574848dc910f"},
{file = "greenlet-3.0.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:73b2f1922a39d5d59cc0e597987300df3396b148a9bd10b76a058a2f2772fc04"},
{file = "greenlet-3.0.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d1e22c22f7826096ad503e9bb681b05b8c1f5a8138469b255eb91f26a76634f2"},
@@ -976,6 +932,7 @@ files = [
{file = "greenlet-3.0.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:952256c2bc5b4ee8df8dfc54fc4de330970bf5d79253c863fb5e6761f00dda35"},
{file = "greenlet-3.0.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:269d06fa0f9624455ce08ae0179430eea61085e3cf6457f05982b37fd2cefe17"},
{file = "greenlet-3.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:9adbd8ecf097e34ada8efde9b6fec4dd2a903b1e98037adf72d12993a1c80b51"},
{file = "greenlet-3.0.0-cp312-universal2-macosx_10_9_universal2.whl", hash = "sha256:553d6fb2324e7f4f0899e5ad2c427a4579ed4873f42124beba763f16032959af"},
{file = "greenlet-3.0.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c6b5ce7f40f0e2f8b88c28e6691ca6806814157ff05e794cdd161be928550f4c"},
{file = "greenlet-3.0.0-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ecf94aa539e97a8411b5ea52fc6ccd8371be9550c4041011a091eb8b3ca1d810"},
{file = "greenlet-3.0.0-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:80dcd3c938cbcac986c5c92779db8e8ce51a89a849c135172c88ecbdc8c056b7"},
@@ -1654,13 +1611,13 @@ test = ["hatch", "ipykernel", "openapi-core (>=0.18.0,<0.19.0)", "openapi-spec-v
[[package]]
name = "langchain"
version = "0.0.316"
version = "0.0.333"
description = "Building applications with LLMs through composability"
optional = false
python-versions = ">=3.8.1,<4.0"
files = [
{file = "langchain-0.0.316-py3-none-any.whl", hash = "sha256:997d2ecdaf481517c90dcea86f93b98327546c357ac8f581f06d7d782a2eda2d"},
{file = "langchain-0.0.316.tar.gz", hash = "sha256:732c958d41e22a5bb55f8c0cb70914793f083d175739d476e5cbbc7715703153"},
{file = "langchain-0.0.333-py3-none-any.whl", hash = "sha256:7ee619bbdccfe15bcc4e255a30b5f2e75f9d230cdbaf572f4063dc59d4b03af6"},
{file = "langchain-0.0.333.tar.gz", hash = "sha256:64e00ecee3dd316a97f825429e286a1b207315a0cc753bcc1cd5cfcb92abbc39"},
]
[package.dependencies]
@@ -1669,7 +1626,7 @@ anyio = "<4.0"
async-timeout = {version = ">=4.0.0,<5.0.0", markers = "python_version < \"3.11\""}
dataclasses-json = ">=0.5.7,<0.7"
jsonpatch = ">=1.33,<2.0"
langsmith = ">=0.0.43,<0.1.0"
langsmith = ">=0.0.62,<0.1.0"
numpy = ">=1,<2"
pydantic = ">=1,<3"
PyYAML = ">=5.3"
@@ -1678,14 +1635,14 @@ SQLAlchemy = ">=1.4,<3"
tenacity = ">=8.1.0,<9.0.0"
[package.extras]
all = ["O365 (>=2.0.26,<3.0.0)", "aleph-alpha-client (>=2.15.0,<3.0.0)", "amadeus (>=8.1.0)", "arxiv (>=1.4,<2.0)", "atlassian-python-api (>=3.36.0,<4.0.0)", "awadb (>=0.3.9,<0.4.0)", "azure-ai-formrecognizer (>=3.2.1,<4.0.0)", "azure-ai-vision (>=0.11.1b1,<0.12.0)", "azure-cognitiveservices-speech (>=1.28.0,<2.0.0)", "azure-cosmos (>=4.4.0b1,<5.0.0)", "azure-identity (>=1.12.0,<2.0.0)", "beautifulsoup4 (>=4,<5)", "clarifai (>=9.1.0)", "clickhouse-connect (>=0.5.14,<0.6.0)", "cohere (>=4,<5)", "deeplake (>=3.6.8,<4.0.0)", "docarray[hnswlib] (>=0.32.0,<0.33.0)", "duckduckgo-search (>=3.8.3,<4.0.0)", "elasticsearch (>=8,<9)", "esprima (>=4.0.1,<5.0.0)", "faiss-cpu (>=1,<2)", "google-api-python-client (==2.70.0)", "google-auth (>=2.18.1,<3.0.0)", "google-search-results (>=2,<3)", "gptcache (>=0.1.7)", "html2text (>=2020.1.16,<2021.0.0)", "huggingface_hub (>=0,<1)", "jinja2 (>=3,<4)", "jq (>=1.4.1,<2.0.0)", "lancedb (>=0.1,<0.2)", "langkit (>=0.0.6,<0.1.0)", "lark (>=1.1.5,<2.0.0)", "libdeeplake (>=0.0.60,<0.0.61)", "librosa (>=0.10.0.post2,<0.11.0)", "lxml (>=4.9.2,<5.0.0)", "manifest-ml (>=0.0.1,<0.0.2)", "marqo (>=1.2.4,<2.0.0)", "momento (>=1.10.1,<2.0.0)", "nebula3-python (>=3.4.0,<4.0.0)", "neo4j (>=5.8.1,<6.0.0)", "networkx (>=2.6.3,<4)", "nlpcloud (>=1,<2)", "nltk (>=3,<4)", "nomic (>=1.0.43,<2.0.0)", "openai (>=0,<1)", "openlm (>=0.0.5,<0.0.6)", "opensearch-py (>=2.0.0,<3.0.0)", "pdfminer-six (>=20221105,<20221106)", "pexpect (>=4.8.0,<5.0.0)", "pgvector (>=0.1.6,<0.2.0)", "pinecone-client (>=2,<3)", "pinecone-text (>=0.4.2,<0.5.0)", "psycopg2-binary (>=2.9.5,<3.0.0)", "pymongo (>=4.3.3,<5.0.0)", "pyowm (>=3.3.0,<4.0.0)", "pypdf (>=3.4.0,<4.0.0)", "pytesseract (>=0.3.10,<0.4.0)", "python-arango (>=7.5.9,<8.0.0)", "pyvespa (>=0.33.0,<0.34.0)", "qdrant-client (>=1.3.1,<2.0.0)", "rdflib (>=6.3.2,<7.0.0)", "redis (>=4,<5)", "requests-toolbelt (>=1.0.0,<2.0.0)", "sentence-transformers (>=2,<3)", "singlestoredb (>=0.7.1,<0.8.0)", "tensorflow-text (>=2.11.0,<3.0.0)", "tigrisdb (>=1.0.0b6,<2.0.0)", "tiktoken (>=0.3.2,<0.6.0)", "torch (>=1,<3)", "transformers (>=4,<5)", "weaviate-client (>=3,<4)", "wikipedia (>=1,<2)", "wolframalpha (==5.0.0)"]
all = ["O365 (>=2.0.26,<3.0.0)", "aleph-alpha-client (>=2.15.0,<3.0.0)", "amadeus (>=8.1.0)", "arxiv (>=1.4,<2.0)", "atlassian-python-api (>=3.36.0,<4.0.0)", "awadb (>=0.3.9,<0.4.0)", "azure-ai-formrecognizer (>=3.2.1,<4.0.0)", "azure-ai-vision (>=0.11.1b1,<0.12.0)", "azure-cognitiveservices-speech (>=1.28.0,<2.0.0)", "azure-cosmos (>=4.4.0b1,<5.0.0)", "azure-identity (>=1.12.0,<2.0.0)", "beautifulsoup4 (>=4,<5)", "clarifai (>=9.1.0)", "clickhouse-connect (>=0.5.14,<0.6.0)", "cohere (>=4,<5)", "deeplake (>=3.8.3,<4.0.0)", "docarray[hnswlib] (>=0.32.0,<0.33.0)", "duckduckgo-search (>=3.8.3,<4.0.0)", "elasticsearch (>=8,<9)", "esprima (>=4.0.1,<5.0.0)", "faiss-cpu (>=1,<2)", "google-api-python-client (==2.70.0)", "google-auth (>=2.18.1,<3.0.0)", "google-search-results (>=2,<3)", "gptcache (>=0.1.7)", "html2text (>=2020.1.16,<2021.0.0)", "huggingface_hub (>=0,<1)", "jinja2 (>=3,<4)", "jq (>=1.4.1,<2.0.0)", "lancedb (>=0.1,<0.2)", "langkit (>=0.0.6,<0.1.0)", "lark (>=1.1.5,<2.0.0)", "librosa (>=0.10.0.post2,<0.11.0)", "lxml (>=4.9.2,<5.0.0)", "manifest-ml (>=0.0.1,<0.0.2)", "marqo (>=1.2.4,<2.0.0)", "momento (>=1.10.1,<2.0.0)", "nebula3-python (>=3.4.0,<4.0.0)", "neo4j (>=5.8.1,<6.0.0)", "networkx (>=2.6.3,<4)", "nlpcloud (>=1,<2)", "nltk (>=3,<4)", "nomic (>=1.0.43,<2.0.0)", "openai (>=0,<1)", "openlm (>=0.0.5,<0.0.6)", "opensearch-py (>=2.0.0,<3.0.0)", "pdfminer-six (>=20221105,<20221106)", "pexpect (>=4.8.0,<5.0.0)", "pgvector (>=0.1.6,<0.2.0)", "pinecone-client (>=2,<3)", "pinecone-text (>=0.4.2,<0.5.0)", "psycopg2-binary (>=2.9.5,<3.0.0)", "pymongo (>=4.3.3,<5.0.0)", "pyowm (>=3.3.0,<4.0.0)", "pypdf (>=3.4.0,<4.0.0)", "pytesseract (>=0.3.10,<0.4.0)", "python-arango (>=7.5.9,<8.0.0)", "pyvespa (>=0.33.0,<0.34.0)", "qdrant-client (>=1.3.1,<2.0.0)", "rdflib (>=6.3.2,<7.0.0)", "redis (>=4,<5)", "requests-toolbelt (>=1.0.0,<2.0.0)", "sentence-transformers (>=2,<3)", "singlestoredb (>=0.7.1,<0.8.0)", "tensorflow-text (>=2.11.0,<3.0.0)", "tigrisdb (>=1.0.0b6,<2.0.0)", "tiktoken (>=0.3.2,<0.6.0)", "torch (>=1,<3)", "transformers (>=4,<5)", "weaviate-client (>=3,<4)", "wikipedia (>=1,<2)", "wolframalpha (==5.0.0)"]
azure = ["azure-ai-formrecognizer (>=3.2.1,<4.0.0)", "azure-ai-vision (>=0.11.1b1,<0.12.0)", "azure-cognitiveservices-speech (>=1.28.0,<2.0.0)", "azure-core (>=1.26.4,<2.0.0)", "azure-cosmos (>=4.4.0b1,<5.0.0)", "azure-identity (>=1.12.0,<2.0.0)", "azure-search-documents (==11.4.0b8)", "openai (>=0,<1)"]
clarifai = ["clarifai (>=9.1.0)"]
cli = ["typer (>=0.9.0,<0.10.0)"]
cohere = ["cohere (>=4,<5)"]
docarray = ["docarray[hnswlib] (>=0.32.0,<0.33.0)"]
embeddings = ["sentence-transformers (>=2,<3)"]
extended-testing = ["aiosqlite (>=0.19.0,<0.20.0)", "amazon-textract-caller (<2)", "anthropic (>=0.3.11,<0.4.0)", "arxiv (>=1.4,<2.0)", "assemblyai (>=0.17.0,<0.18.0)", "atlassian-python-api (>=3.36.0,<4.0.0)", "beautifulsoup4 (>=4,<5)", "bibtexparser (>=1.4.0,<2.0.0)", "cassio (>=0.1.0,<0.2.0)", "chardet (>=5.1.0,<6.0.0)", "dashvector (>=1.0.1,<2.0.0)", "esprima (>=4.0.1,<5.0.0)", "faiss-cpu (>=1,<2)", "feedparser (>=6.0.10,<7.0.0)", "geopandas (>=0.13.1,<0.14.0)", "gitpython (>=3.1.32,<4.0.0)", "gql (>=3.4.1,<4.0.0)", "html2text (>=2020.1.16,<2021.0.0)", "jinja2 (>=3,<4)", "jq (>=1.4.1,<2.0.0)", "lxml (>=4.9.2,<5.0.0)", "markdownify (>=0.11.6,<0.12.0)", "motor (>=3.3.1,<4.0.0)", "mwparserfromhell (>=0.6.4,<0.7.0)", "mwxml (>=0.3.3,<0.4.0)", "newspaper3k (>=0.2.8,<0.3.0)", "numexpr (>=2.8.6,<3.0.0)", "openai (>=0,<1)", "openapi-schema-pydantic (>=1.2,<2.0)", "pandas (>=2.0.1,<3.0.0)", "pdfminer-six (>=20221105,<20221106)", "pgvector (>=0.1.6,<0.2.0)", "psychicapi (>=0.8.0,<0.9.0)", "py-trello (>=0.19.0,<0.20.0)", "pymupdf (>=1.22.3,<2.0.0)", "pypdf (>=3.4.0,<4.0.0)", "pypdfium2 (>=4.10.0,<5.0.0)", "pyspark (>=3.4.0,<4.0.0)", "rank-bm25 (>=0.2.2,<0.3.0)", "rapidfuzz (>=3.1.1,<4.0.0)", "rapidocr-onnxruntime (>=1.3.2,<2.0.0)", "requests-toolbelt (>=1.0.0,<2.0.0)", "rspace_client (>=2.5.0,<3.0.0)", "scikit-learn (>=1.2.2,<2.0.0)", "sqlite-vss (>=0.1.2,<0.2.0)", "streamlit (>=1.18.0,<2.0.0)", "sympy (>=1.12,<2.0)", "telethon (>=1.28.5,<2.0.0)", "timescale-vector (>=0.0.1,<0.0.2)", "tqdm (>=4.48.0)", "upstash-redis (>=0.15.0,<0.16.0)", "xata (>=1.0.0a7,<2.0.0)", "xmltodict (>=0.13.0,<0.14.0)"]
extended-testing = ["aiosqlite (>=0.19.0,<0.20.0)", "aleph-alpha-client (>=2.15.0,<3.0.0)", "anthropic (>=0.3.11,<0.4.0)", "arxiv (>=1.4,<2.0)", "assemblyai (>=0.17.0,<0.18.0)", "atlassian-python-api (>=3.36.0,<4.0.0)", "beautifulsoup4 (>=4,<5)", "bibtexparser (>=1.4.0,<2.0.0)", "cassio (>=0.1.0,<0.2.0)", "chardet (>=5.1.0,<6.0.0)", "dashvector (>=1.0.1,<2.0.0)", "esprima (>=4.0.1,<5.0.0)", "faiss-cpu (>=1,<2)", "feedparser (>=6.0.10,<7.0.0)", "fireworks-ai (>=0.6.0,<0.7.0)", "geopandas (>=0.13.1,<0.14.0)", "gitpython (>=3.1.32,<4.0.0)", "google-cloud-documentai (>=2.20.1,<3.0.0)", "gql (>=3.4.1,<4.0.0)", "html2text (>=2020.1.16,<2021.0.0)", "jinja2 (>=3,<4)", "jq (>=1.4.1,<2.0.0)", "jsonschema (>1)", "lxml (>=4.9.2,<5.0.0)", "markdownify (>=0.11.6,<0.12.0)", "motor (>=3.3.1,<4.0.0)", "mwparserfromhell (>=0.6.4,<0.7.0)", "mwxml (>=0.3.3,<0.4.0)", "newspaper3k (>=0.2.8,<0.3.0)", "numexpr (>=2.8.6,<3.0.0)", "openai (>=0,<1)", "openapi-pydantic (>=0.3.2,<0.4.0)", "pandas (>=2.0.1,<3.0.0)", "pdfminer-six (>=20221105,<20221106)", "pgvector (>=0.1.6,<0.2.0)", "psychicapi (>=0.8.0,<0.9.0)", "py-trello (>=0.19.0,<0.20.0)", "pymupdf (>=1.22.3,<2.0.0)", "pypdf (>=3.4.0,<4.0.0)", "pypdfium2 (>=4.10.0,<5.0.0)", "pyspark (>=3.4.0,<4.0.0)", "rank-bm25 (>=0.2.2,<0.3.0)", "rapidfuzz (>=3.1.1,<4.0.0)", "rapidocr-onnxruntime (>=1.3.2,<2.0.0)", "requests-toolbelt (>=1.0.0,<2.0.0)", "rspace_client (>=2.5.0,<3.0.0)", "scikit-learn (>=1.2.2,<2.0.0)", "sqlite-vss (>=0.1.2,<0.2.0)", "streamlit (>=1.18.0,<2.0.0)", "sympy (>=1.12,<2.0)", "telethon (>=1.28.5,<2.0.0)", "timescale-vector (>=0.0.1,<0.0.2)", "tqdm (>=4.48.0)", "upstash-redis (>=0.15.0,<0.16.0)", "xata (>=1.0.0a7,<2.0.0)", "xmltodict (>=0.13.0,<0.14.0)"]
javascript = ["esprima (>=4.0.1,<5.0.0)"]
llms = ["clarifai (>=9.1.0)", "cohere (>=4,<5)", "huggingface_hub (>=0,<1)", "manifest-ml (>=0.0.1,<0.0.2)", "nlpcloud (>=1,<2)", "openai (>=0,<1)", "openlm (>=0.0.5,<0.0.6)", "torch (>=1,<3)", "transformers (>=4,<5)"]
openai = ["openai (>=0,<1)", "tiktoken (>=0.3.2,<0.6.0)"]
@@ -1694,13 +1651,13 @@ text-helpers = ["chardet (>=5.1.0,<6.0.0)"]
[[package]]
name = "langsmith"
version = "0.0.44"
version = "0.0.64"
description = "Client library to connect to the LangSmith LLM Tracing and Evaluation Platform."
optional = false
python-versions = ">=3.8.1,<4.0"
files = [
{file = "langsmith-0.0.44-py3-none-any.whl", hash = "sha256:5e7e5b45360ce89a2d5d6066a3b9fdd31b1f874a0cf19b1666c9792fecef0a1b"},
{file = "langsmith-0.0.44.tar.gz", hash = "sha256:74a262ba23a958ca1a4863d5386c151be462e40ccfcb8b39d0a5d8c9eaa40164"},
{file = "langsmith-0.0.64-py3-none-any.whl", hash = "sha256:461acdcd8332d1325c16dc57e8a2d5ec9d1578490a4eaabe14db74db74ceaf21"},
{file = "langsmith-0.0.64.tar.gz", hash = "sha256:e78c02501c2cff24fff7bd2d28ff3765b21675c7f0fcf6a09932bc218603c36e"},
]
[package.dependencies]
@@ -2142,6 +2099,65 @@ dev = ["black (>=21.6b0,<22.0)", "pytest (==6.*)", "pytest-asyncio", "pytest-moc
embeddings = ["matplotlib", "numpy", "openpyxl (>=3.0.7)", "pandas (>=1.2.3)", "pandas-stubs (>=1.1.0.11)", "plotly", "scikit-learn (>=1.0.2)", "scipy", "tenacity (>=8.0.1)"]
wandb = ["numpy", "openpyxl (>=3.0.7)", "pandas (>=1.2.3)", "pandas-stubs (>=1.1.0.11)", "wandb"]
[[package]]
name = "orjson"
version = "3.9.10"
description = "Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy"
optional = false
python-versions = ">=3.8"
files = [
{file = "orjson-3.9.10-cp310-cp310-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:c18a4da2f50050a03d1da5317388ef84a16013302a5281d6f64e4a3f406aabc4"},
{file = "orjson-3.9.10-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5148bab4d71f58948c7c39d12b14a9005b6ab35a0bdf317a8ade9a9e4d9d0bd5"},
{file = "orjson-3.9.10-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4cf7837c3b11a2dfb589f8530b3cff2bd0307ace4c301e8997e95c7468c1378e"},
{file = "orjson-3.9.10-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c62b6fa2961a1dcc51ebe88771be5319a93fd89bd247c9ddf732bc250507bc2b"},
{file = "orjson-3.9.10-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:deeb3922a7a804755bbe6b5be9b312e746137a03600f488290318936c1a2d4dc"},
{file = "orjson-3.9.10-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1234dc92d011d3554d929b6cf058ac4a24d188d97be5e04355f1b9223e98bbe9"},
{file = "orjson-3.9.10-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:06ad5543217e0e46fd7ab7ea45d506c76f878b87b1b4e369006bdb01acc05a83"},
{file = "orjson-3.9.10-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:4fd72fab7bddce46c6826994ce1e7de145ae1e9e106ebb8eb9ce1393ca01444d"},
{file = "orjson-3.9.10-cp310-none-win32.whl", hash = "sha256:b5b7d4a44cc0e6ff98da5d56cde794385bdd212a86563ac321ca64d7f80c80d1"},
{file = "orjson-3.9.10-cp310-none-win_amd64.whl", hash = "sha256:61804231099214e2f84998316f3238c4c2c4aaec302df12b21a64d72e2a135c7"},
{file = "orjson-3.9.10-cp311-cp311-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:cff7570d492bcf4b64cc862a6e2fb77edd5e5748ad715f487628f102815165e9"},
{file = "orjson-3.9.10-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ed8bc367f725dfc5cabeed1ae079d00369900231fbb5a5280cf0736c30e2adf7"},
{file = "orjson-3.9.10-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c812312847867b6335cfb264772f2a7e85b3b502d3a6b0586aa35e1858528ab1"},
{file = "orjson-3.9.10-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9edd2856611e5050004f4722922b7b1cd6268da34102667bd49d2a2b18bafb81"},
{file = "orjson-3.9.10-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:674eb520f02422546c40401f4efaf8207b5e29e420c17051cddf6c02783ff5ca"},
{file = "orjson-3.9.10-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1d0dc4310da8b5f6415949bd5ef937e60aeb0eb6b16f95041b5e43e6200821fb"},
{file = "orjson-3.9.10-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:e99c625b8c95d7741fe057585176b1b8783d46ed4b8932cf98ee145c4facf499"},
{file = "orjson-3.9.10-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:ec6f18f96b47299c11203edfbdc34e1b69085070d9a3d1f302810cc23ad36bf3"},
{file = "orjson-3.9.10-cp311-none-win32.whl", hash = "sha256:ce0a29c28dfb8eccd0f16219360530bc3cfdf6bf70ca384dacd36e6c650ef8e8"},
{file = "orjson-3.9.10-cp311-none-win_amd64.whl", hash = "sha256:cf80b550092cc480a0cbd0750e8189247ff45457e5a023305f7ef1bcec811616"},
{file = "orjson-3.9.10-cp312-cp312-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:602a8001bdf60e1a7d544be29c82560a7b49319a0b31d62586548835bbe2c862"},
{file = "orjson-3.9.10-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f295efcd47b6124b01255d1491f9e46f17ef40d3d7eabf7364099e463fb45f0f"},
{file = "orjson-3.9.10-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:92af0d00091e744587221e79f68d617b432425a7e59328ca4c496f774a356071"},
{file = "orjson-3.9.10-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c5a02360e73e7208a872bf65a7554c9f15df5fe063dc047f79738998b0506a14"},
{file = "orjson-3.9.10-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:858379cbb08d84fe7583231077d9a36a1a20eb72f8c9076a45df8b083724ad1d"},
{file = "orjson-3.9.10-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:666c6fdcaac1f13eb982b649e1c311c08d7097cbda24f32612dae43648d8db8d"},
{file = "orjson-3.9.10-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:3fb205ab52a2e30354640780ce4587157a9563a68c9beaf52153e1cea9aa0921"},
{file = "orjson-3.9.10-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:7ec960b1b942ee3c69323b8721df2a3ce28ff40e7ca47873ae35bfafeb4555ca"},
{file = "orjson-3.9.10-cp312-none-win_amd64.whl", hash = "sha256:3e892621434392199efb54e69edfff9f699f6cc36dd9553c5bf796058b14b20d"},
{file = "orjson-3.9.10-cp38-cp38-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:8b9ba0ccd5a7f4219e67fbbe25e6b4a46ceef783c42af7dbc1da548eb28b6531"},
{file = "orjson-3.9.10-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2e2ecd1d349e62e3960695214f40939bbfdcaeaaa62ccc638f8e651cf0970e5f"},
{file = "orjson-3.9.10-cp38-cp38-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7f433be3b3f4c66016d5a20e5b4444ef833a1f802ced13a2d852c637f69729c1"},
{file = "orjson-3.9.10-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4689270c35d4bb3102e103ac43c3f0b76b169760aff8bcf2d401a3e0e58cdb7f"},
{file = "orjson-3.9.10-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4bd176f528a8151a6efc5359b853ba3cc0e82d4cd1fab9c1300c5d957dc8f48c"},
{file = "orjson-3.9.10-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3a2ce5ea4f71681623f04e2b7dadede3c7435dfb5e5e2d1d0ec25b35530e277b"},
{file = "orjson-3.9.10-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:49f8ad582da6e8d2cf663c4ba5bf9f83cc052570a3a767487fec6af839b0e777"},
{file = "orjson-3.9.10-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:2a11b4b1a8415f105d989876a19b173f6cdc89ca13855ccc67c18efbd7cbd1f8"},
{file = "orjson-3.9.10-cp38-none-win32.whl", hash = "sha256:a353bf1f565ed27ba71a419b2cd3db9d6151da426b61b289b6ba1422a702e643"},
{file = "orjson-3.9.10-cp38-none-win_amd64.whl", hash = "sha256:e28a50b5be854e18d54f75ef1bb13e1abf4bc650ab9d635e4258c58e71eb6ad5"},
{file = "orjson-3.9.10-cp39-cp39-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:ee5926746232f627a3be1cc175b2cfad24d0170d520361f4ce3fa2fd83f09e1d"},
{file = "orjson-3.9.10-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a73160e823151f33cdc05fe2cea557c5ef12fdf276ce29bb4f1c571c8368a60"},
{file = "orjson-3.9.10-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c338ed69ad0b8f8f8920c13f529889fe0771abbb46550013e3c3d01e5174deef"},
{file = "orjson-3.9.10-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5869e8e130e99687d9e4be835116c4ebd83ca92e52e55810962446d841aba8de"},
{file = "orjson-3.9.10-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d2c1e559d96a7f94a4f581e2a32d6d610df5840881a8cba8f25e446f4d792df3"},
{file = "orjson-3.9.10-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:81a3a3a72c9811b56adf8bcc829b010163bb2fc308877e50e9910c9357e78521"},
{file = "orjson-3.9.10-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:7f8fb7f5ecf4f6355683ac6881fd64b5bb2b8a60e3ccde6ff799e48791d8f864"},
{file = "orjson-3.9.10-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:c943b35ecdf7123b2d81d225397efddf0bce2e81db2f3ae633ead38e85cd5ade"},
{file = "orjson-3.9.10-cp39-none-win32.whl", hash = "sha256:fb0b361d73f6b8eeceba47cd37070b5e6c9de5beaeaa63a1cb35c7e1a73ef088"},
{file = "orjson-3.9.10-cp39-none-win_amd64.whl", hash = "sha256:b90f340cb6397ec7a854157fac03f0c82b744abdd1c0941a024c3c29d1340aff"},
{file = "orjson-3.9.10.tar.gz", hash = "sha256:9ebbdbd6a046c304b1845e96fbcc5559cd296b4dfd3ad2509e33c4d9ce07d6a1"},
]
[[package]]
name = "overrides"
version = "7.4.0"
@@ -2190,17 +2206,6 @@ files = [
qa = ["flake8 (==3.8.3)", "mypy (==0.782)"]
testing = ["docopt", "pytest (<6.0.0)"]
[[package]]
name = "pathspec"
version = "0.11.2"
description = "Utility library for gitignore style pattern matching of file paths."
optional = false
python-versions = ">=3.7"
files = [
{file = "pathspec-0.11.2-py3-none-any.whl", hash = "sha256:1d6ed233af05e679efb96b1851550ea95bbb64b7c490b0f5aa52996c11e92a20"},
{file = "pathspec-0.11.2.tar.gz", hash = "sha256:e0d8d0ac2f12da61956eb2306b69f9469b42f4deb0f3cb6ed47b9cce9996ced3"},
]
[[package]]
name = "pexpect"
version = "4.8.0"
@@ -2438,13 +2443,13 @@ plugins = ["importlib-metadata"]
[[package]]
name = "pytest"
version = "7.4.2"
version = "7.4.3"
description = "pytest: simple powerful testing with Python"
optional = false
python-versions = ">=3.7"
files = [
{file = "pytest-7.4.2-py3-none-any.whl", hash = "sha256:1d881c6124e08ff0a1bb75ba3ec0bfd8b5354a01c194ddd5a0a870a48d99b002"},
{file = "pytest-7.4.2.tar.gz", hash = "sha256:a766259cfab564a2ad52cb1aae1b881a75c3eb7e34ca3779697c23ed47c47069"},
{file = "pytest-7.4.3-py3-none-any.whl", hash = "sha256:0d009c083ea859a71b76adf7c1d502e4bc170b80a8ef002da5806527b9591fac"},
{file = "pytest-7.4.3.tar.gz", hash = "sha256:d989d136982de4e3b29dabcc838ad581c64e8ed52c11fbe86ddebd9da0818cd5"},
]
[package.dependencies]
@@ -2496,13 +2501,13 @@ testing = ["fields", "hunter", "process-tests", "pytest-xdist", "six", "virtuale
[[package]]
name = "pytest-mock"
version = "3.11.1"
version = "3.12.0"
description = "Thin-wrapper around the mock package for easier use with pytest"
optional = false
python-versions = ">=3.7"
python-versions = ">=3.8"
files = [
{file = "pytest-mock-3.11.1.tar.gz", hash = "sha256:7f6b125602ac6d743e523ae0bfa71e1a697a2f5534064528c6ff84c2f7c2fc7f"},
{file = "pytest_mock-3.11.1-py3-none-any.whl", hash = "sha256:21c279fff83d70763b05f8874cc9cfb3fcacd6d354247a976f9529d19f9acf39"},
{file = "pytest-mock-3.12.0.tar.gz", hash = "sha256:31a40f038c22cad32287bb43932054451ff5583ff094bca6f675df2f8bc1a6e9"},
{file = "pytest_mock-3.12.0-py3-none-any.whl", hash = "sha256:0972719a7263072da3a21c7f4773069bcc7486027d7e8e1f81d98a47e701bc4f"},
]
[package.dependencies]
@@ -2525,6 +2530,20 @@ files = [
[package.dependencies]
pytest = ">=3.6.3"
[[package]]
name = "pytest-timeout"
version = "2.2.0"
description = "pytest plugin to abort hanging tests"
optional = false
python-versions = ">=3.7"
files = [
{file = "pytest-timeout-2.2.0.tar.gz", hash = "sha256:3b0b95dabf3cb50bac9ef5ca912fa0cfc286526af17afc806824df20c2f72c90"},
{file = "pytest_timeout-2.2.0-py3-none-any.whl", hash = "sha256:bde531e096466f49398a59f2dde76fa78429a09a12411466f88a07213e220de2"},
]
[package.dependencies]
pytest = ">=5.0.0"
[[package]]
name = "pytest-watch"
version = "4.2.0"
@@ -2936,28 +2955,28 @@ files = [
[[package]]
name = "ruff"
version = "0.0.255"
description = "An extremely fast Python linter, written in Rust."
version = "0.1.4"
description = "An extremely fast Python linter and code formatter, written in Rust."
optional = false
python-versions = ">=3.7"
files = [
{file = "ruff-0.0.255-py3-none-macosx_10_7_x86_64.whl", hash = "sha256:b2d71fb6a7e50501a2473864acffc85dee6b750c25db198f7e71fe1dbbff1aad"},
{file = "ruff-0.0.255-py3-none-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl", hash = "sha256:6c97d746861a6010f941179e84bba9feb8a871815667471d9ed6beb98d45c252"},
{file = "ruff-0.0.255-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9a7fa60085079b91a298b963361be9b1b1c724582af6c84be954cbabdbd9309a"},
{file = "ruff-0.0.255-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c089f7141496334ab5a127b54ce55e41f0d6714e68a4453a1e09d2204cdea8c3"},
{file = "ruff-0.0.255-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0423908caa7d437a416b853214565b9c33bbd1106c4f88147982216dddcbbd96"},
{file = "ruff-0.0.255-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:981493e92547cacbb8e0874904ec049fe744507ee890dc8736caf89a8864f9a7"},
{file = "ruff-0.0.255-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:59d5193d2aedb35db180824462b374dbcfc306b2e76076245088afa6e5837df2"},
{file = "ruff-0.0.255-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:dd5e00733c9d160c8a34a22e62b390da9d1e9f326676402421cb8c1236beefc3"},
{file = "ruff-0.0.255-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:694418cf41838bd19c6229e4e1b2d04505b1e6b86fe3ab81165484fc96d36f01"},
{file = "ruff-0.0.255-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:5d0408985c9777369daebb5d3340a99e9f7294bdd7120642239261508185cf89"},
{file = "ruff-0.0.255-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:abd6376ef9d12f370d95a8c7c98682fbb9bfedfba59f40e84a816fef8ddcb8de"},
{file = "ruff-0.0.255-py3-none-musllinux_1_2_i686.whl", hash = "sha256:f9b1a5df0bc09193cbef58a6f78e4a9a0b058a4f9733c0442866d078006d1bb9"},
{file = "ruff-0.0.255-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:6a25c5f4ff087445b2e1bbcb9963f2ae7c868d65e4a8d5f84c36c12f71571179"},
{file = "ruff-0.0.255-py3-none-win32.whl", hash = "sha256:1ff87a8310354f9f1a099625e54a27fdd6756d9cd2a40b45922f2e943daf982d"},
{file = "ruff-0.0.255-py3-none-win_amd64.whl", hash = "sha256:f3d8416be618f023f93ec4fd6ee3048585ef85dba9563b2a7e38fc7e5131d5b1"},
{file = "ruff-0.0.255-py3-none-win_arm64.whl", hash = "sha256:8ba124819624145d7b6b53add40c367c44318893215ffc1bfe3d72e0225a1c9c"},
{file = "ruff-0.0.255.tar.gz", hash = "sha256:f9eb1d3b2eecbeedae419fa494c4e2a5e4484baf93a1ce0f81eddb005e1919c5"},
{file = "ruff-0.1.4-py3-none-macosx_10_7_x86_64.whl", hash = "sha256:864958706b669cce31d629902175138ad8a069d99ca53514611521f532d91495"},
{file = "ruff-0.1.4-py3-none-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl", hash = "sha256:9fdd61883bb34317c788af87f4cd75dfee3a73f5ded714b77ba928e418d6e39e"},
{file = "ruff-0.1.4-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b4eaca8c9cc39aa7f0f0d7b8fe24ecb51232d1bb620fc4441a61161be4a17539"},
{file = "ruff-0.1.4-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a9a1301dc43cbf633fb603242bccd0aaa34834750a14a4c1817e2e5c8d60de17"},
{file = "ruff-0.1.4-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:78e8db8ab6f100f02e28b3d713270c857d370b8d61871d5c7d1702ae411df683"},
{file = "ruff-0.1.4-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:80fea754eaae06335784b8ea053d6eb8e9aac75359ebddd6fee0858e87c8d510"},
{file = "ruff-0.1.4-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6bc02a480d4bfffd163a723698da15d1a9aec2fced4c06f2a753f87f4ce6969c"},
{file = "ruff-0.1.4-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9862811b403063765b03e716dac0fda8fdbe78b675cd947ed5873506448acea4"},
{file = "ruff-0.1.4-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:58826efb8b3efbb59bb306f4b19640b7e366967a31c049d49311d9eb3a4c60cb"},
{file = "ruff-0.1.4-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:fdfd453fc91d9d86d6aaa33b1bafa69d114cf7421057868f0b79104079d3e66e"},
{file = "ruff-0.1.4-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:e8791482d508bd0b36c76481ad3117987301b86072158bdb69d796503e1c84a8"},
{file = "ruff-0.1.4-py3-none-musllinux_1_2_i686.whl", hash = "sha256:01206e361021426e3c1b7fba06ddcb20dbc5037d64f6841e5f2b21084dc51800"},
{file = "ruff-0.1.4-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:645591a613a42cb7e5c2b667cbefd3877b21e0252b59272ba7212c3d35a5819f"},
{file = "ruff-0.1.4-py3-none-win32.whl", hash = "sha256:99908ca2b3b85bffe7e1414275d004917d1e0dfc99d497ccd2ecd19ad115fd0d"},
{file = "ruff-0.1.4-py3-none-win_amd64.whl", hash = "sha256:1dfd6bf8f6ad0a4ac99333f437e0ec168989adc5d837ecd38ddb2cc4a2e3db8a"},
{file = "ruff-0.1.4-py3-none-win_arm64.whl", hash = "sha256:d98ae9ebf56444e18a3e3652b3383204748f73e247dea6caaf8b52d37e6b32da"},
{file = "ruff-0.1.4.tar.gz", hash = "sha256:21520ecca4cc555162068d87c747b8f95e1e95f8ecfcbbe59e8dd00710586315"},
]
[[package]]
@@ -3016,54 +3035,6 @@ description = "Database Abstraction Library"
optional = false
python-versions = ">=3.7"
files = [
{file = "SQLAlchemy-2.0.22-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:f146c61ae128ab43ea3a0955de1af7e1633942c2b2b4985ac51cc292daf33222"},
{file = "SQLAlchemy-2.0.22-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:875de9414393e778b655a3d97d60465eb3fae7c919e88b70cc10b40b9f56042d"},
{file = "SQLAlchemy-2.0.22-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:13790cb42f917c45c9c850b39b9941539ca8ee7917dacf099cc0b569f3d40da7"},
{file = "SQLAlchemy-2.0.22-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e04ab55cf49daf1aeb8c622c54d23fa4bec91cb051a43cc24351ba97e1dd09f5"},
{file = "SQLAlchemy-2.0.22-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:a42c9fa3abcda0dcfad053e49c4f752eef71ecd8c155221e18b99d4224621176"},
{file = "SQLAlchemy-2.0.22-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:14cd3bcbb853379fef2cd01e7c64a5d6f1d005406d877ed9509afb7a05ff40a5"},
{file = "SQLAlchemy-2.0.22-cp310-cp310-win32.whl", hash = "sha256:d143c5a9dada696bcfdb96ba2de4a47d5a89168e71d05a076e88a01386872f97"},
{file = "SQLAlchemy-2.0.22-cp310-cp310-win_amd64.whl", hash = "sha256:ccd87c25e4c8559e1b918d46b4fa90b37f459c9b4566f1dfbce0eb8122571547"},
{file = "SQLAlchemy-2.0.22-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4f6ff392b27a743c1ad346d215655503cec64405d3b694228b3454878bf21590"},
{file = "SQLAlchemy-2.0.22-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f776c2c30f0e5f4db45c3ee11a5f2a8d9de68e81eb73ec4237de1e32e04ae81c"},
{file = "SQLAlchemy-2.0.22-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c8f1792d20d2f4e875ce7a113f43c3561ad12b34ff796b84002a256f37ce9437"},
{file = "SQLAlchemy-2.0.22-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d80eeb5189d7d4b1af519fc3f148fe7521b9dfce8f4d6a0820e8f5769b005051"},
{file = "SQLAlchemy-2.0.22-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:69fd9e41cf9368afa034e1c81f3570afb96f30fcd2eb1ef29cb4d9371c6eece2"},
{file = "SQLAlchemy-2.0.22-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:54bcceaf4eebef07dadfde424f5c26b491e4a64e61761dea9459103ecd6ccc95"},
{file = "SQLAlchemy-2.0.22-cp311-cp311-win32.whl", hash = "sha256:7ee7ccf47aa503033b6afd57efbac6b9e05180f492aeed9fcf70752556f95624"},
{file = "SQLAlchemy-2.0.22-cp311-cp311-win_amd64.whl", hash = "sha256:b560f075c151900587ade06706b0c51d04b3277c111151997ea0813455378ae0"},
{file = "SQLAlchemy-2.0.22-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:2c9bac865ee06d27a1533471405ad240a6f5d83195eca481f9fc4a71d8b87df8"},
{file = "SQLAlchemy-2.0.22-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:625b72d77ac8ac23da3b1622e2da88c4aedaee14df47c8432bf8f6495e655de2"},
{file = "SQLAlchemy-2.0.22-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b39a6e21110204a8c08d40ff56a73ba542ec60bab701c36ce721e7990df49fb9"},
{file = "SQLAlchemy-2.0.22-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:53a766cb0b468223cafdf63e2d37f14a4757476157927b09300c8c5832d88560"},
{file = "SQLAlchemy-2.0.22-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:0e1ce8ebd2e040357dde01a3fb7d30d9b5736b3e54a94002641dfd0aa12ae6ce"},
{file = "SQLAlchemy-2.0.22-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:505f503763a767556fa4deae5194b2be056b64ecca72ac65224381a0acab7ebe"},
{file = "SQLAlchemy-2.0.22-cp312-cp312-win32.whl", hash = "sha256:154a32f3c7b00de3d090bc60ec8006a78149e221f1182e3edcf0376016be9396"},
{file = "SQLAlchemy-2.0.22-cp312-cp312-win_amd64.whl", hash = "sha256:129415f89744b05741c6f0b04a84525f37fbabe5dc3774f7edf100e7458c48cd"},
{file = "SQLAlchemy-2.0.22-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:3940677d341f2b685a999bffe7078697b5848a40b5f6952794ffcf3af150c301"},
{file = "SQLAlchemy-2.0.22-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:55914d45a631b81a8a2cb1a54f03eea265cf1783241ac55396ec6d735be14883"},
{file = "SQLAlchemy-2.0.22-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2096d6b018d242a2bcc9e451618166f860bb0304f590d205173d317b69986c95"},
{file = "SQLAlchemy-2.0.22-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:19c6986cf2fb4bc8e0e846f97f4135a8e753b57d2aaaa87c50f9acbe606bd1db"},
{file = "SQLAlchemy-2.0.22-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:6ac28bd6888fe3c81fbe97584eb0b96804bd7032d6100b9701255d9441373ec1"},
{file = "SQLAlchemy-2.0.22-cp37-cp37m-win32.whl", hash = "sha256:cb9a758ad973e795267da334a92dd82bb7555cb36a0960dcabcf724d26299db8"},
{file = "SQLAlchemy-2.0.22-cp37-cp37m-win_amd64.whl", hash = "sha256:40b1206a0d923e73aa54f0a6bd61419a96b914f1cd19900b6c8226899d9742ad"},
{file = "SQLAlchemy-2.0.22-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:3aa1472bf44f61dd27987cd051f1c893b7d3b17238bff8c23fceaef4f1133868"},
{file = "SQLAlchemy-2.0.22-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:56a7e2bb639df9263bf6418231bc2a92a773f57886d371ddb7a869a24919face"},
{file = "SQLAlchemy-2.0.22-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ccca778c0737a773a1ad86b68bda52a71ad5950b25e120b6eb1330f0df54c3d0"},
{file = "SQLAlchemy-2.0.22-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7c6c3e9350f9fb16de5b5e5fbf17b578811a52d71bb784cc5ff71acb7de2a7f9"},
{file = "SQLAlchemy-2.0.22-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:564e9f9e4e6466273dbfab0e0a2e5fe819eec480c57b53a2cdee8e4fdae3ad5f"},
{file = "SQLAlchemy-2.0.22-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:af66001d7b76a3fab0d5e4c1ec9339ac45748bc4a399cbc2baa48c1980d3c1f4"},
{file = "SQLAlchemy-2.0.22-cp38-cp38-win32.whl", hash = "sha256:9e55dff5ec115316dd7a083cdc1a52de63693695aecf72bc53a8e1468ce429e5"},
{file = "SQLAlchemy-2.0.22-cp38-cp38-win_amd64.whl", hash = "sha256:4e869a8ff7ee7a833b74868a0887e8462445ec462432d8cbeff5e85f475186da"},
{file = "SQLAlchemy-2.0.22-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:9886a72c8e6371280cb247c5d32c9c8fa141dc560124348762db8a8b236f8692"},
{file = "SQLAlchemy-2.0.22-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:a571bc8ac092a3175a1d994794a8e7a1f2f651e7c744de24a19b4f740fe95034"},
{file = "SQLAlchemy-2.0.22-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8db5ba8b7da759b727faebc4289a9e6a51edadc7fc32207a30f7c6203a181592"},
{file = "SQLAlchemy-2.0.22-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0b0b3f2686c3f162123adba3cb8b626ed7e9b8433ab528e36ed270b4f70d1cdb"},
{file = "SQLAlchemy-2.0.22-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:0c1fea8c0abcb070ffe15311853abfda4e55bf7dc1d4889497b3403629f3bf00"},
{file = "SQLAlchemy-2.0.22-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:4bb062784f37b2d75fd9b074c8ec360ad5df71f933f927e9e95c50eb8e05323c"},
{file = "SQLAlchemy-2.0.22-cp39-cp39-win32.whl", hash = "sha256:58a3aba1bfb32ae7af68da3f277ed91d9f57620cf7ce651db96636790a78b736"},
{file = "SQLAlchemy-2.0.22-cp39-cp39-win_amd64.whl", hash = "sha256:92e512a6af769e4725fa5b25981ba790335d42c5977e94ded07db7d641490a85"},
{file = "SQLAlchemy-2.0.22-py3-none-any.whl", hash = "sha256:3076740335e4aaadd7deb3fe6dcb96b3015f1613bd190a4e1634e1b99b02ec86"},
{file = "SQLAlchemy-2.0.22.tar.gz", hash = "sha256:5434cc601aa17570d79e5377f5fd45ff92f9379e2abed0be5e8c2fba8d353d2b"},
]
@@ -3073,7 +3044,7 @@ typing-extensions = ">=4.2.0"
[package.extras]
aiomysql = ["aiomysql (>=0.2.0)", "greenlet (!=0.4.17)"]
aiosqlite = ["aiosqlite", "greenlet (!=0.4.17)", "typing-extensions (!=3.10.0.1)"]
aiosqlite = ["aiosqlite", "greenlet (!=0.4.17)", "typing_extensions (!=3.10.0.1)"]
asyncio = ["greenlet (!=0.4.17)"]
asyncmy = ["asyncmy (>=0.2.3,!=0.2.4,!=0.2.6)", "greenlet (!=0.4.17)"]
mariadb-connector = ["mariadb (>=1.0.1,!=1.1.2,!=1.1.5)"]
@@ -3083,7 +3054,7 @@ mssql-pyodbc = ["pyodbc"]
mypy = ["mypy (>=0.910)"]
mysql = ["mysqlclient (>=1.4.0)"]
mysql-connector = ["mysql-connector-python"]
oracle = ["cx-oracle (>=7)"]
oracle = ["cx_oracle (>=7)"]
oracle-oracledb = ["oracledb (>=1.0.1)"]
postgresql = ["psycopg2 (>=2.7)"]
postgresql-asyncpg = ["asyncpg", "greenlet (!=0.4.17)"]
@@ -3093,7 +3064,7 @@ postgresql-psycopg2binary = ["psycopg2-binary"]
postgresql-psycopg2cffi = ["psycopg2cffi"]
postgresql-psycopgbinary = ["psycopg[binary] (>=3.0.7)"]
pymysql = ["pymysql"]
sqlcipher = ["sqlcipher3-binary"]
sqlcipher = ["sqlcipher3_binary"]
[[package]]
name = "sse-starlette"
@@ -3198,17 +3169,6 @@ webencodings = ">=0.4"
doc = ["sphinx", "sphinx_rtd_theme"]
test = ["flake8", "isort", "pytest"]
[[package]]
name = "tokenize-rt"
version = "5.2.0"
description = "A wrapper around the stdlib `tokenize` which roundtrips."
optional = false
python-versions = ">=3.8"
files = [
{file = "tokenize_rt-5.2.0-py2.py3-none-any.whl", hash = "sha256:b79d41a65cfec71285433511b50271b05da3584a1da144a0752e9c621a285289"},
{file = "tokenize_rt-5.2.0.tar.gz", hash = "sha256:9fe80f8a5c1edad2d3ede0f37481cc0cc1538a2f442c9c2f9e4feacd2792d054"},
]
[[package]]
name = "tomli"
version = "2.0.1"
@@ -3328,13 +3288,13 @@ dev = ["flake8", "flake8-annotations", "flake8-bandit", "flake8-bugbear", "flake
[[package]]
name = "urllib3"
version = "2.0.6"
version = "2.0.7"
description = "HTTP library with thread-safe connection pooling, file post, and more."
optional = false
python-versions = ">=3.7"
files = [
{file = "urllib3-2.0.6-py3-none-any.whl", hash = "sha256:7a7c7003b000adf9e7ca2a377c9688bbc54ed41b985789ed576570342a375cd2"},
{file = "urllib3-2.0.6.tar.gz", hash = "sha256:b19e1a85d206b56d7df1d5e683df4a7725252a964e3993648dd0fb5a1c157564"},
{file = "urllib3-2.0.7-py3-none-any.whl", hash = "sha256:fdb6d215c776278489906c2f8916e6e7d4f5a9b602ccbcfdf7f016fc8da0596e"},
{file = "urllib3-2.0.7.tar.gz", hash = "sha256:c97dfde1f7bd43a71c8d2a58e369e9b2bf692d1334ea9f9cae55add7d0dd0f84"},
]
[package.extras]
@@ -3888,4 +3848,4 @@ server = ["fastapi", "sse-starlette"]
[metadata]
lock-version = "2.0"
python-versions = "^3.8.1"
content-hash = "a02e9f4afeff9a7fd8cf972fd48e80fb576941aa35af43c653c7b0de1a88c691"
content-hash = "92a78ecee32d12b6ed8d4b2556631701a1b26d4d4e9b0e0dbbfd8f3577a6204a"
+19 -6
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "langserve"
version = "0.0.13"
version = "0.0.30"
description = ""
readme = "README.md"
authors = ["LangChain"]
@@ -12,11 +12,12 @@ include = ["langserve/playground/dist/**/*"]
[tool.poetry.dependencies]
python = "^3.8.1"
httpx = ">=0.23.0" # May be able to decrease this version
fastapi = {version = ">=0.90.1", optional = true}
fastapi = {version = ">=0.90.1,<1", optional = true}
sse-starlette = {version = "^1.3.0", optional = true}
httpx-sse = {version = ">=0.3.1", optional = true}
pydantic = "^1"
langchain = ">=0.0.316"
pydantic = ">=1"
langchain = ">=0.0.333"
orjson = ">=2"
[tool.poetry.group.dev.dependencies]
jupyterlab = "^3.6.1"
@@ -27,8 +28,7 @@ httpx-sse = ">=0.3.1"
[tool.poetry.group.typing.dependencies]
[tool.poetry.group.lint.dependencies]
black = { version="^23.1.0", extras=["jupyter"] }
ruff = "^0.0.255"
ruff = "^0.1.4"
codespell = "^2.2.0"
[tool.poetry.group.test.dependencies]
@@ -38,6 +38,7 @@ pytest-asyncio = "^0.21.1"
pytest-mock = "^3.11.1"
pytest-socket = "^0.6.0"
pytest-watch = "^4.2.0"
pytest-timeout = "^2.2.0"
[tool.poetry.group.examples.dependencies]
openai = "^0.28.0"
@@ -84,3 +85,15 @@ omit = [
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
[tool.pytest.ini_options]
# --strict-markers will raise errors on unknown marks.
# https://docs.pytest.org/en/7.1.x/how-to/mark.html#raising-errors-on-unknown-marks
#
# https://docs.pytest.org/en/7.1.x/reference/reference.html
# --strict-config any warnings encountered while parsing the `pytest`
# section of the configuration file raise errors.
addopts = "--strict-markers --strict-config --durations=5 -vv"
# Global timeout for all tests. There shuold be a good reason for a test to
# take more than 5 second
timeout = 5
asyncio_mode = "auto"
+59
View File
@@ -0,0 +1,59 @@
import uuid
from langserve.callbacks import AsyncEventAggregatorCallback, replace_uuids
async def test_event_aggregator() -> None:
"""Test that the event aggregator is aggregating events."""
from langchain.llms import FakeListLLM
from langchain.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_template("{question}")
llm = FakeListLLM(responses=["hello", "world"])
chain = prompt | llm
callback = AsyncEventAggregatorCallback()
assert callback.callback_events == []
assert chain.invoke({"question": "hello"}, {"callbacks": [callback]}) == "hello"
callback_events = callback.callback_events
assert isinstance(callback_events, list)
assert len(callback_events) == 6
assert [event["type"] for event in callback_events] == [
"on_chain_start",
"on_chain_start",
"on_chain_end",
"on_llm_start",
"on_llm_end",
"on_chain_end",
]
def test_replace_uuids() -> None:
"""Test replace uuids in place."""
uuid1 = uuid.UUID(int=1)
uuid2 = uuid.UUID(int=2)
events = [
{
"type": "on_llm_start",
"run_id": uuid1,
"parent_run_id": None,
},
{
"type": "on_llm_start",
"run_id": uuid1,
"parent_run_id": uuid2,
},
]
new_events = replace_uuids(events)
# Assert original event is unchanged
assert events[0]["run_id"] == uuid1
assert isinstance(new_events, list)
assert len(new_events) == 2
assert new_events[0]["run_id"] != uuid1
assert new_events[1]["run_id"] != uuid2
assert new_events[0]["run_id"] == new_events[1]["run_id"]
assert new_events[0]["run_id"] != new_events[1]["parent_run_id"]
assert new_events[0]["parent_run_id"] is None
+112 -4
View File
@@ -1,3 +1,6 @@
import datetime
import uuid
from enum import Enum
from typing import Any
import pytest
@@ -6,13 +9,14 @@ from langchain.schema.messages import (
HumanMessageChunk,
SystemMessage,
)
from langchain.schema.output import ChatGeneration
try:
from pydantic.v1 import BaseModel
except ImportError:
from pydantic import BaseModel
from langserve.serialization import simple_dumps, simple_loads
from langserve.serialization import WellKnownLCSerializer, load_events
@pytest.mark.parametrize(
@@ -39,17 +43,22 @@ from langserve.serialization import simple_dumps, simple_loads
"numbers": [1, 2, 3],
"boom": "Hello, world!",
},
[ChatGeneration(message=HumanMessage(content="Hello"))],
],
)
def test_serialization(data: Any) -> None:
"""There and back again! :)"""
# Test encoding
assert isinstance(simple_dumps(data), str)
lc_serializer = WellKnownLCSerializer()
assert isinstance(lc_serializer.dumps(data), bytes)
# Translate to python primitives and load back into object
assert lc_serializer.loadd(lc_serializer.dumpd(data)) == data
# Test simple equality (does not include pydantic class names)
assert simple_loads(simple_dumps(data)) == data
assert lc_serializer.loads(lc_serializer.dumps(data)) == data
# Test full representation equality (includes pydantic class names)
assert _get_full_representation(
simple_loads(simple_dumps(data))
lc_serializer.loads(lc_serializer.dumps(data))
) == _get_full_representation(data)
@@ -75,3 +84,102 @@ def _get_full_representation(data: Any) -> Any:
return data.schema()
else:
return data
@pytest.mark.parametrize(
"data,expected",
[
([], []),
(
[
{
"type": "on_llm_start",
"serialized": {},
"prompts": [],
"run_id": str(uuid.UUID(int=2)),
"parent_run_id": str(uuid.UUID(int=1)),
"tags": ["h"],
"metadata": {},
"kwargs": {},
}
],
[
{
"type": "on_llm_start",
"serialized": {},
"prompts": [],
"run_id": uuid.UUID(int=2),
"parent_run_id": uuid.UUID(int=1),
"tags": ["h"],
"metadata": {},
"kwargs": {},
}
],
),
],
)
def test_decode_events(data: Any, expected: Any) -> None:
"""Test decoding events."""
assert load_events(data) == expected
class SimpleEnum(Enum):
a = "a"
b = "b"
class SimpleModel(BaseModel):
x: int
y: SimpleEnum
z: uuid.UUID
dt: datetime.datetime
d: datetime.date
t: datetime.time
@pytest.mark.parametrize(
"obj, expected",
[
({"key": "value"}, {"key": "value"}),
([1, 2, 3], [1, 2, 3]),
(123, 123),
(uuid.UUID(int=1), "00000000-0000-0000-0000-000000000001"),
(datetime.datetime(2020, 1, 1), "2020-01-01T00:00:00"),
(datetime.date(2020, 1, 1), "2020-01-01"),
(datetime.time(0, 0, 0), "00:00:00"),
(datetime.time(0, 0, 0, 1), "00:00:00.000001"),
(SimpleEnum.a, "a"),
(
SimpleModel(
x=1,
y=SimpleEnum.a,
z=uuid.UUID(int=1),
dt=datetime.datetime(2020, 1, 1),
d=datetime.date(2020, 1, 1),
t=datetime.time(0, 0, 0),
),
{
"x": 1,
"y": "a",
"z": "00000000-0000-0000-0000-000000000001",
"dt": "2020-01-01T00:00:00",
"d": "2020-01-01",
"t": "00:00:00",
},
),
("string", "string"),
(True, True),
(None, None),
],
)
def test_encoding_of_well_known_types(obj: Any, expected: str) -> None:
"""Test encoding of well known types.
This tests verifies that our custom serializer is able to encode some well
known types; e.g., uuid, datetime, date, time
It doesn't handle types like Decimal or frozenset etc just yet while we determine
how to roll out a more complete solution.
"""
lc_serializer = WellKnownLCSerializer()
assert lc_serializer.dumpd(obj) == expected
File diff suppressed because it is too large Load Diff
+14 -4
View File
@@ -1,10 +1,12 @@
from typing import List, Optional
from unittest.mock import MagicMock
import pytest
from fastapi import Request
from langchain.prompts import PromptTemplate
from langchain.schema.runnable.utils import ConfigurableField
from langserve.server import _unpack_config
from langserve.server import _unpack_request_config
try:
from pydantic.v1 import BaseModel, ValidationError
@@ -151,12 +153,14 @@ def test_invoke_request_with_runnables() -> None:
Model = create_invoke_request_model("", runnable.input_schema, config)
assert (
_unpack_config(
_unpack_request_config(
Model(
input={"name": "bob"},
).config,
keys=[],
config_keys=[],
model=config,
request=MagicMock(Request),
per_req_config_modifier=lambda x, y: x,
)
== {}
)
@@ -178,6 +182,12 @@ def test_invoke_request_with_runnables() -> None:
"template": "goodbye {name}",
}
assert _unpack_config(request.config, keys=["configurable"], model=config) == {
assert _unpack_request_config(
request.config,
config_keys=["configurable"],
model=config,
request=MagicMock(Request),
per_req_config_modifier=lambda x, y: x,
) == {
"configurable": {"template": "goodbye {name}"},
}
+43 -1
View File
@@ -1,10 +1,13 @@
from typing import Any, List, Mapping, Optional
from typing import Any, Dict, List, Mapping, Optional
from uuid import UUID
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.callbacks.tracers.base import BaseTracer
from langchain.llms.base import LLM
from langsmith.schemas import Run
class FakeListLLM(LLM):
@@ -52,3 +55,42 @@ class FakeListLLM(LLM):
@property
def _identifying_params(self) -> Mapping[str, Any]:
return {"responses": self.responses}
class FakeTracer(BaseTracer):
"""Fake tracer that records LangChain execution.
It replaces run ids with deterministic UUIDs."""
def __init__(self) -> None:
"""Initialize the tracer."""
super().__init__()
self.runs: List[Run] = []
self.uuids_map: Dict[UUID, UUID] = {}
self.uuids_generator = (
UUID(f"00000000-0000-4000-8000-{i:012}", version=4) for i in range(10_000)
)
def _replace_uuid(self, uuid: UUID) -> UUID:
"""Replace a UUID with a deterministic one."""
if uuid not in self.uuids_map:
self.uuids_map[uuid] = next(self.uuids_generator)
return self.uuids_map[uuid]
def _copy_run(self, run: Run) -> Run:
"""Copy a run, replacing UUIDs."""
return run.copy(
update={
"id": self._replace_uuid(run.id),
"parent_run_id": self.uuids_map[run.parent_run_id]
if run.parent_run_id
else None,
"child_runs": [self._copy_run(child) for child in run.child_runs],
"execution_order": None,
"child_execution_order": None,
}
)
def _persist_run(self, run: Run) -> None:
"""Persist a run."""
self.runs.append(self._copy_run(run))