Compare commits

...

756 Commits

Author SHA1 Message Date
vowelparrot
92b10d98e0 Add Patch to stream runs 2023-05-14 19:42:30 -07:00
Zander Chase
d85b04be7f Add RELLM and JSONFormer experimental LLM decoding (#4185)
[RELLM](https://github.com/r2d4/rellm) is a library that wraps local
HuggingFace pipeline models for structured decoding.

RELLM works by generating tokens one at a time. At each step, it masks
tokens that don't conform to the provided partial regular expression.

[JSONFormer](https://github.com/1rgs/jsonformer) is a bit different, where it sequentially adds the keys then decodes each value directly
2023-05-14 22:40:03 +00:00
Harrison Chase
54f5523197 bump version to 169 (#4675) 2023-05-14 14:18:29 -07:00
Harrison Chase
243886be93 Harrison/virtual time (#4658)
Co-authored-by: ifsheldon <39153080+ifsheldon@users.noreply.github.com>
Co-authored-by: maple.liang <maple.liang@gempoll.com>
2023-05-14 10:29:17 -07:00
Harrison Chase
f2f2aced6d allow partials in from_template (#4638) 2023-05-13 21:47:20 -07:00
Harrison Chase
fbfa49f2c1 agent serialization (#4642) 2023-05-13 21:47:10 -07:00
Harrison Chase
ef49c659f6 add embedding router (#4644) 2023-05-13 21:47:01 -07:00
Harrison Chase
5020094e3b Harrison/azure content filter (#4645)
Co-authored-by: Rob Kopel <R0bk@users.noreply.github.com>
2023-05-13 21:46:51 -07:00
Harrison Chase
f5e2f70115 Harrison/json new line (#4646)
Co-authored-by: David Chen <davidchen@gliacloud.com>
2023-05-13 21:46:33 -07:00
Harrison Chase
87d8d221fb Harrison/headers for openai (#4648)
Co-authored-by: aakash.shah <aakash.shah@quintiles.com>
2023-05-13 21:46:20 -07:00
Harrison Chase
c09bb00959 Harrison/summary memory history (#4649)
Co-authored-by: engkheng <60956360+outday29@users.noreply.github.com>
2023-05-13 21:46:11 -07:00
Harrison Chase
44ae673388 Harrison/multithreading directory loader (#4650)
Co-authored-by: PawelFaron <42373772+PawelFaron@users.noreply.github.com>
Co-authored-by: Pawel Faron <ext-pawel.faron@vaisala.com>
2023-05-13 21:46:02 -07:00
Harrison Chase
b0c733e327 list of messages (#4651) 2023-05-13 21:45:53 -07:00
Harrison Chase
873b0c7eb6 Harrison/structured chat mem (#4652)
Co-authored-by: d 3 n 7 <29033313+d3n7@users.noreply.github.com>
2023-05-13 21:45:42 -07:00
Harrison Chase
9ba3a798c4 Harrison/from keys redis (#4653)
Co-authored-by: Christoph Kahl <christoph@zauberware.com>
2023-05-13 21:45:24 -07:00
Harrison Chase
e781ff9256 Harrison/chatopenaibase path (#4656)
Co-authored-by: Dave <dave@gray101.com>
2023-05-13 21:45:14 -07:00
Harrison Chase
279605b4d3 Harrison/metaphor search (#4657)
Co-authored-by: Jeffrey Wang <jeffreyzhiyuanwang@gmail.com>
2023-05-13 21:45:05 -07:00
Harrison Chase
9aa9fe7021 Harrison/spark connect example (#4659)
Co-authored-by: Mike Wang <62768671+skcoirz@users.noreply.github.com>
2023-05-13 21:44:54 -07:00
Prerit Das
2747ccbcf1 Allow custom base Zapier prompt (#4213)
Currently, all Zapier tools are built using the pre-written base Zapier
prompt. These small changes (that retain default behavior) will allow a
user to create a Zapier tool using the ZapierNLARunTool while providing
their own base prompt.

Their prompt must contain input fields for zapier_description and
params, checked and enforced in the tool's root validator.

An example of when this may be useful: user has several, say 10, Zapier
tools enabled. Currently, the long generic default Zapier base prompt is
attached to every single tool, using an extreme number of tokens for no
real added benefit (repeated). User prompts LLM on how to use Zapier
tools once, then overrides the base prompt.

Or: user has a few specific Zapier tools and wants to maximize their
success rate. So, user writes prompts/descriptions for those tools
specific to their use case, and provides those to the ZapierNLARunTool.

A consideration - this is the simplest way to implement this I could
think of... though ideally custom prompting would be possible at the
Toolkit level as well. For now, this should be sufficient in solving the
concerns outlined above.
2023-05-13 21:08:18 -07:00
Paresh Mathur
e2bc836571 Fix #4087 by setting the correct csv dialect (#4103)
The error in #4087 was happening because of the use of csv.Dialect.*
which is just an empty base class. we need to make a choice on what is
our base dialect. I usually use excel so I put it as excel, if
maintainers have other preferences do let me know.

Open Questions:
1. What should be the default dialect?
2. Should we rework all tests to mock the open function rather than the
csv.DictReader?
3. Should we make a separate input for `dialect` like we have for
`encoding`?

---------

Co-authored-by: = <=>
2023-05-13 20:35:01 -07:00
Leonid Ganeline
3ce78ef6c4 docs: document_loaders classification (#4069)
**Problem statement:** the
[document_loaders](https://python.langchain.com/en/latest/modules/indexes/document_loaders.html#)
section is too long and hard to comprehend.
**Proposal:** group document_loaders by 3 classes: (see `Files changed`
tab)

UPDATE: I've completely reworked the document_loader classification.
Now this PR changes only one file! 

FYI @eyurtsev @hwchase17
2023-05-13 19:17:32 -07:00
Zander Chase
928cdd57a4 [Breaking] Refactor Base Tracer(#4549)
### Refactor the BaseTracer
- Remove the 'session' abstraction from the BaseTracer
- Rename 'RunV2' object(s) to be called 'Run' objects (Rename previous
Run objects to be RunV1 objects)
- Ditto for sessions: TracerSession*V2 -> TracerSession*
- Remove now deprecated conversion from v1 run objects to v2 run objects
in LangChainTracerV2
- Add conversion from v2 run objects to v1 run objects in V1 tracer
2023-05-13 17:23:56 +00:00
Harrison Chase
1e322ffc1c change heading 2023-05-13 09:52:23 -07:00
Harrison Chase
86c1f090fd bump version to 168 (#4632) 2023-05-13 09:50:22 -07:00
Davis Chase
9ab7101182 WIP: FLARE-inspired chain (#4612)
Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-05-13 09:28:28 -07:00
Harrison Chase
daa3e6dedb Harrison/prompt constructor methods (#4616) 2023-05-13 09:23:51 -07:00
Harrison Chase
6265cbfb11 Harrison/standard llm interface (#4615) 2023-05-13 09:05:31 -07:00
Harrison Chase
485ecc3580 option for csv agent to not include df in prompt (#4610) 2023-05-12 21:55:22 -07:00
Harrison Chase
7d425cbf38 improve sql prompt (#4611)
Co-authored-by: Taqi Jaffri <tjaffri@docugami.com>
Co-authored-by: Taqi Jaffri <tjaffri@gmail.com>
2023-05-12 21:55:03 -07:00
Hans van Dam
01531cb16d remove quotes from sql database prompts (caused syntax error) (#4101)
fixes a syntax error mentioned in
#2027 and #3305
another PR to remedy is in #3385, but I believe that is not tacking the
core problem.
Also #2027 mentions a solution that works:
add to the prompt:
'The SQL query should be outputted plainly, do not surround it in quotes
or anything else.'

To me it seems strange to first ask for:

SQLQuery: "SQL Query to run"

and then to tell the LLM not to put the quotes around it. Other
templates (than the sql one) do not use quotes in their steps.
This PR changes that to:

SQLQuery: SQL Query to run
2023-05-12 20:03:37 -07:00
Zander Chase
0c6ed657ef Convert Chain to a Chain Factory (#4605)
## Change Chain argument in client to accept a chain factory

The `run_over_dataset` functionality seeks to treat each iteration of an
example as an independent trial.
Chains have memory, so it's easier to permit this type of behavior if we
accept a factory method rather than the chain object directly.

There's still corner cases / UX pains people will likely run into, like:
- Caching may cause issues
- if memory is persisted to a shared object (e.g., same redis queue) ,
this could impact what is retrieved
- If we're running the async methods with concurrency using local
models, if someone naively instantiates the chain and loads each time,
it could lead to tons of disk I/O or OOM
2023-05-13 02:13:21 +00:00
Tim Asp
ed0d557ede docs: fix pdf docs hierarchy and formatting (#4593)
# Fix pdf loader docs page


![image](https://github.com/hwchase17/langchain/assets/707699/4a11f379-00ed-4f7a-9870-71f74e0cadc6)

Using h1's messes with hierarchy, this fixes that, and moves the
PyPDFium2 loader out of the middle of PDFMiner docs
2023-05-12 15:03:01 -04:00
Davis Chase
36f9e9a0ba Skip flaky unit test (#4591) 2023-05-12 11:54:40 -07:00
Eugene Yurtsev
08ed927c32 Turn on extended tests (#4588)
# Turn on strict extended tests

This PR turns on strict testing for extended tests.
2023-05-12 14:50:08 -04:00
Zander Chase
d96f6a106b Add Steamship Image Generation Tool (#4580)
Co-authored-by: Enias Cailliau <enias@steamship.com>
2023-05-12 10:35:01 -07:00
Davis Chase
739c297c94 Release 167 (#4589) 2023-05-12 10:24:59 -07:00
Davis Chase
a4a9d1f403 Improve vespa interface (#4546)
![Screenshot 2023-05-11 at 7 50 31
PM](https://github.com/hwchase17/langchain/assets/130488702/bc8ab4bb-8006-44fc-ba07-df54e84ee2c1)
2023-05-12 10:11:26 -07:00
vinoyang
72f18fd08b Provide get current date function dialect for other DBs (#4576)
# Provide get current date function dialect for other DBs

<!--
Thank you for contributing to LangChain! Your PR will appear in our next
release under the title you set. Please make sure it highlights your
valuable contribution.

Replace this with a description of the change, the issue it fixes (if
applicable), and relevant context. List any dependencies required for
this change.

After you're done, someone will review your PR. They may suggest
improvements. If no one reviews your PR within a few days, feel free to
@-mention the same people again, as notifications can get lost.
-->

<!-- Remove if not applicable -->

Fixes # (issue)

## Before submitting

<!-- If you're adding a new integration, include an integration test and
an example notebook showing its use! -->

## Who can review?

Community members can review the PR once tests pass. Tag
maintainers/contributors who might be interested:

@eyurtsev

<!-- For a quicker response, figure out the right person to tag with @

        @hwchase17 - project lead

        Tracing / Callbacks
        - @agola11

        Async
        - @agola11

        DataLoaders
        - @eyurtsev

        Models
        - @hwchase17
        - @agola11

        Agents / Tools / Toolkits
        - @vowelparrot
        
        VectorStores / Retrievers / Memory
        - @dev2049
        
 -->
2023-05-12 13:04:28 -04:00
Neil Ruaro
3a2855945b added documentation on retrieving a PG vectorstore (#4578)
This PR adds in documentation on querying an existing vectorstore in PG 

Fixes 3191 (issue)
2023-05-12 13:04:06 -04:00
Andrea Pinto
1e5d25b93c Improve error messages formatting in doc loaders (#4586)
# Cosmetic in errors formatting

Added appropriate spacing to the `ImportError` message in a bunch of
document loaders to enhance trace readability (including Google Drive,
Youtube, Confluence and others). This change ensures that the error
messages are not displayed as a single line block, and that the `pip
install xyz` commands can be copied to clipboard from terminal easily.

## Who can review?

@eyurtsev
2023-05-12 13:03:39 -04:00
kYLe
570d057db4 Expose AnyScale LLM in langchain.llms (#4585)
# Expose AnyScale LLM in  langchain.llms

Fixes # update init.py so we can from langchain.llms import Anyscale
2023-05-12 12:48:38 -04:00
Eugene Yurtsev
a5371a0fa2 Add pytest --only-extended and --only-core options (#4494)
# Adds testing options to pytest

This PR adds the following options: 

* `--only-core` will skip all extended tests, running all core tests.
* `--only-extended` will skip all core tests. Forcing alll extended
tests to be run.

Running `py.test` without specifying either option will remain
unaffected. Run
all tests that can be run within the unit_tests direction. Extended
tests will
run if required packages are installed.

## Before submitting

## Who can review?
2023-05-12 11:35:22 -04:00
Harrison Chase
5ad151ed44 Add constitutional principles from paper (#4554)
Add constitutional principles from https://arxiv.org/pdf/2212.08073.pdf

---------

Co-authored-by: Dev 2049 <dev.dev2049@gmail.com>
2023-05-12 07:34:03 -07:00
Sai Vinay G
cf4c1394a2 feat: Added class to support huggingface text generation inference server (#4447)
[Text Generation
Inference](https://github.com/huggingface/text-generation-inference) is
a Rust, Python and gRPC server for generating text using LLMs.

This pull request add support for self hosted Text Generation Inference
servers.

feature: #4280

---------

Co-authored-by: Your Name <you@example.com>
Co-authored-by: Dev 2049 <dev.dev2049@gmail.com>
2023-05-12 07:32:37 -07:00
Zander Chase
258c319855 Dereference Messages (#4557)
Update how we parse the messages now that the server splits prompts /
messages up
2023-05-12 00:12:43 -07:00
Leonid Ganeline
e17d0319d5 Add arxiv retriever (#4538) 2023-05-11 22:48:38 -07:00
vinoyang
25cd6e060a Enhance the prompt to make the LLM generate right date for real today (#4505)
# Enhance the prompt to make the LLM generate right date for real today

Fixes # (issue)

Currently, if the user's question contains `today`, the clickhouse
always points to an old date. This may be related to the fact that the
GPT training data is relatively old.
2023-05-11 22:11:14 -04:00
vinoyang
e942db3e78 Add prestodb prompt (#4516)
Add a PrestoDB prompt
2023-05-11 22:09:48 -04:00
SimFG
7bcf238a1a Optimize the initialization method of GPTCache (#4522)
Optimize the initialization method of GPTCache, so that users can use GPTCache more quickly.
2023-05-11 16:15:23 -07:00
Zander Chase
f4d3cf2dfb Add Invocation Params (#4509)
### Add Invocation Params to Logged Run


Adds an llm type to each chat model as well as an override of the dict()
method to log the invocation parameters for each call

---------

Co-authored-by: Ankush Gola <ankush.gola@gmail.com>
2023-05-11 15:34:06 -07:00
Ankush Gola
59853fc876 add invocation params as extra params in llm callbacks (#4506)
# Your PR Title (What it does)

<!--
Thank you for contributing to LangChain! Your PR will appear in our next
release under the title you set. Please make sure it highlights your
valuable contribution.

Replace this with a description of the change, the issue it fixes (if
applicable), and relevant context. List any dependencies required for
this change.

After you're done, someone will review your PR. They may suggest
improvements. If no one reviews your PR within a few days, feel free to
@-mention the same people again, as notifications can get lost.
-->

<!-- Remove if not applicable -->

Fixes # (issue)

## Before submitting

<!-- If you're adding a new integration, include an integration test and
an example notebook showing its use! -->

## Who can review?

Community members can review the PR once tests pass. Tag
maintainers/contributors who might be interested:

<!-- For a quicker response, figure out the right person to tag with @

        @hwchase17 - project lead

        Tracing / Callbacks
        - @agola11

        Async
        - @agola11

        DataLoader Abstractions
        - @eyurtsev

        LLM/Chat Wrappers
        - @hwchase17
        - @agola11

        Tools / Toolkits
        - @vowelparrot
 -->
2023-05-11 15:33:52 -07:00
Ofey Chan
1c0ec26e40 [pyproject.toml] add tiktoken when install langchain[openai] (#4514)
# Add `tiktoken` as dependency when installed as `langchain[openai]`

Fixes #4513 (issue)

## Who can review?

Community members can review the PR once tests pass. Tag
maintainers/contributors who might be interested:

@vowelparrot 

<!-- For a quicker response, figure out the right person to tag with @

        @hwchase17 - project lead

        Tracing / Callbacks
        - @agola11

        Async
        - @agola11

        DataLoaders
        - @eyurtsev

        Models
        - @hwchase17
        - @agola11

        Agents / Tools / Toolkits
        - @vowelparrot
        
        VectorStores / Retrievers / Memory
        - @dev2049
        
 -->
2023-05-11 12:21:06 -07:00
Zander Chase
4ee47926ca Add on_chat_message_start (#4499)
### Add on_chat_message_start to callback manager and base tracer

Goal: trace messages directly to permit reloading as chat messages
(store in an integration-agnostic way)

Add an `on_chat_message_start` method. Fall back to `on_llm_start()` for
handlers that don't have it implemented.

Does so in a non-backwards-compat breaking way (for now)
2023-05-11 11:06:39 -07:00
Yu Le
bbf76dbb52 fix typos in the prompts of LLMSummarizationCheckerChain (#4518) 2023-05-11 10:32:34 -07:00
Jonas Nelle
97e7dc1502 Make BaseStringMessagePromptTemplate.from_template return type generic (#4523)
# Make BaseStringMessagePromptTemplate.from_template return type generic

I use mypy to check type on my code that uses langchain. Currently after
I load a prompt and convert it to a system prompt I have to explicitly
cast it which is quite ugly (and not necessary):
```
prompt_template = load_prompt("prompt.yaml")
system_prompt_template = cast(
    SystemMessagePromptTemplate,
    SystemMessagePromptTemplate.from_template(prompt_template.template),
)
```

With this PR, the code would simply be: 
```
prompt_template = load_prompt("prompt.yaml")
system_prompt_template = SystemMessagePromptTemplate.from_template(prompt_template.template)
```

Given how much langchain uses inheritance, I think this type hinting
could be applied in a bunch more places, e.g. load_prompt also return a
`FewShotPromptTemplate` or a `PromptTemplate` but without typing the
type checkers aren't able to infer that. Let me know if you agree and I
can take a look at implementing that as well.

        @hwchase17 - project lead

        DataLoaders
        - @eyurtsev
2023-05-11 10:24:50 -07:00
kYLe
446b60d803 Fix a typo in langchain/docs/modules/models/llms/integrations/anyscale.ipynb (#4526) 2023-05-11 09:03:04 -07:00
Davis Chase
0f93de0a59 Release 0.0.166 (#4510) 2023-05-11 08:53:48 -07:00
Sunish Sheth
812e5f43f5 Add _type for all parsers (#4189)
Used for serialization. Also add test that recurses through
our subclasses to check they have them implemented

Would fix https://github.com/hwchase17/langchain/issues/3217
Blocking: https://github.com/mlflow/mlflow/pull/8297

---------

Signed-off-by: Sunish Sheth <sunishsheth2009@gmail.com>
Co-authored-by: Dev 2049 <dev.dev2049@gmail.com>
2023-05-11 01:27:58 -07:00
Akshaya Annavajhala
b21d7c138c Callback Handler for MLflow (#4150)
Rebased Mahmedk's PR with the callback refactor and added the example
requested by hwchase plus a couple minor fixes

---------

Co-authored-by: Ahmed K <77802633+mahmedk@users.noreply.github.com>
Co-authored-by: Ahmed K <mda3k27@gmail.com>
Co-authored-by: Davis Chase <130488702+dev2049@users.noreply.github.com>
Co-authored-by: Corey Zumar <39497902+dbczumar@users.noreply.github.com>
Co-authored-by: Dev 2049 <dev.dev2049@gmail.com>
2023-05-11 01:10:40 -07:00
kYLe
0d51a1f12b Add LLMs support for Anyscale Service (#4350)
Add Anyscale service integration under LLM

Co-authored-by: Dev 2049 <dev.dev2049@gmail.com>
2023-05-11 00:39:59 -07:00
Kristóf Dombi
99b2400048 [Docs]: Add Kinsta to the list of deployment providers (#4445)
We're fans of the LangChain framework thus we wanted to make sure we
provide an easy way for our customers to be able to utilize this
framework for their LLM-powered applications at our platform.
2023-05-11 00:29:48 -07:00
Evan Jones
f668251948 parameterized distance metrics; lint; format; tests (#4375)
# Parameterize Redis vectorstore index

Redis vectorstore allows for three different distance metrics: `L2`
(flat L2), `COSINE`, and `IP` (inner product). Currently, the
`Redis._create_index` method hard codes the distance metric to COSINE.

I've parameterized this as an argument in the `Redis.from_texts` method
-- pretty simple.

Fixes #4368 

## Before submitting

I've added an integration test showing indexes can be instantiated with
all three values in the `REDIS_DISTANCE_METRICS` literal. An example
notebook seemed overkill here. Normal API documentation would be more
appropriate, but no standards are in place for that yet.

## Who can review?

Not sure who's responsible for the vectorstore module... Maybe @eyurtsev
/ @hwchase17 / @agola11 ?
2023-05-11 00:20:01 -07:00
Nick Omeyer
f46710d408 Fix minor issues in self-query retriever prompt formatting (#4450)
# Fix minor issues in self-query retriever prompt formatting

I noticed a few minor issues with the self-query retriever's prompt
while using it, so here's PR to fix them 😇

## Who can review?

Community members can review the PR once tests pass. Tag
maintainers/contributors who might be interested:

<!-- For a quicker response, figure out the right person to tag with @

        @hwchase17 - project lead

        Tracing / Callbacks
        - @agola11

        Async
        - @agola11

        DataLoader Abstractions
        - @eyurtsev

        LLM/Chat Wrappers
        - @hwchase17
        - @agola11

        Tools / Toolkits
        - @vowelparrot
 -->
2023-05-11 00:10:41 -07:00
Zander Chase
d969f43ed8 Load HuggingFace Tool (#4475)
# Add option to `load_huggingface_tool`

Expose a method to load a huggingface Tool from the HF hub

---------

Co-authored-by: Dev 2049 <dev.dev2049@gmail.com>
2023-05-11 00:07:36 -07:00
Davis Chase
cd01de49cf Update contribution guidelines (#4431)
provide more guidance on pr's
2023-05-11 00:05:25 -07:00
Eugene Yurtsev
146616aa5d Test workflow, fix minor typos (#4495)
# Fix 2 minor typos in test workflow.

This PR does not result in any functional changes.
2023-05-10 22:36:50 -04:00
Eugene Yurtsev
f373883c1a Refactor test workflow (#4457)
# Refactor the test workflow

This PR refactors the tests to run using a single test workflow. This
makes it easier to relaunch failing tests and see in the UI which test
failed since the jobs are grouped together.

## Before submitting

## Who can review?
2023-05-10 21:57:39 -04:00
Davis Chase
b77e103ca6 Add aleph alpha api key attribute (#4489)
@tugot17 applied your change to master
2023-05-10 17:29:57 -07:00
Harrison Chase
3ce29cb4a6 Harrison/new search (#4359)
Co-authored-by: Jiaping(JP) Zhang <vincentzhangv@gmail.com>
2023-05-10 17:09:16 -07:00
Jakob Heyder
545ae8b756 Fix: Add run_manager on all AgentFinish returns in AgentExecutor (#4466) 2023-05-10 16:25:23 -07:00
Ankush Gola
ae8d6d5a89 Add docs for tracing environment variable (#4477) 2023-05-10 16:07:02 -07:00
Davis Chase
9ec60ad832 Add azure cognitive search retriever (#4467)
All credit to @UmerHA, made a couple small changes

---------

Co-authored-by: UmerHA <40663591+UmerHA@users.noreply.github.com>
2023-05-10 15:27:27 -07:00
Davis Chase
46b100ea63 Add DocArray vector stores (#4483)
Thanks to @anna-charlotte and @jupyterjazz for the contribution! Made
few small changes to get it across the finish line

---------

Signed-off-by: anna-charlotte <charlotte.gerhaher@jina.ai>
Signed-off-by: jupyterjazz <saba.sturua@jina.ai>
Co-authored-by: anna-charlotte <charlotte.gerhaher@jina.ai>
Co-authored-by: jupyterjazz <saba.sturua@jina.ai>
Co-authored-by: Saba Sturua <45267439+jupyterjazz@users.noreply.github.com>
2023-05-10 15:22:16 -07:00
Davis Chase
f2a536b445 release 165 (#4486)
bump version
2023-05-10 15:20:43 -07:00
Harrison Chase
b2f920e891 add tracing v2 env var (#4465)
Co-authored-by: Ankush Gola <ankush.gola@gmail.com>
2023-05-10 11:08:29 -07:00
Zander Chase
9231143f91 Fix Duplicate trust_remote_code in pipeline (#4369)
### Fix issue with duplicate specification of `trust_remote_code` in
HuggingFacePipeline

Fixes # 4351
2023-05-10 10:21:54 -07:00
Davis Chase
6fbdb9ce51 Release 0.0.164 (#4454) 2023-05-10 08:44:14 -07:00
Davis Chase
04475bea7d Mv plan and execute to experimental (#4459) 2023-05-10 08:31:53 -07:00
netseye
1ad180f6de Add request timeout to openai embedding (#4144)
Add request_timeout field to openai embedding. Defaults to None

---------

Co-authored-by: Jeakin <Jeakin@botu.cc>
2023-05-10 08:11:32 -07:00
zvrr
274dc4bc53 add clickhouse prompt (#4456)
# Add clickhouse prompt

Add clickhouse database sql prompt
2023-05-10 10:22:42 -04:00
Paresh Mathur
05e749d9fe make running specific unit tests easier (#4336)
I find it's easier to do TDD if i can run specific unit tests. I know
watch is there but some people prefer running their tests manually.
2023-05-10 09:39:22 -04:00
Eugene Yurtsev
80558b5b27 Add workflow for testing with all deps (#4410)
# Add action to test with all dependencies installed

PR adds a custom action for setting up poetry that allows specifying a
cache key:
https://github.com/actions/setup-python/issues/505#issuecomment-1273013236

This makes it possible to run 2 types of unit tests: 

(1) unit tests with only core dependencies
(2) unit tests with extended dependencies (e.g., those that rely on an
optional pdf parsing library)


As part of this PR, we're moving some pdf parsing tests into the
unit-tests section and making sure that these unit tests get executed
when running with extended dependencies.
2023-05-10 09:35:07 -04:00
Matt Robinson
3637d6da6e feat: add loader for open office odt files (#4405)
# ODF File Loader

Adds a data loader for handling Open Office ODT files. Requires
`unstructured>=0.6.3`.

### Testing

The following should work using the `fake.odt` example doc from the
[`unstructured` repo](https://github.com/Unstructured-IO/unstructured).

```python
from langchain.document_loaders import UnstructuredODTLoader

loader = UnstructuredODTLoader(file_path="fake.odt", mode="elements")
loader.load()

loader = UnstructuredODTLoader(file_path="fake.odt", mode="single")
loader.load()
```
2023-05-10 01:37:17 -07:00
Zander Chase
65f85af242 Improve math chain error msg (#4415) 2023-05-10 01:08:01 -07:00
Davis Chase
f6c97e6af4 Fix Lark import error (#4421)
Any import that touches langchain.retrievers currently requires Lark.
Here's one attempt to fix. Not very pretty, very open to other ideas.
Alternatives I thought of are 1) make Lark requirement, 2) put
everything in parser.py in the try/except. Neither sounds much better

Related to #4316, #4275
2023-05-10 01:07:34 -07:00
Harrison Chase
f0cfed636f change nb name 2023-05-09 21:22:35 -07:00
Harrison Chase
6b8d144ccc Harrison/plan and solve (#4422) 2023-05-09 21:07:56 -07:00
StephaneBereux
d383c0cb43 fixed the filtering error in chromadb (#1621)
Fixed two small bugs (as reported in issue #1619 ) in the filtering by
metadata for `chroma` databases :
- ```langchain.vectorstores.chroma.similarity_search``` takes a
```filter``` input parameter but do not forward it to
```langchain.vectorstores.chroma.similarity_search_with_score```
- ```langchain.vectorstores.chroma.similarity_search_by_vector```
doesn't take this parameter in input, although it could be very useful,
without any additional complexity - and it would thus be coherent with
the syntax of the two other functions.

Co-authored-by: Davis Chase <130488702+dev2049@users.noreply.github.com>
2023-05-09 16:43:00 -07:00
jrhe
28091c2101 Use passed LLM for default chain in MultiPromptChain (#4418)
Currently, MultiPromptChain instantiates a ChatOpenAI LLM instance for
the default chain to use if none of the prompts passed match. This seems
like an error as it means that you can't use your choice of LLM, or
configure how to instantiate the default LLM (e.g. passing in an API key
that isn't in the usual env variable).
2023-05-09 16:15:25 -07:00
Davis Chase
5c8e12558d Dev2049/pinecone try except (#4424)
Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
Co-authored-by: Bernie G <bernie.gandin2@gmail.com>
2023-05-09 16:03:19 -07:00
Rukmani
2b14036126 Update WhatsAppChatLoader to include the character ~ in the sender name (#4420)
Fixes #4153

If the sender of a message in a group chat isn't in your contact list,
they will appear with a ~ prefix in the exported chat. This PR adds
support for parsing such lines.
2023-05-09 15:00:04 -07:00
Zander Chase
f2150285a4 Fix nested runs example ID (#4413)
#### Only reference example ID on the parent run

Previously, I was assigning the example ID to every child run. 
Adds a test.
2023-05-09 12:21:53 -07:00
Davis Chase
e4ca511ec8 Delete comment (#4412) 2023-05-09 10:38:44 -07:00
mbchang
9fafe7b2b9 fix: remove unnecessary line of code (#4408)
Removes unnecessary line of code in
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html
2023-05-09 10:35:09 -07:00
Aivin V. Solatorio
6335cb5b3a Add support for Qdrant nested filter (#4354)
# Add support for Qdrant nested filter

This extends the filter functionality for the Qdrant vectorstore. The
current filter implementation is limited to a single-level metadata
structure; however, Qdrant supports nested metadata filtering. This
extends the functionality for users to maximize the filter functionality
when using Qdrant as the vectorstore.

Reference: https://qdrant.tech/documentation/filtering/#nested-key

---------

Signed-off-by: Aivin V. Solatorio <avsolatorio@gmail.com>
2023-05-09 10:34:11 -07:00
Martin Holzhauer
872605a5c5 Add an option to extract more metadata from crawled websites (#4347)
This pr makes it possible to extract more metadata from websites for
later use.

my usecase:
parsing ld+json or microdata from sites and store it as structured data
in the metadata field
2023-05-09 10:18:33 -07:00
Leonid Ganeline
ce15ffae6a added Wikipedia retriever (#4302)
- added `Wikipedia` retriever. It is effectively a wrapper for
`WikipediaAPIWrapper`. It wrapps load() into get_relevant_documents()
- sorted `__all__` in the `retrievers/__init__`
- added integration tests for the WikipediaRetriever
- added an example (as Jupyter notebook) for the WikipediaRetriever
2023-05-09 10:08:39 -07:00
Davis Chase
ea83eed9ba Bump to version 0.0.163 (#4382) 2023-05-09 07:51:51 -07:00
Prayson Wilfred Daniel
2b4ba203f7 query correction from when to what (#4383)
# Minor Wording Documentation Change 

```python
agent_chain.run("When's my friend Eric's surname?")
# Answer with 'Zhu'
```

is change to 

```python
agent_chain.run("What's my friend Eric's surname?")
# Answer with 'Zhu'
```

I think when is a residual of the old query that was "When’s my friends
Eric`s birthday?".
2023-05-09 07:42:47 -07:00
Eugene Yurtsev
2ceb807da2 Add PDF parser implementations (#4356)
# Add PDF parser implementations

This PR separates the data loading from the parsing for a number of
existing PDF loaders.

Parser tests have been designed to help encourage developers to create a
consistent interface for parsing PDFs.

This interface can be made more consistent in the future by adding
information into the initializer on desired behavior with respect to splitting by
page etc.

This code is expected to be backwards compatible -- with the exception
of a bug fix with pymupdf parser which was returning `bytes` in the page
content rather than strings.

Also changing the lazy parser method of document loader to return an
Iterator rather than Iterable over documents.

## Before submitting

<!-- If you're adding a new integration, include an integration test and
an example notebook showing its use! -->

## Who can review?

Community members can review the PR once tests pass. Tag
maintainers/contributors who might be interested:

@

<!-- For a quicker response, figure out the right person to tag with @

        @hwchase17 - project lead

        Tracing / Callbacks
        - @agola11

        Async
        - @agola11

        DataLoader Abstractions
        - @eyurtsev

        LLM/Chat Wrappers
        - @hwchase17
        - @agola11

        Tools / Toolkits
        - @vowelparrot
 -->
2023-05-09 10:24:17 -04:00
Eugene Yurtsev
ae0c3382dd Add MimeType based parser (#4376)
# Add MimeType Based Parser

This PR adds a MimeType Based Parser. The parser inspects the mime-type
of the blob it is parsing and based on the mime-type can delegate to the sub
parser.

## Before submitting

Waiting on adding notebooks until more implementations are landed. 

## Who can review?

Community members can review the PR once tests pass. Tag
maintainers/contributors who might be interested:


@hwchase17
@vowelparrot
2023-05-09 10:22:56 -04:00
Leonid Ganeline
c485e7ab59 added GitHub star number (#4214)
added GitHub star number with a link to the `GitHub star history chart`
This is an interesting chart https://star-history.com/#hwchase17/langchain :)
2023-05-09 09:39:53 -04:00
Heath
0d568daacb Update writer integration (#4363)
# Update Writer LLM integration

Changes the parameters and base URL to be in line with Writer's current
API.
Based on the documentation on this page:
https://dev.writer.com/reference/completions-1
2023-05-08 21:59:46 -07:00
BioErrorLog
04f765b838 Fix grammar in Text Splitters docs (#4373)
# Fix grammar in Text Splitters docs

Just a small fix of grammar in the documentation:

"That means there two different axes" -> "That means there are two
different axes"
2023-05-08 22:38:40 -04:00
Zander Chase
c73cec5ac1 Add Example Notebook for LCP Client (#4207)
Add a notebook in the `experimental/` directory detailing:
- How to capture traces with the v2 endpoint
- How to create datasets
- How to run traces over the dataset
2023-05-08 18:33:19 -07:00
mbchang
f1401a6dff new example: two agent debate with tools (#4024) 2023-05-08 17:10:44 -07:00
玄猫
deffc65693 fix: vectorstore pgvector ensure compatibility #3884 (#4248)
Ensure compatibility with both SQLAlchemy v1/v2 

fix the issue when using SQLAlchemy v1 (reported at #3884)

`
langchain/vectorstores/pgvector.py", line 168, in
create_tables_if_not_exists
    self._conn.commit()
AttributeError: 'Connection' object has no attribute 'commit'
`

Ref Doc :
https://docs.sqlalchemy.org/en/14/changelog/migration_20.html#migration-20-autocommit
2023-05-08 16:43:50 -07:00
Davis Chase
ba0057c077 Check OpenAI model kwargs (#4366)
Handle duplicate and incorrectly specified OpenAI params

Thanks @PawelFaron for the fix! Made small update

Closes #4331

---------

Co-authored-by: PawelFaron <42373772+PawelFaron@users.noreply.github.com>
Co-authored-by: Pawel Faron <ext-pawel.faron@vaisala.com>
2023-05-08 16:37:34 -07:00
Davis Chase
02ebb15c4a Fix TextSplitter.from_tiktoken(#4361)
Thanks to @danb27 for the fix! Minor update

Fixes https://github.com/hwchase17/langchain/issues/4357

---------

Co-authored-by: Dan Bianchini <42096328+danb27@users.noreply.github.com>
2023-05-08 16:36:38 -07:00
Naveen Tatikonda
782df1db10 OpenSearch: Add Similarity Search with Score (#4089)
### Description
Add `similarity_search_with_score` method for OpenSearch to return
scores along with documents in the search results

Signed-off-by: Naveen Tatikonda <navtat@amazon.com>
2023-05-08 16:35:21 -07:00
Ankush Gola
b3ecce0545 fix json saving, update docs to reference anthropic chat model (#4364)
Fixes # (issue)
https://github.com/hwchase17/langchain/issues/4085
2023-05-08 15:30:52 -07:00
ImmortalZ
b04d84f6b3 fix: solve the infinite loop caused by 'add_memory' function when run… (#4318)
fix: solve the infinite loop caused by 'add_memory' function when run
'pause_to_reflect' function

run steps:
'add_memory' -> 'pause_to_reflect' -> 'add_memory':  infinite loop
2023-05-08 15:13:23 -07:00
Eugene Yurtsev
aa11f7c89b Add progress bar to filesystemblob loader, update pytest config for unit tests (#4212)
This PR adds:

* Option to show a tqdm progress bar when using the file system blob loader
* Update pytest run configuration to be stricter
* Adding a new marker that checks that required pkgs exist
2023-05-08 16:15:09 -04:00
Eduard van Valkenburg
f4c8502e61 fix for cosmos not loading old messages (#4094)
I noticed cosmos was not loading old messages properly, fixed now.
2023-05-08 12:48:15 -07:00
Simba Khadder
d84df25466 Add example on how to use Featureform with langchain (#4337)
Added an example on how to use Featureform to
connecting_to_a_feature_store.ipynb .
2023-05-08 10:32:17 -07:00
Harrison Chase
42df78d396 bump ver 162 (#4346) 2023-05-08 09:28:41 -07:00
Zander Chase
8b284f9ad0 Pass parsed inputs through to tool _run (#4309) 2023-05-08 09:13:05 -07:00
Zander Chase
35c9e6ab40 Pass Callbacks through load_tools (#4298)
- Update the load_tools method to properly accept `callbacks` arguments.
- Add a deprecation warning when `callback_manager` is passed
- Add two unit tests to check the deprecation warning is raised and to
confirm the callback is passed through.

Closes issue #4096
2023-05-08 08:44:26 -07:00
Zander Chase
0870a45a69 Add Pull Request Template (#4247) 2023-05-08 08:34:37 -07:00
Jinto Jose
8a338412fa mongodb support for chat history (#4266) 2023-05-08 08:34:05 -07:00
Harrison Chase
f510940bde add check for lower bound of lark (#4287) 2023-05-08 08:31:05 -07:00
Harrison Chase
c8b0b6e6c1 add youtube tools (#4320) 2023-05-08 08:29:30 -07:00
PawelFaron
1d1166ded6 Fixed huggingfacehub_api_token hadning in HuggingFaceEndpoint (#4335)
Reported here:
https://github.com/hwchase17/langchain/issues/4334

---------

Co-authored-by: Pawel Faron <ext-pawel.faron@vaisala.com>
2023-05-08 08:29:17 -07:00
Arjun Aravindan
637c61cffb Add support for passing binary_location to the SeleniumURLLoader when creating Chrome or Firefox web drivers (#4305)
This commit adds support for passing binary_location to the SeleniumURLLoader when creating Chrome or Firefox web drivers.

This allows users to specify the Browser binary location which is required when deploying to services such as Heroku

This change also includes updated documentation and type hints to reflect the new binary_location parameter and its usage.

fixes #4304
2023-05-08 11:05:55 -04:00
Lior Neudorfer
65c95f9fb2 Better error when running chain without any args (#4294)
Today, when running a chain without any arguments, the raised ValueError
incorrectly specifies that user provided "both positional arguments and
keyword arguments".

This PR adds a more accurate error in that case.
2023-05-07 21:11:51 -07:00
Harrison Chase
edcd171535 bring back ref (#4308) 2023-05-07 17:32:28 -07:00
Wuxian Zhang
6f386628c2 Permit unicode outputs when dumping json in GetElementsTool (#4276)
Adds ensure_ascii=False when dumping json in the GetElementsTool
Fixes issue https://github.com/hwchase17/langchain/issues/4265
2023-05-07 14:43:03 -07:00
Eugene Brodsky
a1001b29eb Incorrect docstring for PythonCodeTextSplitter (#4296)
Fixes a copy-paste error in the doctring
2023-05-07 14:04:54 -07:00
Ikko Eltociear Ashimine
f70e18a5b3 Fix typo in huggingface.py (#4277)
enviroment -> environment
2023-05-07 11:37:06 -04:00
Eugene Yurtsev
0c646bb703 Minor clean up in BlobParser (#4210)
Minor clean up to use `abstractmethod` and `ABC` instead of `abc.abstractmethod` and `abc.ABC`.
2023-05-07 11:32:53 -04:00
PawelFaron
04b74d0446 Adjusted GPT4All llm to streaming API and added support for GPT4All_J (#4131)
Fix for these issues:
https://github.com/hwchase17/langchain/issues/4126

https://github.com/hwchase17/langchain/issues/3839#issuecomment-1534258559

---------

Co-authored-by: Pawel Faron <ext-pawel.faron@vaisala.com>
2023-05-06 15:14:09 -07:00
Harrison Chase
075d9631f5 bump ver to 161 (#4239) 2023-05-06 10:20:36 -07:00
Harrison Chase
64940e9d0f docs for azure (#4238) 2023-05-06 10:16:00 -07:00
Myeongseop Kim
747b5f87c2 Add HumanInputLLM (#4160)
Related: #4028, I opened a new PR because (1) I was unable to unstage
mistakenly committed files (I'm not familiar with git enough to resolve
this issue), (2) I felt closing the original PR and opening a new PR
would be more appropriate if I changed the class name.

This PR creates HumanInputLLM(HumanLLM in #4028), a simple LLM wrapper
class that returns user input as the response. I also added a simple
Jupyter notebook regarding how and why to use this LLM wrapper. In the
notebook, I went over how to use this LLM wrapper and showed example of
testing `WikipediaQueryRun` using HumanInputLLM.
 
I believe this LLM wrapper will be useful especially for debugging,
educational or testing purpose.
2023-05-06 09:48:40 -07:00
Davis Chase
6cd51ef3d0 Simplify router chain constructor signatures (#4146) 2023-05-06 09:38:17 -07:00
玄猫
43a7a89e93 opt: document_loader notiondb to extract url (#4222) 2023-05-06 09:34:33 -07:00
Leonid Ganeline
9544b30821 added Wikipedia document loader (#4141)
- Added the `Wikipedia` document loader. It is based on the existing
`unilities/WikipediaAPIWrapper`
- Added a respective ut-s and example notebook
- Sorted list of classes in __init__
2023-05-06 09:32:45 -07:00
Eugene Yurtsev
423f497168 Add BlobParser abstraction (#3979)
This PR adds the BlobParser abstraction.

It follows the proposal described here:
https://github.com/hwchase17/langchain/pull/2833#issuecomment-1509097756
2023-05-05 21:43:38 -04:00
Davis Chase
5ca13cc1f0 Dev2049/pypdfium2 (#4209)
thanks @jerrytigerxu for the addition!

---------

Co-authored-by: Jere Xu <jtxu2008@gmail.com>
Co-authored-by: jerrytigerxu <jere.tiger.xu@gmailc.om>
2023-05-05 17:55:31 -07:00
Leonid Ganeline
59204a5033 docs: document_loaders improvements (#4200)
- made notebooks consistent: titles, service/format descriptions.
- corrected short names to full names, for example, `Word` -> `Microsoft
Word`
- added missed descriptions
- renamed notebook files to make ToC correctly sorted
2023-05-05 17:44:54 -07:00
Harrison Chase
eeb7c96e0c bump version to 160 (#4205) 2023-05-05 17:02:39 -07:00
Davis Chase
f1fc4dfebc Dev2049/obsidian patch (#4204)
thanks @shkarlsson for the fix! (just updated formatting)

---------

Co-authored-by: shkarlsson <sven.henrik.karlsson@gmail.com>
2023-05-05 16:49:19 -07:00
George
2324f19c85 Update qdrant interface (#3971)
Hello

1) Passing `embedding_function` as a callable seems to be outdated and
the common interface is to pass `Embeddings` instance

2) At the moment `Qdrant.add_texts` is designed to be used with
`embeddings.embed_query`, which is 1) slow 2) causes ambiguity due to 1.
It should be used with `embeddings.embed_documents`

This PR solves both problems and also provides some new tests
2023-05-05 16:46:40 -07:00
Harrison Chase
76ed41f48a update docs (#4194) 2023-05-05 16:45:26 -07:00
Zander Chase
1017e5cee2 Add LCP Client (#4198)
Adding a client to fetch datasets, examples, and runs from a LCP
instance and run objects over them.
2023-05-05 16:28:56 -07:00
Zander Chase
a30f42da4e Update V2 Tracer (#4193)
- Update the RunCreate object to work with recent changes
- Add optional Example ID to the tracer
- Adjust default persist_session behavior to attempt to load the session
if it exists
- Raise more useful HTTP errors for logging
- Add unit testing
- Fix the default ID to be a UUID for v2 tracer sessions


Broken out from the big draft here:
https://github.com/hwchase17/langchain/pull/4061
2023-05-05 14:55:01 -07:00
Mike Wang
c3044b1bf0 [test] Add integration_test for PandasAgent (#4056)
- confirm creation
- confirm functionality with a simple dimension check.

The test now is calling OpenAI API directly, but learning from
@vowelparrot that we’re caching the requests, so that it’s not that
expensive. I also found we’re calling OpenAI api in other integration
tests. Please lmk if there is any concern of real external API calls. I
can alternatively make a fake LLM for this test. Thanks
2023-05-05 14:49:02 -07:00
Aivin V. Solatorio
6567b73e1a JSON loader (#4067)
This implements a loader of text passages in JSON format. The `jq`
syntax is used to define a schema for accessing the relevant contents
from the JSON file. This requires dependency on the `jq` package:
https://pypi.org/project/jq/.

---------

Signed-off-by: Aivin V. Solatorio <avsolatorio@gmail.com>
2023-05-05 14:48:13 -07:00
PawelFaron
bb6d97c18c Fixed the example code (#4117)
Fixed the issue mentioned here:

https://github.com/hwchase17/langchain/issues/3799#issuecomment-1534785861

Co-authored-by: Pawel Faron <ext-pawel.faron@vaisala.com>
2023-05-05 14:22:10 -07:00
Anurag
19e28d8784 feat: Allow users to pass additional arguments to the WebDriver (#4121)
This commit adds support for passing additional arguments to the
`SeleniumURLLoader ` when creating Chrome or Firefox web drivers.
Previously, only a few arguments such as `headless` could be passed in.
With this change, users can pass any additional arguments they need as a
list of strings using the `arguments` parameter.

The `arguments` parameter allows users to configure the driver with any
options that are available for that particular browser. For example,
users can now pass custom `user_agent` strings or `proxy` settings using
this parameter.

This change also includes updated documentation and type hints to
reflect the new `arguments` parameter and its usage.

fixes #4120
2023-05-05 13:24:42 -07:00
hp0404
2a3c5f8353 Update WhatsAppChatLoader regex to handle multiple date-time formats (#4186)
This PR updates the `message_line_regex` used by `WhatsAppChatLoader` to
support different date-time formats used in WhatsApp chat exports;
resolves #4153.

The new regex handles the following input formats:
```terminal
[05.05.23, 15:48:11] James: Hi here
[11/8/21, 9:41:32 AM] User name: Message 123
1/23/23, 3:19 AM - User 2: Bye!
1/23/23, 3:22_AM - User 1: And let me know if anything changes
```

Tests have been added to verify that the loader works correctly with all
formats.
2023-05-05 13:13:05 -07:00
Nicolas
a57259ec83 docs: Mendable Fixes and Improvements (#4184)
Overall fixes and improvements.
2023-05-05 13:04:24 -07:00
Harrison Chase
7dcc698ebf bump version to 159 (#4183) 2023-05-05 09:31:08 -07:00
Harrison Chase
26534457f5 simplify csv args (#4182) 2023-05-05 09:22:08 -07:00
Eduard van Valkenburg
3095546851 PowerBI fix for table names with spaces (#4170)
small fix to make sure a table name with spaces is passed correctly to
the API for the schema lookup.
2023-05-05 09:15:47 -07:00
obbiondo
b1e2e29222 fix: remove expand parameter from ConfluenceLoader by label (#4181)
expand is not an allowed parameter for the method
confluence.get_all_pages_by_label, since it doesn't return the body of
the text but just metadata of documents

Co-authored-by: Andrea Biondo <a.biondo@reply.it>
2023-05-05 09:15:21 -07:00
Zander Chase
84cfa76e00 Update Cohere Reranker (#4180)
The forward ref annotations don't get updated if we only iimport with
type checking

---------

Co-authored-by: Abhinav Verma <abhinav_win12@yahoo.co.in>
2023-05-05 09:11:37 -07:00
Davis Chase
d84bb02881 Add Chroma self query (#4149)
Add internal query language -> chroma metadata filter translator
2023-05-05 08:43:08 -07:00
Vinoo Ganesh
905a2114d7 Fix: Typo in Docs (#4179)
Fixing small typo in docs
2023-05-05 08:35:49 -07:00
Ankush Gola
8de1b4c4c2 Revert "fix: #4128 missing run_manager parameter" (#4159)
Reverts hwchase17/langchain#4130
2023-05-05 00:52:16 -07:00
Chakib Ben Ziane
878d0c8155 fix: #4128 missing run_manager parameter (#4130)
`run_manager` was not being passed downstream. Not sure if this was a
deliberate choice but it seems like it broke many agent callbacks like
`agent_action` and `agent_finish`. This fix needs a proper review.

Co-authored-by: blob42 <spike@w530>
2023-05-04 23:59:55 -07:00
Zander Chase
6032a051e9 Add Tenant ID to V2 Tracer (#4135)
Update the V2 tracer to
- use UUIDs instead of int's
- load a tenant ID and use that when saving sessions
2023-05-04 21:35:20 -07:00
Zander Chase
fea639c1fc Vwp/sqlalchemy (#4145)
Bump threshold to 1.4 from 1.3. Change import to be compatible

Resolves #4142 and #4129

---------

Co-authored-by: ndaugreal <ndaugreal@gmail.com>
Co-authored-by: Jeremy Lopez <lopez86@users.noreply.github.com>
2023-05-04 20:46:38 -07:00
Zander Chase
2f087d63af Fix Python RePL Tool (#4137)
Filter out kwargs from inferred schema when determining if a tool is
single input.

Add a couple unit tests.

Move tool unit tests to the tools dir
2023-05-04 20:31:16 -07:00
Zander Chase
cc068f1b77 Add Issue Templates (#4021)
Add issue templates for
- bug reports
- feature suggestions
- documentation
and a link to the discord for general discussion.

Open to other suggestions here. Could also add another "Other" template
with just a raw text box if we think this is too restrictive


<img width="1464" alt="image"
src="https://user-images.githubusercontent.com/130414180/236115358-e603bcbe-282c-40c7-82eb-905eb93ccec0.png">
2023-05-04 16:33:52 -07:00
Zander Chase
ac0a9d02bd Visual Studio Code/Github Codespaces Dev Containers (#4035) (#4122)
Having dev containers makes its easier, faster and secure to setup the
dev environment for the repository.

The pull request consists of:

- .devcontainer folder with:
- **devcontainer.json :** (minimal necessary vscode extensions and
settings)
- **docker-compose.yaml :** (could be modified to run necessary services
as per need. Ex vectordbs, databases)
    - **Dockerfile:**(non root with dev tools)
- Changes to README - added the Open in Github Codespaces Badge - added
the Open in dev container Badge

Co-authored-by: Jinto Jose <129657162+jj701@users.noreply.github.com>
2023-05-04 11:37:00 -07:00
Harrison Chase
d86ed15d88 bump version to 158 (#4091) 2023-05-04 09:14:47 -07:00
OlajideOgun
624554a43a DeepLake: Pass in rest of args to self._search_helper (#4080)
As of right now when trying to use functions like
`max_marginal_relevance_search()` or
`max_marginal_relevance_search_by_vector()` the rest of the kwargs are
not propagated to `self._search_helper()`. For example a user cannot
explicitly state the distance_metric they want to use when calling
`max_marginal_relevance_search`
2023-05-04 02:14:22 -07:00
Eduard van Valkenburg
6d84541ff9 fix base url (#4095)
Noticed a mistake in the base url and group vs non-group urls
2023-05-04 02:08:21 -07:00
Harrison Chase
a9c2450330 Harrison/toml loader (#4090)
Co-authored-by: Mika Ayenson <Mikaayenson@users.noreply.github.com>
2023-05-03 23:14:39 -07:00
Harrison Chase
d4cf1eb60a Add firestore memory (#3792) (#3941)
If you have any other suggestions or feedback, please let me know.

---------

Co-authored-by: yakigac <10434946+yakigac@users.noreply.github.com>
2023-05-03 22:55:47 -07:00
Harrison Chase
fba6921b50 Harrison/one drive loader (#4081)
Co-authored-by: José Ferraz Neto <netoferraz@gmail.com>
2023-05-03 22:55:34 -07:00
golergka
bd277b5327 feat: prune summary buffer (#4004)
If the library user has to decrease the `max_token_limit`, he would
probably want to prune the summary buffer even though he haven't added
any new messages.

Personally, I need it because I want to serialise memory buffer object
and save to database, and when I load it, I may have re-configured my
code to have a shorter memory to save on tokens.
2023-05-03 22:45:48 -07:00
AndreLCanada
bf726f9d8a Update python_repl docs (#4012)
In the example for creating a Python REPL tool under the Agent module,
the ".run" was omitted in the example. I believe this is required when
defining a Tool.
2023-05-03 22:45:32 -07:00
Mike Wang
67db495fcf [agent] Add Spark Agent (#4020)
- added support for spark through pyspark library.
- added jupyter notebook as example.
2023-05-03 22:45:23 -07:00
Gengliang Wang
8af25867cb Simplify HumanMessages in the quick start guide (#4026)
In the section `Get Message Completions from a Chat Model` of the quick
start guide, the HumanMessage doesn't need to include `Translate this
sentence from English to French.` when there is a system message.

Simplify HumanMessages in these examples can further demonstrate the
power of LLM.
2023-05-03 22:45:03 -07:00
Harrison Chase
087a4bd2b8 improve agent documentation (#4062) 2023-05-03 22:44:01 -07:00
rogerserper
b1446bea5f google-serper: async + full json results + support for Google Images, Places and News (#4078)
* implemented arun, results, and aresults. Reuses aiosession if
available.
* helper tools GoogleSerperRun and GoogleSerperResults
* support for Google Images, Places and News (examples given) and
filtering based on time (e.g. past hour)
* updated docs
2023-05-03 22:35:48 -07:00
mbchang
cdea47491d refactor: refactor dialogue examples (DialogueAgent, DialogueSimulator) (#4074)
refactor dialogue examples to have same DialogueAgent and
DialogueSimulator definitions
2023-05-03 22:32:26 -07:00
Jan Philipp Harries
657f5f259f Added option to reduce verbosity of Deeplake integration (#4038)
The deeplake integration was/is very verbose (see e.g. [the
documentation
example](https://python.langchain.com/en/latest/use_cases/code/code-analysis-deeplake.html)
when loading or creating a deeplake dataset with only limited options to
dial down verbosity.

Additionally, the warning that a "Deep Lake Dataset already exists" was
confusing, as there is as far as I can tell no other way to load a
dataset.

This small PR changes that and introduces an explicit `verbose` argument
which is also passed to the deeplake library.

There should be minimal changes to the default output (the loading line
is printed instead of warned to make it consistent with `ds.summary()`
which also prints.
2023-05-03 22:16:27 -07:00
Davis Chase
7f8727bbcd Router chains (#4019)
Unpolished router examples to help flesh out abstractions and use cases 
![Screenshot 2023-05-02 at 7 02 58
PM](https://user-images.githubusercontent.com/130488702/235820394-389e5584-db0b-415e-a260-2824b5555167.png)

---------

Co-authored-by: Shreya Rajpal <shreya.rajpal@gmail.com>
2023-05-03 22:02:55 -07:00
Pulkit Mehta
bbbca10704 issue#4082 base_language had wrong code comment that it was using gpt… (#4084)
…3 to tokenize text instead of gpt-2

Co-authored-by: Pulkit <pulkit.mehta@catylex.com>
2023-05-03 21:58:29 -07:00
Leonid Ganeline
6caba8e759 docs: added a link to the Google Scholar articles (#4007)
Google Scholar outputs a nice list of scientific and research articles
that use LangChain.
I added a link to the Google Scholar page to the `gallery` doc page
2023-05-03 21:54:44 -07:00
obbiondo
d18e788ee3 bugfix: return whole document when loading with ConfluenceLoader.load by label (#3980)
Method confluence.get_all_pages_by_label, returns only metadata about
documents with a certain label (such as pageId, titles, ...). To return
all documents with a certain label we need to extract all page ids given
a certain label and get pages content by these ids.

---------

Co-authored-by: Andrea Biondo <a.biondo@reply.it>
2023-05-03 21:52:05 -07:00
Harrison Chase
5f30cc8713 Harrison/knn retriever (#4083)
Co-authored-by: Yuichi Tateno (secon) <hotchpotch@users.noreply.github.com>
2023-05-03 21:21:58 -07:00
Zander Chase
65c3b146c9 Accept str or list[str] for shell (#4060)
Relax the requirements
2023-05-03 21:11:06 -07:00
Harrison Chase
5a269d3175 Harrison/media wiki xml (#4072)
Co-authored-by: Géraud de Drouas <gdedrouas@users.noreply.github.com>
2023-05-03 20:45:33 -07:00
Zeeland
c186f18aab fix: incorrect data type when construct_path in chain (#4031)
A incorrect data type error happened when executing _construct_path in
`chain.py` as follows:

```python
Error with message replace() argument 2 must be str, not int
```

The path is always a string. But the result of `args.pop(param, "")` is
undefined.
2023-05-03 18:49:47 -07:00
engkheng
349ba88aee Export FileChatMessageHistory (#4042) 2023-05-03 18:14:47 -07:00
Nikolas Garske
1608f5dcae Remove pip stdout and fix typo (#4050) 2023-05-03 18:06:39 -07:00
Ivo Stranic
3b556eae44 Update deeplake example (#4055) 2023-05-03 18:03:51 -07:00
Steve Kim
9b830f437c Deleted importing Document from document_loaders.base because Documen… (#4068)
Hi,

- Modification:
https://python.langchain.com/en/latest/modules/indexes/document_loaders/examples/arxiv.html
- Reason: In this example, the first line is unnecessary because the
Document class does not exist in the base.
- Resolves: Issue #4052

--------
P.S: This pull-request is my first time, so please let me know if I need
to correct or write more explanation.
2023-05-03 17:54:30 -07:00
hp0404
374725a715 Refactor TelegramChatLoader and FacebookChatLoader classes and add tests (#3863)
This PR includes two main changes:

- Refactor the `TelegramChatLoader` and `FacebookChatLoader` classes by
removing the dependency on pandas and simplifying the message filtering
process.

- Add test cases for the `TelegramChatLoader` and `FacebookChatLoader`
classes. This test ensures that the class correctly loads and processes
the example chat data, providing better test coverage for this
functionality.
2023-05-03 15:59:19 -07:00
Jon Saginaw
ea64b1716d Enhancement: option to Get All Tokens with a single Blockchain Document Loader call (#3797)
The Blockchain Document Loader's default behavior is to return 100
tokens at a time which is the Alchemy API limit. The Document Loader
exposes a startToken that can be used for pagination against the API.

This enhancement includes an optional get_all_tokens param (default:
False) which will:

- Iterate over the Alchemy API until it receives all the tokens, and
return the tokens in a single call to the loader.
- Manage all/most tokenId formats (this can be int, hex16 with zero or
all the leading zeros). There aren't constraints as to how smart
contracts can represent this value, but these three are most common.

Note that a contract with 10,000 tokens will issue 100 calls to the
Alchemy API, and could take about a minute, which is why this param will
default to False. But I've been using the doc loader with these
utilities on the side, so figured it might make sense to build them in
for others to use.
2023-05-03 15:46:44 -07:00
Akash Sharma
525db1b6cb Fixed typo leading to broken link (#4034) 2023-05-03 14:45:54 -07:00
Zander Chase
afa9d1292b Re-Permit Partials in Tool (#4058)
Resolved issue #4053

Now that StructuredTool is a separate class, this constraint is no
longer needed.

Added/updated a unit test
2023-05-03 13:16:41 -07:00
Zander Chase
7e967aa4d5 Update Notebooks (#4051) 2023-05-03 09:31:02 -07:00
Nuno Campos
f3ec6d2449 Replace remaining usage of basellm with baselangmodel (#3981) 2023-05-02 21:52:29 -07:00
mbchang
f291fd7eed docs: remove stdout from pip install (for gymnasium) (#3993) 2023-05-02 21:51:40 -07:00
Harrison Chase
b67be55ab8 bump ver (#4018) 2023-05-02 19:02:02 -07:00
Harrison Chase
a5dd73c1a6 Revert "[agent][property type] Change allowed_tools to Set as Duplicate doesn’t make sense" (#4014)
Reverts hwchase17/langchain#3840
2023-05-02 18:58:05 -07:00
Davis Chase
df3bc707fc Dev2049/callback example fix (#4010)
Closes #3997

---------

Co-authored-by: Akshaj Jain <akshaj.jain@gmail.com>
2023-05-02 16:20:16 -07:00
Davis Chase
f08a76250f Better custom model handling OpenAICallbackHandler (#4009)
Thanks @maykcaldas for flagging! think this should resolve #3988. Let me
know if you still see issues after next release.
2023-05-02 16:19:57 -07:00
Zander Chase
aa38355999 Vwp/docs improved document loaders (#4006)
Huge thanks to @leo-gan for improving the document loaders notebooks

---------

Co-authored-by: Leonid Ganeline <leo.gan.57@gmail.com>
2023-05-02 15:24:53 -07:00
Zander Chase
1c68cbdb28 Fix typing of attribute (#3999) 2023-05-02 15:11:23 -07:00
MichaelMDowling
36ee60c96c Update \docs\modules\models\text_embedding\examples\openai.ipynb (#3976)
Single edit to: models/text_embedding/examples/openai.ipynb - Line 88:
changed from: "embeddings = OpenAIEmbeddings(model_name=\"ada\")" to
"embeddings = OpenAIEmbeddings()" as model_name is no longer part of the
OpenAIEmbeddings class.
2023-05-02 14:41:31 -07:00
Harrison Chase
e23391965b fix import (#4003) 2023-05-02 14:26:46 -07:00
Jinto Jose
013208cce6 Fix Documentation - Nomic - Atlas Jupyter Notebook (#3987)
Correction to Numic-Atlas Jupyter Notebook Docs
2023-05-02 14:20:01 -07:00
Ankush Gola
18f9d7b4f6 don't deepcopy handlers (#3995)
Co-authored-by: Sami Liedes <sami.liedes@iki.fi>
Co-authored-by: Sami Liedes <sami.liedes@rocket-science.ch>
2023-05-02 13:53:27 -07:00
Mike Wang
c26cf04110 [check] add import check and warning for pandas (#3944)
- as titled, add an `import` catch for pandas with a user suggestion
message.
2023-05-02 10:08:16 -07:00
Chop Tr
71a337dac6 Update output_fixing_parser.ipynb (#3978) 2023-05-02 09:33:46 -07:00
Ankush Gola
3bd5a99b83 v2 tracer with single runs endpoint (#3951) 2023-05-01 22:41:32 -07:00
Harrison Chase
8fcb56e74a bump version to 155 (#3943) 2023-05-01 22:05:52 -07:00
Harrison Chase
ca08a34a98 retry to parsing (#3696) 2023-05-01 22:05:42 -07:00
mbchang
3993166b5e docs: remove stdout from pip install (#3945) 2023-05-01 22:05:22 -07:00
Harrison Chase
2366e71bed Harrison/azure openai (#3942)
Co-authored-by: Saverio Proto <zioproto@gmail.com>
2023-05-01 21:34:16 -07:00
Harrison Chase
48ea27ba60 Harrison/blockwise sitemap (#3940)
Co-authored-by: Martin Holzhauer <martin@holzhauer.eu>
2023-05-01 21:34:07 -07:00
Harrison Chase
483fe257d9 bump timeout (#3939) 2023-05-01 21:33:57 -07:00
Jan Philipp Harries
fc3c2c4406 Async Support for LLMChainExtractor (new) (#3780)
@vowelparrot @hwchase17 Here a new implementation of
`acompress_documents` for `LLMChainExtractor ` without changes to the
sync-version, as you suggested in #3587 / [Async Support for
LLMChainExtractor](https://github.com/hwchase17/langchain/pull/3587) .

I created a new PR to avoid cluttering history with reverted commits,
hope that is the right way.
Happy for any improvements/suggestions.

(PS:
I also tried an alternative implementation with a nested helper function
like

``` python
  async def acompress_documents_old(
      self, documents: Sequence[Document], query: str
  ) -> Sequence[Document]:
      """Compress page content of raw documents."""
      async def _compress_concurrently(doc):
          _input = self.get_input(query, doc)
          output = await self.llm_chain.apredict_and_parse(**_input)
          return Document(page_content=output, metadata=doc.metadata)
      outputs=await asyncio.gather(*[_compress_concurrently(doc) for doc in documents])
      compressed_docs=list(filter(lambda x: len(x.page_content)>0,outputs))
      return compressed_docs
```

But in the end I found the commited version to be better readable and
more "canonical" - hope you agree.
2023-05-01 21:23:13 -07:00
Harrison Chase
2cecc572f9 Harrison/chroma get (#3938)
Co-authored-by: sdan <git@sdan.io>
2023-05-01 21:19:28 -07:00
liviuasnash1
6396a4ad8d Fix documentation typos (#3870)
Co-authored-by: Liviu Asnash <liviua@maximallearning.com>
2023-05-01 20:58:38 -07:00
Hristo Stoychev
109927cdb2 Make project compatible with SQLAlchemy 1.3.* (#3862)
Related to [this
issue.](https://github.com/hwchase17/langchain/issues/3655#issuecomment-1529415363)

The `Mapped` SQLAlchemy class is introduced in SQLAlchemy 1.4 but the
migration from 1.3 to 1.4 is quite challenging so, IMO, it's better to
keep backwards compatibility and not change the SQLAlchemy requirements
just because of type annotations.
2023-05-01 20:58:22 -07:00
sqr
8bbdde8f9e make ARG POETRY_HOME available in multistage (#3882) 2023-05-01 20:57:41 -07:00
玄猫
188a7bd653 fix: pgvector hang risk if table not exist #3883 (#3884) 2023-05-01 20:57:31 -07:00
tomer555
9acf80fd69 fix: invalid escape sequence error in regex pattern (#3902)
This PR fixes the "SyntaxError: invalid escape sequence" error in the
pydantic.py file. The issue was caused by the backslashes in the regular
expression pattern being treated as escape characters. By using a raw
string literal for the regex pattern (e.g., r"\{.*\}"), this fix ensures
that backslashes are treated as literal characters, thus preventing the
error.

Co-authored-by: Tomer Levy <tomer.levy@tipalti.com>
2023-05-01 20:57:19 -07:00
Samuel Dion-Girardeau
c5c33786a7 Fix bad spellings for 'convenience' (#3936)
Found in the docs for chat prompt templates:

https://python.langchain.com/en/latest/getting_started/getting_started.html#chat-prompt-templates

and fixed similar issues in neighboring notebooks.
2023-05-01 20:57:06 -07:00
Harrison Chase
f04faf8496 Harrison/spreedly (#3937)
Co-authored-by: Esmit Pérez <esmitperez@users.noreply.github.com>
2023-05-01 20:56:56 -07:00
Harrison Chase
cd3f8582cb Harrison/combined memory (#3935)
Co-authored-by: engkheng <60956360+outday29@users.noreply.github.com>
2023-05-01 20:55:56 -07:00
Zander Chase
c4cb55a0c5 [Breaking] Migrate GPT4All to use PyGPT4All (#3934)
Seems the pyllamacpp package is no longer the supported bindings from
gpt4all. Tested that this works locally.

Given that the older models weren't very performant, I think it's better
to migrate now without trying to include a lot of try / except blocks

---------

Co-authored-by: Nissan Pow <npow@users.noreply.github.com>
Co-authored-by: Nissan Pow <pownissa@amazon.com>
2023-05-01 20:42:45 -07:00
leo-gan
f0a4bbb8e2 updated YouTube links (#3916)
Added several links to fresh videos

Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-05-01 20:39:59 -07:00
Mike Wang
68a18cc621 [simple] add ddg-search to __init__ for easier loading (#3933)
the same as other tools
2023-05-01 20:39:17 -07:00
Matt Robinson
c51dec5101 feat: add Unstructured API loaders (#3906)
### Summary

Adds `UnstructuredAPIFileLoaders` and `UnstructuredAPIFIleIOLoaders`
that partition documents through the Unstructured API. Defaults to the
URL for hosted Unstructured API, but can switch to a self hosted or
locally running API using the `url` kwarg. Currently, the Unstructured
API is open and does not require an API, but it will soon. A note was
added about that to the Unstructured ecosystem page.

### Testing


```python
from langchain.document_loaders import UnstructuredAPIFileIOLoader

filename = "fake-email.eml"

with open(filename, "rb") as f:
    loader = UnstructuredAPIFileIOLoader(file=f, file_filename=filename)
    docs = loader.load()

docs[0]
```

```python
from langchain.document_loaders import UnstructuredAPIFileLoader

filename = "fake-email.eml"
loader = UnstructuredAPIFileLoader(file_path=filename, mode="elements")
docs = loader.load()

docs[0]
```
2023-05-01 20:37:35 -07:00
Harrison Chase
13269fb583 Harrison/relevancy score (#3907)
Co-authored-by: Ryan Grippeling <R.Grippeling@hotmail.com>
Co-authored-by: Ryan <ryan@webgrip.nl>
Co-authored-by: Zander Chase <130414180+vowelparrot@users.noreply.github.com>
2023-05-01 20:37:24 -07:00
Zander Chase
c582f2e9e3 Add Structure Chat Agent (#3912)
Create a new chat agent that is compatible with the Multi-input tools
2023-05-01 20:34:50 -07:00
Mike Wang
ec21b7126c [agent][property type] Change allowed_tools to Set as Duplicate doesn’t make sense (#3840)
- ActionAgent has a property called, `allowed_tools`, which is declared
as `List`. It stores all provided tools which is available to use during
agent action.
- This collection shouldn’t allow duplicates. The original datatype List
doesn’t make sense. Each tool should be unique. Even when there are
variants (assuming in the future), it would be named differently in
load_tools.


Test:
- confirm the functionality in an example by initializing an agent with
a list of 2 tools and confirm everything works.
```python3
def test_agent_chain_chat_bot():
	from langchain.agents import load_tools
	from langchain.agents import initialize_agent
	from langchain.agents import AgentType
	from langchain.chat_models import ChatOpenAI
	from langchain.llms import OpenAI
	from langchain.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper

	chat = ChatOpenAI(temperature=0)
	llm = OpenAI(temperature=0)
	tools = load_tools(["ddg-search", "llm-math"], llm=llm)

	agent = initialize_agent(tools, chat, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
	agent.run("Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?")
test_agent_chain_chat_bot()
```
Result:
<img width="863" alt="Screenshot 2023-05-01 at 7 58 11 PM"
src="https://user-images.githubusercontent.com/62768671/235572157-0937594c-ddfb-4760-acb2-aea4cacacd89.png">
2023-05-01 20:30:10 -07:00
Harrison Chase
c5cc09d4e3 Harrison/agent exec kwargs (#3917)
Co-authored-by: Zach Schillaci <40636930+zachschillaci27@users.noreply.github.com>
2023-05-01 20:28:43 -07:00
Harrison Chase
05170b6764 Harrison/from documents (#3919)
Co-authored-by: Gabriel Altay <gabriel.altay@gmail.com>
2023-05-01 20:28:14 -07:00
Davis Chase
e7e29f9937 Dev2049/add modern treasury (#3924)
Modified Modern Treasury and Strip slightly so credentials don't have to
be passed in explicitly. Thanks @mattgmarcus for adding Modern Treasury!

---------

Co-authored-by: Matt Marcus <matt.g.marcus@gmail.com>
2023-05-01 20:28:02 -07:00
Davis Chase
5db6b796cf Dev2049/hf emb encode kwargs (#3925)
Thanks @amogkam for the addition! Refactored slightly

---------

Co-authored-by: Amog Kamsetty <amogkam@users.noreply.github.com>
2023-05-01 20:27:41 -07:00
mbchang
ffc87233a1 refactor GymnasiumAgent (#3927)
refactor GymnasiumAgent (for single-agent environments) to be extensible
to PettingZooAgent (multi-agent environments)
2023-05-01 20:25:03 -07:00
mbchang
81601d886c new example: multi-agent simulations with environment (#3928) 2023-05-01 20:24:15 -07:00
Harrison Chase
f7a828685d Harrison/constitutional chain (#3931)
Co-authored-by: Sam Ching <samuel@duolingo.com>
2023-05-01 20:23:16 -07:00
Eduard van Valkenburg
43a0cb4b92 small change to allow powerbi tools to all have single inputs (#3864)
Small change in the tool input so that the single_input_tool function
works against all powerbi tools
2023-05-01 20:22:16 -07:00
Eduard van Valkenburg
c38cafd6c2 Add connection string auth to cosmos (#3867)
Adds a connection string option for the cosmos memory, in case AAD auth
is not enabled on the cosmos instance.
2023-05-01 20:21:46 -07:00
Venelin Valkov
bc7e4d5cd4 Add links to YouTube videos by Venelin Valkov (#3820)
Hi,
I've added links to my YouTube videos on LangChain. Thank you for
making/maintaining LangChain!
Venelin
2023-05-01 20:20:30 -07:00
Rafal Wojdyla
a5a4999fb7 New line should be remove only for the 1st gen embedding models (#3853)
Only 1st generation OpenAI embeddings models are negatively impacted by
new lines.

Context:
https://github.com/openai/openai-python/issues/418#issuecomment-1525939500
2023-05-01 20:09:20 -07:00
Johan Stenberg (MSFT)
6bd367916c Update adding_memory_chain_multiple_inputs.ipynb (#3895)
Fix misleading docs in memory chain example (used the term "outputs"
instead of "inputs")
2023-05-01 19:57:27 -07:00
Zander Chase
9b9b231e10 Update some Tools Docs (#3913)
Haven't gotten to all of them, but this:
- Updates some of the tools notebooks to actually instantiate a tool
(many just show a 'utility' rather than a tool. More changes to come in
separate PR)
- Move the `Tool` and decorator definitions to `langchain/tools/base.py`
(but still export from `langchain.agents`)
- Add scene explain to the load_tools() function
- Add unit tests for public apis for the langchain.tools and langchain.agents modules
2023-05-01 19:07:26 -07:00
Zander Chase
84ea17b786 Move Tool Validation (#3923)
Move tool validation to each implementation of the Agent.

Another alternative would be to adjust the `_validate_tools()` signature
to accept the output parser (and format instructions) and add logic
there. Something like

`parser.outputs_structured_actions(format_instructions)`

But don't think that's needed right now.
2023-05-01 18:44:24 -07:00
Eugene Yurtsev
7cce68a051 Add minimal file system blob loader (#3669)
This adds a minimal file system blob loader.

If looks good, this PR will be merged and a few additional enhancements will be made.
2023-05-01 21:37:26 -04:00
Bank Natchapol
487d4aeebd Motorhead Memory messages come in reversed order. (#3835)
History from Motorhead memory return in reversed order
It should be Human: 1, AI:..., Human: 2, Ai...

```
You are a chatbot having a conversation with a human.
AI: I'm sorry, I'm still not sure what you're trying to communicate. Can you please provide more context or information?
Human: 3
AI: I'm sorry, I'm not sure what you mean by "1" and "2". Could you please clarify your request or question?
Human: 2
AI: Hello, how can I assist you today?
Human: 1
Human: 4
AI:
```

So, i `reversed` the messages before putting in chat_memory.
2023-05-01 17:02:34 -07:00
Davis Chase
900ad106d3 Update google palm model signatures (#3920)
Signatures out of date after callback refactors
2023-05-01 16:19:31 -07:00
sherylZhaoCode
145ff23fb1 correct the llm type of AzureOpenAI (#3721)
The llm type of AzureOpenAI was previously set to default, which is
openai. But since AzureOpenAI has different API from openai, it creates
problems when doing chain saving and loading. This PR corrected the llm
type of AzureOpenAI to "azure"
2023-05-01 15:51:34 -07:00
engkheng
21335d43b2 Minor LLMChain docs correction (#3791)
`LLMChain` run method can take multiple input variables.
2023-05-01 15:50:57 -07:00
Rafal Wojdyla
039b672f46 Fixup OpenAI Embeddings - fix the weighted mean (#3778)
Re: https://github.com/hwchase17/langchain/issues/3777

Copy pasting from the issue:

While working on https://github.com/hwchase17/langchain/issues/3722 I
have noticed that there might be a bug in the current implementation of
the OpenAI length safe embeddings in `_get_len_safe_embeddings`, which
before https://github.com/hwchase17/langchain/issues/3722 was actually
the **default implementation** regardless of the length of the context
(via https://github.com/hwchase17/langchain/pull/2330).

It appears the weights used are constant and the length of the embedding
vector (1536) and NOT the number of tokens in the batch, as in the
reference implementation at
https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb

<hr>

Here's some debug info:

<img width="1094" alt="image"
src="https://user-images.githubusercontent.com/1419010/235286595-a8b55298-7830-45df-b9f7-d2a2ad0356e0.png">

<hr>

We can also validate this against the reference implementation:

<details>

<summary>Reference implementation (click to unroll)</summary>

This implementation is copy pasted from
https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb

```py
import openai
from itertools import islice
import numpy as np
from tenacity import retry, wait_random_exponential, stop_after_attempt, retry_if_not_exception_type


EMBEDDING_MODEL = 'text-embedding-ada-002'
EMBEDDING_CTX_LENGTH = 8191
EMBEDDING_ENCODING = 'cl100k_base'

# let's make sure to not retry on an invalid request, because that is what we want to demonstrate
@retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6), retry=retry_if_not_exception_type(openai.InvalidRequestError))
def get_embedding(text_or_tokens, model=EMBEDDING_MODEL):
    return openai.Embedding.create(input=text_or_tokens, model=model)["data"][0]["embedding"]

def batched(iterable, n):
    """Batch data into tuples of length n. The last batch may be shorter."""
    # batched('ABCDEFG', 3) --> ABC DEF G
    if n < 1:
        raise ValueError('n must be at least one')
    it = iter(iterable)
    while (batch := tuple(islice(it, n))):
        yield batch
        
def chunked_tokens(text, encoding_name, chunk_length):
    encoding = tiktoken.get_encoding(encoding_name)
    tokens = encoding.encode(text)
    chunks_iterator = batched(tokens, chunk_length)
    yield from chunks_iterator


def reference_safe_get_embedding(text, model=EMBEDDING_MODEL, max_tokens=EMBEDDING_CTX_LENGTH, encoding_name=EMBEDDING_ENCODING, average=True):
    chunk_embeddings = []
    chunk_lens = []
    for chunk in chunked_tokens(text, encoding_name=encoding_name, chunk_length=max_tokens):
        chunk_embeddings.append(get_embedding(chunk, model=model))
        chunk_lens.append(len(chunk))

    if average:
        chunk_embeddings = np.average(chunk_embeddings, axis=0, weights=chunk_lens)
        chunk_embeddings = chunk_embeddings / np.linalg.norm(chunk_embeddings)  # normalizes length to 1
        chunk_embeddings = chunk_embeddings.tolist()
    return chunk_embeddings
```

</details>

```py
long_text = 'foo bar' * 5000

reference_safe_get_embedding(long_text, average=True)[:10]

# Here's the first 10 floats from the reference embeddings:
[0.004407593824276758,
 0.0017611146161865465,
 -0.019824815970984996,
 -0.02177626039794025,
 -0.012060967454897886,
 0.0017955296329155309,
 -0.015609168983609643,
 -0.012059823076681351,
 -0.016990468527792825,
 -0.004970484452089445]


# and now langchain implementation
from langchain.embeddings.openai import OpenAIEmbeddings
OpenAIEmbeddings().embed_query(long_text)[:10]

[0.003791506184693747,
 0.0025310066579390025,
 -0.019282322699514628,
 -0.021492679249899803,
 -0.012598522213242891,
 0.0022181168611315662,
 -0.015858940621301307,
 -0.011754004130791204,
 -0.016402944319627515,
 -0.004125287485127554]

# clearly they are different ^
```
2023-05-01 15:47:38 -07:00
Younis Shah
22a1896c30 [docs]: updates connecting_to_a_feature_store.ipynb (#3776)
* fixes `FeastPromptTemplate.format` example to use `driver_id`
2023-05-01 15:45:59 -07:00
Harrison Chase
e28c6403aa Harrison/cohere reranker (#3904) 2023-05-01 15:40:16 -07:00
Zura Isakadze
647bbf61c1 Add SQLiteChatMessageHistory (#3534)
It's based on already existing `PostgresChatMessageHistory`

Use case somewhere in between multiple files and Postgres storage.
2023-05-01 15:40:00 -07:00
James Brotchie
921894960b Add ChatModel, LLM, and Embeddings for Google's PaLM APIs (#3575)
- Add langchain.llms.GooglePalm for text completion,
 - Add langchain.chat_models.ChatGooglePalm for chat completion,
- Add langchain.embeddings.GooglePalmEmbeddings for sentence embeddings,
- Add example field to HumanMessage and AIMessage so that users can feed
in examples into the PaLM Chat API,
 - Add system and unit tests.

Note async completion for the Text API is not yet supported and will be
included in a future PR.

Happy for feedback on any aspect of this PR, especially our choice of
adding an example field to Human and AI Message objects to enable
passing example messages to the API.
2023-05-01 15:23:16 -07:00
Roma
d15f481352 Add unit test to output parsers (#3911)
This pull request adds unit tests for various output parsers
(BooleanOutputParser, CommaSeparatedListOutputParser, and
StructuredOutputParser) to ensure their correct functionality and to
increase code reliability and maintainability. The tests cover both
valid and invalid input cases.

Changes:

Added unit tests for BooleanOutputParser.
Added unit tests for CommaSeparatedListOutputParser.
Added unit tests for StructuredOutputParser.

Testing:

All new unit tests have been executed, and they pass successfully.
The overall test suite has been run, and all tests pass.
Notes:

These tests cover both successful parsing scenarios and error handling
for invalid inputs.
If any new output parsers are added in the future, corresponding unit
tests should also be created to maintain coverage.
2023-05-01 14:53:08 -07:00
Tim Asp
9c89ff8bd9 Increase request_timeout on ChatOpenAI (#3910)
With longer context and completions, gpt-3.5-turbo and, especially,
gpt-4, will more times than not take > 60seconds to respond.

Based on some other discussions, it seems like this is an increasingly
common problem, especially with summarization tasks.
- https://github.com/hwchase17/langchain/issues/3512
- https://github.com/hwchase17/langchain/issues/3005

OpenAI's max 600s timeout seems excessive, so I settled on 120, but I do
run into generations that take >240 seconds when using large prompts and
completions with GPT-4, so maybe 240 would be a better compromise?
2023-05-01 14:51:05 -07:00
Davis Chase
2451310975 Chroma fix mmr (#3897)
Fixes #3628, thanks @derekmoeller for the issue!
2023-05-01 10:47:15 -07:00
mbchang
3e1cb31f63 fix: add import for gymnasium (#3899) 2023-05-01 10:37:25 -07:00
Zander Chase
484707ad29 Add incremental messages token count (#3890) 2023-05-01 10:36:54 -07:00
Davis Chase
52e4fba897 Fix self query pinecone translation (#3892)
Enum to string conversion handled differently between python 3.9 and
3.11, currently breaking in 3.11 (see #3788). Thanks @peter-brady for
catching this!
2023-05-01 10:35:48 -07:00
Jef Packer
47a685adcf count tokens instead of chars in autogpt prompt (#3841)
This looks like a bug. 

Overall by using len instead of token_counter the prompt thinks it has
less context window than it actually does. Because of this it adds fewer
messages. The reduced previous message context makes the agent
repetitive when selecting tasks.
2023-05-01 09:21:42 -07:00
Nikolas Garske
c4d3d74148 Fix typos in arxiv.ipynb (#3887)
Several minor typos in the doc for the arxiv document loaders were
fixed.
2023-05-01 09:17:37 -07:00
Zander Chase
f7cb2af5f4 Export StructuredTool at /tools (#3858) 2023-04-30 19:22:21 -07:00
Ankush Gola
e87f81b3ec add more color to callbacks docs (#3856) 2023-04-30 19:13:01 -07:00
Zander Chase
19912d755e Vwp/arxiv (#3855)
Co-authored-by: Mike Wang <62768671+skcoirz@users.noreply.github.com>
2023-04-30 18:59:22 -07:00
Zander Chase
e17858470c Vwp/multi line input (#3854)
Co-authored-by: Paolo Rechia <paolorechia@gmail.com>
2023-04-30 18:59:11 -07:00
Harrison Chase
c896657d28 bump version to 154 (#3846) 2023-04-30 17:49:58 -07:00
Zander Chase
d7e17fc8fe Deprecate StdInquireTool (#3850)
- Deprecate StdInInquire tool (dup of HumanInputRun)
- Expose missing tools from `langchain.tools`
2023-04-30 16:55:50 -07:00
Zander Chase
b1d69d3e7a Vwp/fix vectorstore typing (#3851)
Co-authored-by: Jay Stakelon <stakes@users.noreply.github.com>
2023-04-30 16:45:10 -07:00
Zander Chase
fbbdf161cd Lambda Tool (#3842)
Co-authored-by: Jason Holtkamp <holtkam2@gmail.com>
2023-04-30 15:15:09 -07:00
Ankush Gola
d3ec00b566 Callbacks Refactor [base] (#3256)
Co-authored-by: Nuno Campos <nuno@boringbits.io>
Co-authored-by: Davis Chase <130488702+dev2049@users.noreply.github.com>
Co-authored-by: Zander Chase <130414180+vowelparrot@users.noreply.github.com>
Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-04-30 11:14:09 -07:00
Zander Chase
18ec22fe56 Remove multi-input tool section (#3810)
Moving to new notebook. Will re-intro w/ new agent
2023-04-29 15:29:08 -07:00
mbchang
adcad98bee fix: fix filepath error in agent simulations docs (#3795) 2023-04-29 11:21:27 -07:00
Harrison Chase
20aad0bed1 stripe docs 2023-04-29 08:16:37 -07:00
Harrison Chase
378f0889eb bump version to 153 (#3774) 2023-04-29 07:31:35 -07:00
Sheldon
399065e858 update zilliz example (#3578)
1. Now the Zilliz example can't connect to Zilliz Cloud, fixed

Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-04-28 22:10:13 -07:00
Harrison Chase
bd7e0a534c Harrison/csv loader (#3771)
Co-authored-by: mrT23 <tal.r@codium.ai>
2023-04-28 21:54:24 -07:00
Harrison Chase
c494ca3ad2 Harrison/doc2txt (#3772)
Co-authored-by: rishni ratnam <rishniratnam@gmail.com>
2023-04-28 21:54:16 -07:00
Mike Wang
ce4fea983b [simple] added test case and improve self class return type annotation (#3773)
a simple follow up of https://github.com/hwchase17/langchain/pull/3748
- added test case
- improve annotation when function return type is class itself.
2023-04-28 21:54:07 -07:00
Harrison Chase
0c0f14407c Harrison/tair (#3770)
Co-authored-by: Seth Huang <848849+seth-hg@users.noreply.github.com>
2023-04-28 21:25:33 -07:00
Aurélien SCHILTZ
502ba6a0be Fix type annotation for SQLDatabaseToolkit.llm (#3581)
Currently `langchain.agents.agent_toolkits.SQLDatabaseToolkit` has a
field `llm` with type `BaseLLM`. This breaks initialization for some
LLMs. For example, trying to use it with GPT4:
```

from langchain.sql_database import SQLDatabase
from langchain.chat_models import ChatOpenAI
from langchain.agents.agent_toolkits import SQLDatabaseToolkit


db = SQLDatabase.from_uri("some_db_uri")
llm = ChatOpenAI(model_name="gpt-4")
toolkit = SQLDatabaseToolkit(db=db, llm=llm)

# pydantic.error_wrappers.ValidationError: 1 validation error for SQLDatabaseToolkit
# llm
#  Can't instantiate abstract class BaseLLM with abstract methods _agenerate, _generate, _llm_type (type=type_error)
```
Seems like much of the rest of the codebase has switched from BaseLLM to
BaseLanguageModel. This PR makes the change for SQLDatabaseToolkit as
well
2023-04-28 21:19:01 -07:00
uyhcire
0a7a2b99b5 Fix Chroma integration failing when there are less than 4 items in the collection (#3674)
The code was failing to decrement the `n_results` kwarg passed to
`query(...)`
2023-04-28 21:18:19 -07:00
Rafal Wojdyla
57e028549a Expose kwargs in LLMChainExtractor.from_llm (#3748)
Re: https://github.com/hwchase17/langchain/issues/3747
2023-04-28 21:18:05 -07:00
Mike Wang
512c24fc9c [annotation improvement] Make AgentType->Class Conversion More Scalable (#3749)
In the current solution, AgentType and AGENT_TO_CLASS are placed in two
separate files and both manually maintained. This might cause
inconsistency when we update either of them.

— latest —
based on the discussion with hwchase17, we don’t know how to further use
the newly introduced AgentTypeConfig type, so it doesn’t make sense yet
to add it. Instead, it’s better to move the dictionary to another file
to keep the loading.py file clear. The consistency is a good point.
Instead of asserting the consistency during linting, we added a unittest
for consistency check. I think it works as auto unittest is triggered
every time with clear failure notice. (well, force push is possible, but
we all know what we are doing, so let’s show trust. :>)

~~This PR includes~~
- ~~Introduced AgentTypeConfig as the source of truth of all AgentType
related meta data.~~
- ~~Each AgentTypeConfig is a annotated class type which can be used for
annotation in other places.~~
- ~~Each AgentTypeConfig can be easily extended when we have more meta
data needs.~~
- ~~Strong assertion to ensure AgentType and AGENT_TO_CLASS are always
consistent.~~
- ~~Made AGENT_TO_CLASS automatically generated.~~

~~Test Plan:~~
- ~~since this change is focusing on annotation, lint is the major test
focus.~~
- ~~lint, format and test passed on local.~~
2023-04-28 21:17:28 -07:00
Harrison Chase
b7ae9f715d Langchain with reddit (#3661) (#3768)
I have added a reddit document loader which fetches the text from the
Posts of Subreddits or Reddit users, using the `praw` Python package. I
have also added an example notebook reddit.ipynb in order to guide users
to use this dataloader.
This code was made in format similar to twiiter document loader. I have
run code formating, linting and also checked the code myself for
different scenarios.

This is my first contribution to an open source project and I am really
excited about this. If you want to suggest some improvements in my code,
I will be happy to do it. :)

Co-authored-by: Taaha Bajwa <taaha.s.bajwa@gmail.com>
2023-04-28 20:59:56 -07:00
Kohei Kumazaki
fa4c35e9e5 Fix encoding issue in WebBaseLoader (#3602)
The character code mismatches occurred when character information was
not included in the response header (In my case, a Japanese web page).
I solved this issue by changing the encoding setting to
apparent_encoding.
2023-04-28 20:56:33 -07:00
Harrison Chase
be7a8e0824 Harrison/redis cache (#3766)
Co-authored-by: Tyler Hutcherson <tyler.hutcherson@redis.com>
2023-04-28 20:47:18 -07:00
Mike Wang
b588446bf9 [simple][test] Added test case for schema.py (#3692)
- added unittest for schema.py covering utility functions and token
counting.
- fixed a nit. based on huggingface doc, the tokenizer model is gpt-2.
[link](https://huggingface.co/transformers/v4.8.2/_modules/transformers/models/gpt2/tokenization_gpt2_fast.html)
- make lint && make format, passed on local
- screenshot of new test running result

<img width="1283" alt="Screenshot 2023-04-27 at 9 51 55 PM"
src="https://user-images.githubusercontent.com/62768671/235057441-c0ac3406-9541-453f-ba14-3ebb08656114.png">
2023-04-28 20:42:24 -07:00
Harrison Chase
15b92d361d Harrison/confluence stuff (#3765)
Co-authored-by: Jelmer Borst <japborst@gmail.com>
2023-04-28 20:19:44 -07:00
SimFG
5998b53596 Use the GPTCache api interface (#3693)
Use the GPTCache api interface to reduce the possibility of
compatibility issues
2023-04-28 20:18:51 -07:00
engkheng
f37a932b24 Improve chat prompt template docs (#3719)
Add a few more explanations and examples.
2023-04-28 20:16:22 -07:00
Robert Perrotta
22770f5202 Make StuffDocumentsChain doc separator configurable (#3718)
This PR makes the `"\n\n"` string with which `StuffDocumentsChain` joins
formatted documents a property so it can be configured. The new
`document_separator` property defaults to `"\n\n"` so the change is
backwards compatible.
2023-04-28 20:14:07 -07:00
Akhil Vempali
64ba24292d fix: 🐛 SQLAlchemy import error (#3716)
During the import of langchain, SQLAlchemy was throeing an errror
`ImportError: cannot import name 'Mapped' from 'sqlalchemy.orm'`. This
is becaue the Mapped name was introduced in v1.4
2023-04-28 20:13:32 -07:00
Jon Saginaw
f8d69e4e52 Enhancement: Blockchain Document Loader with better Metadata support (#3710)
This PR includes some minor alignment updates, including:

- metadata object extended to support contractAddress, blockchainType,
and tokenId
- notebook doc better aligned to standard langchain format
- startToken changed from int to str to support multiple hex value types
on the Alchemy API

The updated metadata will look like the below. It's possible for a
single contractAddress to exist across multiple blockchains (e.g.
Ethereum, Polygon, etc.) so it's important to include the
blockchainType.

```
 metadata = {"source": self.contract_address, 
                      "blockchain": self.blockchainType,
                      "tokenId": tokenId}
```
2023-04-28 20:13:05 -07:00
Davis Chase
220a7076ac Add Mathpix pdf loader (#3727)
Inspo
https://twitter.com/danielgross/status/1651695062307274754?s=46&t=1zHLap5WG4I_kQPPjfW9fA

Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-04-28 20:11:22 -07:00
Rafal Wojdyla
37ed6f2177 Handle length safe embedding only if needed (#3723)
Re: https://github.com/hwchase17/langchain/issues/3722

Copy pasting context from the issue:


1bf1c37c0c/langchain/embeddings/openai.py (L210-L211)

Means that the length safe embedding method is "always" used, initial
implementation https://github.com/hwchase17/langchain/pull/991 has the
`embedding_ctx_length` set to -1 (meaning you had to opt-in for the
length safe method), https://github.com/hwchase17/langchain/pull/2330
changed that to max length of OpenAI embeddings v2, meaning the length
safe method is used at all times.

How about changing that if branch to use length safe method only when
needed, meaning when the text is longer than the max context length?
2023-04-28 20:10:04 -07:00
Harrison Chase
40f6e60e68 Harrison/stripe (#3762)
Co-authored-by: Ismail Pelaseyed <homanp@gmail.com>
2023-04-28 20:03:21 -07:00
Jelmer Borst
8cf2ff0be0 Confluence: Add page status filter for spaces (#3732)
At the moment all content in Confluence is retrieved by default,
including archived content.

Often, this is undesired as the content is not relevant anymore.

**Notes**
Fetching pages by label does not support excluding archived content.
This may lead to unexpected results.
2023-04-28 19:56:53 -07:00
Harrison Chase
7a129ac043 Harrison/pypdf loader (#3764)
Co-authored-by: Felipe Meres <felipe@felipemeres.com>
2023-04-28 19:56:21 -07:00
mbchang
4eefea0fe8 new example: single agent, simulated environment (openai gym) (#3758)
For many applications of LLM agents, the environment is real (internet,
database, REPL, etc). However, we can also define agents to interact in
simulated environments like text-based games. This is an example of how
to create a simple agent-environment interaction loop with
[Gymnasium](https://github.com/Farama-Foundation/Gymnasium) (formerly
[OpenAI Gym](https://github.com/openai/gym)).
2023-04-28 19:52:05 -07:00
0xDTE
6ce34bb4fe Fixing broken document links (#3756)
simple document url fixes. nothing fancy.
2023-04-28 19:51:23 -07:00
Rafal Wojdyla
160bfae93f Add DocstoreFn - lookup doc via arbitrary function (#3760)
This **partially** addresses
https://github.com/hwchase17/langchain/issues/1524, but it's also useful
for some of our use cases.

This `DocstoreFn` allows to lookup a document given a function that
accepts the `search` string without the need to implement a custom
`Docstore`.

This could be useful when:
* you don't want to implement a `Docstore` just to provide a custom
`search`
 * it's expensive to construct an `InMemoryDocstore`/dict
 * you retrieve documents from remote sources
 * you just want to reuse existing objects
2023-04-28 19:50:32 -07:00
Harrison Chase
c55ba43093 Harrison/vespa (#3761)
Co-authored-by: Lester Solbakken <lesters@users.noreply.github.com>
2023-04-28 19:48:43 -07:00
mbchang
ee20b3e0d0 bug fix: initialize the arxivAPIWrapper object (#3733) 2023-04-28 19:35:01 -07:00
leo-gan
e510732ad2 docs: improved vectorstore notebooks (#3724)
- Added links to the vectorstore providers
- Added installation code (it is not clear that we have to go to the
`LangChan Ecosystem` page to get installation instructions.)
2023-04-28 19:26:50 -07:00
BioErrorLog
ad4eae7ef0 Fix linting on the Quickstart Guide sample codes (#3701)
When copying and pasting the sample code from the Quickstart Guide, lint
errors ("missing whitespace around operator") occur."
2023-04-28 17:29:05 -07:00
Zander Chase
a46f1d830e Synchronous Browser (#3745)
Split out sync methods in playwright
2023-04-28 17:09:00 -07:00
Zander Chase
6c2b16e465 Add SceneXplain Tool (#3752) 2023-04-28 17:01:54 -07:00
erwanlc
72c5c15f7f Fix: Updated links for in depth explanation of chain types in the Question Answering notebooks (#3714)
In the notebook question_answering.ipynb
([link](https://github.com/hwchase17/langchain/blob/master/docs/modules/chains/index_examples/question_answering.ipynb)),
and the notebook qa_with_sources.ipynb
([link](https://github.com/hwchase17/langchain/blob/master/docs/modules/chains/index_examples/qa_with_sources.ipynb)),
the first paragraph contains a dead link:

> This notebook walks through how to use LangChain for question
answering over a list of documents. It covers four different types of
chains: stuff, map_reduce, refine, map_rerank. For a more in depth
explanation of what these chain types are, see
[here](32793f94fd/docs/modules/chains/combine_docs.md).

The file combine_docs.md doesn't exist anymore and thus provide 404 -
Page not found.

I updated the links so it redirect to
https://docs.langchain.com/docs/components/chains/index_related_chains
as in the summarize notebook
([link](https://github.com/hwchase17/langchain/blob/master/docs/modules/chains/index_examples/summarize.ipynb))
present in the same folder.
2023-04-28 15:06:46 -07:00
Alan Cha
e3b7a20454 Fix typo (#3728) 2023-04-28 13:01:09 -07:00
Zander Chase
5042bd40d3 Add Shell Tool (#3335)
Create an official bash shell tool to replace the dynamically generated one
2023-04-28 11:10:43 -07:00
Zander Chase
334c162f16 Add Other File Utilities (#3209)
Add other File Utilities, include
- List Directory
- Search for file
- Move
- Copy
- Remove file

Bundle as toolkit
Add a notebook that connects to the Chat Agent, which somewhat supports
multi-arg input tools
Update original read/write files to return the original dir paths and
better handle unsupported file paths.
Add unit tests
2023-04-28 10:53:37 -07:00
Zander Chase
491c27f861 PlayWright Web Browser Toolkit (#3262)
Adds a PlayWright web browser toolkit with the following tools:

- NavigateTool (navigate_browser) - navigate to a URL
- NavigateBackTool (previous_page) - wait for an element to appear
- ClickTool (click_element) - click on an element (specified by
selector)
- ExtractTextTool (extract_text) - use beautiful soup to extract text
from the current web page
- ExtractHyperlinksTool (extract_hyperlinks) - use beautiful soup to
extract hyperlinks from the current web page
- GetElementsTool (get_elements) - select elements by CSS selector
- CurrentPageTool (current_page) - get the current page URL
2023-04-28 10:42:44 -07:00
Zander Chase
da7b51455c Dynamic tool -> single purpose (#3697)
I think the logic of
https://github.com/hwchase17/langchain/pull/3684#pullrequestreview-1405358565
is too confusing.

I prefer this alternative because:
- All `Tool()` implementations by default will be treated the same as
before. No breaking changes.
- Less reliance on pydantic magic
- The decorator (which only is typed as returning a callable) can infer
schema and generate a structured tool
- Either way, the recommended way to create a custom tool is through
inheriting from the base tool
2023-04-28 09:38:41 -07:00
Zach Schillaci
1bf1c37c0c Update VectorDBQA to RetrievalQA in tools (#3698)
Because `VectorDBQA` and `VectorDBQAWithSourcesChain` are deprecated
2023-04-28 07:39:59 -07:00
Harrison Chase
32793f94fd bump version to 152 (#3695) 2023-04-28 00:21:53 -07:00
mbchang
1da3ee1386 Multiagent authoritarian (#3686)
This notebook showcases how to implement a multi-agent simulation where
a privileged agent decides who to speak.
This follows the polar opposite selection scheme as [multi-agent
decentralized speaker
selection](https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html).

We show an example of this approach in the context of a fictitious
simulation of a news network. This example will showcase how we can
implement agents that
- think before speaking
- terminate the conversation
2023-04-27 23:33:29 -07:00
Zander Chase
4654c58f72 Add validation on agent instantiation for multi-input tools (#3681)
Tradeoffs here:
- No lint-time checking for compatibility
- Differs from JS package
- The signature inference, etc. in the base tool isn't simple
- The `args_schema` is optional 

Pros:
- Forwards compatibility retained
- Doesn't break backwards compatibility
- User doesn't have to think about which class to subclass (single base
tool or dynamic `Tool` interface regardless of input)
-  No need to change the load_tools, etc. interfaces

Co-authored-by: Hasan Patel <mangafield@gmail.com>
2023-04-27 15:36:11 -07:00
Davis Chase
212aadd4af Nit: list to sequence (#3678) 2023-04-27 14:41:59 -07:00
Davis Chase
b807a114e4 Add query parsing unit tests (#3672) 2023-04-27 13:42:12 -07:00
Hasan Patel
03c05b15f6 Fixed some typos on deployment.md (#3652)
Fixed typos and added better formatting for easier readability
2023-04-27 13:01:24 -07:00
Zander Chase
1b5721c999 Remove Pexpect Dependency (#3667)
Resolves #3664

Next PR will be to clean up CI to catch this earlier. Triaging this, it
looks like it wasn't caught because pexpect is a `poetry` dependency.

---------

Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-04-27 11:39:01 -07:00
Eugene Yurtsev
708787dddb Blob: Add validator and use future annotations (#3650)
Minor changes to the Blob schema.

---------

Co-authored-by: Zander Chase <130414180+vowelparrot@users.noreply.github.com>
2023-04-27 14:33:59 -04:00
Eugene Yurtsev
c5a4b4fea1 Suppress duckdb warning in unit tests explicitly (#3653)
This catches the warning raised when using duckdb, asserts that it's as expected.

The goal is to resolve all existing warnings to make unit-testing much stricter.
2023-04-27 14:29:41 -04:00
Eugene Yurtsev
2052e70664 Add lazy iteration interface to document loaders (#3659)
Adding a lazy iteration for document loaders.

Following the plan here:
https://github.com/hwchase17/langchain/pull/2833

Keeping the `load` method as is for backwards compatibility. The `load`
returns a materialized list of documents and downstream users may rely on that
fact.

A new method that returns an iterable is introduced for handling lazy
loading.

---------

Co-authored-by: Zander Chase <130414180+vowelparrot@users.noreply.github.com>
2023-04-27 14:29:01 -04:00
Piotr Mardziel
8a54217e7b update example of ConstitutionalChain.from_llm (#3630)
Example code was missing an argument and import. Fixed.
2023-04-27 11:17:31 -07:00
Eugene Yurtsev
e6c8cce050 Add unit-test to catch changes to required deps (#3662)
This adds a unit test that can catch changes to required dependencies
2023-04-27 13:04:17 -04:00
Eugene Yurtsev
055f58960a Fix pytest collection warning (#3651)
Fixes a pytest collection warning because the test class starts with the
prefix "Test"
2023-04-27 09:51:43 -07:00
Harrison Chase
0cf890eed4 bump version to 151 (#3658) 2023-04-27 09:02:39 -07:00
Davis Chase
3b609642ae Self-query with generic query constructor (#3607)
Alternate implementation of #3452 that relies on a generic query
constructor chain and language and then has vector store-specific
translation layer. Still refactoring and updating examples but general
structure is there and seems to work s well as #3452 on exampels

---------

Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-04-27 08:36:00 -07:00
plutopulp
6d6fd1b9e1 Add PipelineAI LLM integration (#3644)
Add PipelineAI LLM integration
2023-04-27 08:22:26 -07:00
Harrison Chase
a35bbbfa9e Harrison/lancedb (#3634)
Co-authored-by: Minh Le <minhle@canva.com>
2023-04-27 08:14:36 -07:00
Nuno Campos
52b5290810 Update README.md (#3643) 2023-04-27 08:14:09 -07:00
Eugene Yurtsev
5d02010763 Introduce Blob and Blob Loader interface (#3603)
This PR introduces a Blob data type and a Blob loader interface.

This is the first of a sequence of PRs that follows this proposal: 

https://github.com/hwchase17/langchain/pull/2833

The primary goals of these abstraction are:

* Decouple content loading from content parsing code.
* Help duplicated content loading code from document loaders.
* Make lazy loading a default for langchain.
2023-04-27 09:45:25 -04:00
Matt Robinson
8e10ac422e enhancement: add elements mode to UnstructuredURLLoader (#3456)
### Summary

Updates the `UnstructuredURLLoader` to include a "elements" mode that
retains additional metadata from `unstructured`. This makes
`UnstructuredURLLoader` consistent with other unstructured loaders,
which also support "elements" mode. Patched mode into the existing
`UnstructuredURLLoader` class instead of inheriting from
`UnstructuredBaseLoader` because it significantly simplified the
implementation.

### Testing

This should still work and show the url in the source for the metadata

```python
from langchain.document_loaders import UnstructuredURLLoader

urls = ["https://www.understandingwar.org/sites/default/files/Russian%20Offensive%20Campaign%20Assessment%2C%20April%2011%2C%202023.pdf"]

loader = UnstructuredURLLoader(urls=urls, headers={"Accept": "application/json"}, strategy="fast")
docs = loader.load()
print(docs[0].page_content[:1000])
docs[0].metadata
``` 

This should now work and show additional metadata from `unstructured`.

This should still work and show the url in the source for the metadata

```python
from langchain.document_loaders import UnstructuredURLLoader

urls = ["https://www.understandingwar.org/sites/default/files/Russian%20Offensive%20Campaign%20Assessment%2C%20April%2011%2C%202023.pdf"]

loader = UnstructuredURLLoader(urls=urls, headers={"Accept": "application/json"}, strategy="fast", mode="elements")
docs = loader.load()
print(docs[0].page_content[:1000])
docs[0].metadata
```
2023-04-26 22:09:45 -07:00
Eduard van Valkenburg
a3e3f26090 Some more PowerBI pydantic and import fixes (#3461) 2023-04-26 22:09:12 -07:00
Harrison Chase
ab749fa1bb Harrison/opensearch logic (#3631)
Co-authored-by: engineer-matsuo <95115586+engineer-matsuo@users.noreply.github.com>
2023-04-26 22:08:03 -07:00
ccw630
cf384dcb7f Supports async in SequentialChain/SimpleSequentialChain (#3503) 2023-04-26 22:07:20 -07:00
Ehsan M. Kermani
4a246e2fd6 Allow clearing cache and fix gptcache (#3493)
This PR

* Adds `clear` method for `BaseCache` and implements it for various
caches
* Adds the default `init_func=None` and fixes gptcache integtest
* Since right now integtest is not running in CI, I've verified the
changes by running `docs/modules/models/llms/examples/llm_caching.ipynb`
(until proper e2e integtest is done in CI)
2023-04-26 22:03:50 -07:00
Howard Su
83e871f1ff Fix Invalid Request using AzureOpenAI (#3522)
This fixes the error when calling AzureOpenAI of gpt-35-turbo model.

The error is:
InvalidRequestError: logprobs, best_of and echo parameters are not
available on gpt-35-turbo model. Please remove the parameter and try
again. For more details, see
https://go.microsoft.com/fwlink/?linkid=2227346.
2023-04-26 22:00:09 -07:00
Luoyger
f5aa767ef1 add --no-sandbox for chrome in url_selenium (#3589)
without --no-sandbox param, load documents from url by selenium in
chrome occured error below:

```Traceback (most recent call last):
  File "/data//playgroud/try_langchain.py", line 343, in <module>
    langchain_doc_loader()
  File "/data//playgroud/try_langchain.py", line 67, in langchain_doc_loader
    documents = loader.load()
  File "/install/anaconda3-env/envs/python3.10/lib/python3.10/site-packages/langchain/document_loaders/url_selenium.py", line 102, in load
    driver = self._get_driver()
  File "/install/anaconda3-env/envs/python3.10/lib/python3.10/site-packages/langchain/document_loaders/url_selenium.py", line 76, in _get_driver
    return Chrome(options=chrome_options)
  File "/install/anaconda3-env/envs/python3.10/lib/python3.10/site-packages/selenium/webdriver/chrome/webdriver.py", line 80, in __init__
    super().__init__(
  File "/install/anaconda3-env/envs/python3.10/lib/python3.10/site-packages/selenium/webdriver/chromium/webdriver.py", line 104, in __init__
    super().__init__(
  File "/install/anaconda3-env/envs/python3.10/lib/python3.10/site-packages/selenium/webdriver/remote/webdriver.py", line 286, in __init__
    self.start_session(capabilities, browser_profile)
  File "/install/anaconda3-env/envs/python3.10/lib/python3.10/site-packages/selenium/webdriver/remote/webdriver.py", line 378, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/install/anaconda3-env/envs/python3.10/lib/python3.10/site-packages/selenium/webdriver/remote/webdriver.py", line 440, in execute
    self.error_handler.check_response(response)
  File "/install/anaconda3-env/envs/python3.10/lib/python3.10/site-packages/selenium/webdriver/remote/errorhandler.py", line 245, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Stacktrace:
#0 0x55cf8da1bfe3 <unknown>
#1 0x55cf8d75ad36 <unknown>
#2 0x55cf8d783b20 <unknown>
#3 0x55cf8d77fa9b <unknown>
#4 0x55cf8d7c1af7 <unknown>
#5 0x55cf8d7c111f <unknown>
#6 0x55cf8d7b8693 <unknown>
#7 0x55cf8d78b03a <unknown>
#8 0x55cf8d78c17e <unknown>
#9 0x55cf8d9dddbd <unknown>
#10 0x55cf8d9e1c6c <unknown>
#11 0x55cf8d9eb4b0 <unknown>
#12 0x55cf8d9e2d63 <unknown>
#13 0x55cf8d9b5c35 <unknown>
#14 0x55cf8da06138 <unknown>
#15 0x55cf8da062c7 <unknown>
#16 0x55cf8da14093 <unknown>
#17 0x7f3da31a72de start_thread
```

add option `chrome_options.add_argument("--no-sandbox")` for chrome.
2023-04-26 21:48:43 -07:00
Shukri
fac4f36a87 Update models used for embeddings in the weaviate example (#3594)
Use text-embedding-ada-002 because it [outperforms all other
models](https://openai.com/blog/new-and-improved-embedding-model).
2023-04-26 21:48:08 -07:00
cs0lar
440c98e24b Fix/issue 2695 (#3608)
## Background
fixes #2695  

## Changes
The `add_text` method uses the internal embedding function if one was
passes to the `Weaviate` constructor.
NOTE: the latest merge on the `Weaviate` class made the specification of
a `weaviate_api_key` mandatory which might not be desirable for all
users and connection methods (for example weaviate also support Embedded
Weaviate which I am happy to add support to here if people think it's
desirable). I wrapped the fetching of the api key into a try catch in
order to allow the `weaviate_api_key` to be unspecified. Do let me know
if this is unsatisfactory.

## Test Plan
added test for `add_texts` method.
2023-04-26 21:45:03 -07:00
brian-tecton-ai
615812581e Add Tecton example to the "Connecting to a Feature Store" example notebook (#3626)
This PR adds a similar example to the Feast example, using the [Tecton
Feature Platform](https://www.tecton.ai/) and features from the [Tecton
Fundamentals
Tutorial](https://docs.tecton.ai/docs/tutorials/tecton-fundamentals).
2023-04-26 21:38:50 -07:00
mbchang
3b7d27d39e new example: multiagent dialogue with decentralized speaker selection (#3629)
This notebook showcases how to implement a multi-agent simulation
without a fixed schedule for who speaks when. Instead the agents decide
for themselves who speaks. We can implement this by having each agent
bid to speak. Whichever agent's bid is the highest gets to speak.

We will show how to do this in the example below that showcases a
fictitious presidential debate.
2023-04-26 21:37:36 -07:00
leo-gan
36c59e0c25 Arxiv document loader (#3627)
It makes sense to use `arxiv` as another source of the documents for
downloading.
- Added the `arxiv` document_loader, based on the
`utilities/arxiv.py:ArxivAPIWrapper`
- added tests
- added an example notebook
- sorted `__all__` in `__init__.py` (otherwise it is hard to find a
class in the very long list)
2023-04-26 21:04:56 -07:00
Tim Asp
539142f8d5 Add way to get serpapi results async (#3604)
Sometimes it's nice to get the raw results from serpapi, and we're
missing the async version of this function.
2023-04-26 16:37:03 -07:00
Zander Chase
443a893ffd Align names of search tools (#3620)
Tools for Bing, DDG and Google weren't consistent even though the
underlying implementations were.
All three services now have the same tools and implementations to easily
switch and experiment when building chains.
2023-04-26 16:21:34 -07:00
Maciej Bryński
aa345a4bb7 Add get_text_separator parameter to BSHTMLLoader (#3551)
By default get_text doesn't separate content of different HTML tag.
Adding option for specifying separator helps with document splitting.
2023-04-26 16:10:16 -07:00
Bhupendra Aole
568c4f0d81 Close dataframe column names are being treated as one by the LLM (#3611)
We are sending sample dataframe to LLM with df.head().
If the column names are close by, LLM treats two columns names as one,
returning incorrect results.


![image](https://user-images.githubusercontent.com/4707543/234678692-97851fa0-9e12-44db-92ec-9ad9f3545ae2.png)

In the above case the LLM uses **Org Week** as the column name instead
of **Week** if asked about a specific week.

Returning head() as a markdown separates out the columns names and thus
using correct column name.


![image](https://user-images.githubusercontent.com/4707543/234678945-c6d7b218-143e-4e70-9e17-77dc64841a49.png)
2023-04-26 16:05:53 -07:00
James O'Dwyer
860fa59cd3 add metal to ecosystem (#3613) 2023-04-26 15:57:48 -07:00
Zander Chase
ee670c448e Persistent Bash Shell (#3580)
Clean up linting and make more idiomatic by using an output parser

---------

Co-authored-by: FergusFettes <fergusfettes@gmail.com>
2023-04-26 15:20:28 -07:00
Ilyes Bouchada
c5451f4298 Update docker-compose.yaml (#3582)
The following error gets returned when trying to launch
langchain-server:

ERROR: The Compose file
'/opt/homebrew/lib/python3.11/site-packages/langchain/docker-compose.yaml'
is invalid because:
services.langchain-db.expose is invalid: should be of the format
'PORT[/PROTOCOL]'

Solution:
Change line 28 from - 5432:5432 to - 5432
2023-04-26 15:11:59 -07:00
Kátia Nakamura
e1a4fc55e6 Add docs for Fly.io deployment (#3584)
A minimal example of how to deploy LangChain to Fly.io using Flask.
2023-04-26 14:41:08 -07:00
Chirag Bhatia
08478deec5 Fixed typo for HuggingFaceHub (#3612)
The current text has a typo. This PR contains the corrected spelling for
HuggingFaceHub
2023-04-26 14:33:31 -07:00
Charlie Holtz
246710def9 Fix Replicate llm response to handle iterator / multiple outputs (#3614)
One of our users noticed a bug when calling streaming models. This is
because those models return an iterator. So, I've updated the Replicate
`_call` code to join together the output. The other advantage of this
fix is that if you requested multiple outputs you would get them all –
previously I was just returning output[0].

I also adjusted the demo docs to use dolly, because we're featuring that
model right now and it's always hot, so people won't have to wait for
the model to boot up.

The error that this fixes:
```
> llm = Replicate(model=“replicate/flan-t5-xl:eec2f71c986dfa3b7a5d842d22e1130550f015720966bec48beaae059b19ef4c”)
>  llm(“hello”)
> Traceback (most recent call last):
  File "/Users/charlieholtz/workspace/dev/python/main.py", line 15, in <module>
    print(llm(prompt))
  File "/opt/homebrew/lib/python3.10/site-packages/langchain/llms/base.py", line 246, in __call__
    return self.generate([prompt], stop=stop).generations[0][0].text
  File "/opt/homebrew/lib/python3.10/site-packages/langchain/llms/base.py", line 140, in generate
    raise e
  File "/opt/homebrew/lib/python3.10/site-packages/langchain/llms/base.py", line 137, in generate
    output = self._generate(prompts, stop=stop)
  File "/opt/homebrew/lib/python3.10/site-packages/langchain/llms/base.py", line 324, in _generate
    text = self._call(prompt, stop=stop)
  File "/opt/homebrew/lib/python3.10/site-packages/langchain/llms/replicate.py", line 108, in _call
    return outputs[0]
TypeError: 'generator' object is not subscriptable
```
2023-04-26 14:26:33 -07:00
Harrison Chase
7536912125 bump ver 150 (#3599) 2023-04-26 08:29:09 -07:00
Chirag Bhatia
f174aa7712 Fix broken Cerebrium link in documentation (#3554)
The current hyperlink has a typo. This PR contains the corrected
hyperlink to Cerebrium docs
2023-04-26 08:11:58 -07:00
Harrison Chase
d880775e5d Harrison/plugnplai (#3573)
Co-authored-by: Eduardo Reis <edu.pontes@gmail.com>
2023-04-26 08:09:34 -07:00
Zander Chase
85dae78548 Confluence beautifulsoup (#3576)
Co-authored-by: Theau Heral <theau.heral@ln.email.gs.com>
2023-04-25 23:40:06 -07:00
Mike Wang
64501329ab [simple] updated annotation in load_tools.py (#3544)
- added a few missing annotation for complex local variables.
- auto formatted.
- I also went through all other files in agent directory. no seeing any
other missing piece. (there are several prompt strings not annotated,
but I think it’s trivial. Also adding annotation will make it harder to
read in terms of indents.) Anyway, I think this is the last PR in
agent/annotation.
2023-04-25 23:30:49 -07:00
Zander Chase
d6d697a41b Sentence Transformers Aliasing (#3541)
The sentence transformers was a dup of the HF one. 

This is a breaking change (model_name vs. model) for anyone using
`SentenceTransformerEmbeddings(model="some/nondefault/model")`, but
since it was landed only this week it seems better to do this now rather
than doing a wrapper.
2023-04-25 23:29:20 -07:00
Eric Peter
603ea75bcd Fix docs error for google drive loader (#3574) 2023-04-25 22:52:59 -07:00
CG80499
cfd34e268e Add ReAct eval chain (#3161)
- Adds GPT-4 eval chain for arbitrary agents using any set of tools
- Adds notebook

---------

Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-04-25 21:22:25 -07:00
mbchang
4bc209c6f7 example: multi player dnd (#3560)
This notebook shows how the DialogueAgent and DialogueSimulator class
make it easy to extend the [Two-Player Dungeons & Dragons
example](https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html)
to multiple players.

The main difference between simulating two players and multiple players
is in revising the schedule for when each agent speaks

To this end, we augment DialogueSimulator to take in a custom function
that determines the schedule of which agent speaks. In the example
below, each character speaks in round-robin fashion, with the
storyteller interleaved between each player.
2023-04-25 21:20:39 -07:00
James Brotchie
5fdaa95e06 Strip surrounding quotes from requests tool URLs. (#3563)
Often an LLM will output a requests tool input argument surrounded by
single quotes. This triggers an exception in the requests library. Here,
we add a simple clean url function that strips any leading and trailing
single and double quotes before passing the URL to the underlying
requests library.

Co-authored-by: James Brotchie <brotchie@google.com>
2023-04-25 21:20:26 -07:00
Harrison Chase
f4829025fe add feast nb (#3565) 2023-04-25 17:46:06 -07:00
Harrison Chase
47da5f0e58 Harrison/streamlit handler (#3564)
Co-authored-by: kurupapi <37198601+kurupapi@users.noreply.github.com>
2023-04-25 17:26:30 -07:00
Filip Michalsky
49593a3e41 Notebook example: Context-Aware AI Sales Agent (#3547)
I would like to contribute with a jupyter notebook example
implementation of an AI Sales Agent using `langchain`.

The bot understands the conversation stage (you can define your own
stages fitting your needs)
using two chains:

1. StageAnalyzerChain - takes context and LLM decides what part of sales
conversation is one in
2. SalesConversationChain - generate next message

Schema:

https://images-genai.s3.us-east-1.amazonaws.com/architecture2.png

my original repo: https://github.com/filip-michalsky/SalesGPT

This example creates a sales person named Ted Lasso who is trying to
sell you mattresses.

Happy to update based on your feedback.

Thanks, Filip
https://twitter.com/FilipMichalsky
2023-04-25 16:14:33 -07:00
Harrison Chase
52d95ec47d anthropic docs: deprecated LLM, add chat model (#3549) 2023-04-25 16:11:14 -07:00
mbchang
628e93a9a0 docs: simplification of two agent d&d simulation (#3550)
Simplifies the [Two Agent
D&D](https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html)
example with a cleaner, simpler interface that is extensible for
multiple agents.

`DialogueAgent`:
- `send()`: applies the chatmodel to the message history and returns the
message string
- `receive(name, message)`: adds the `message` spoken by `name` to
message history

The `DialogueSimulator` class takes a list of agents. At each step, it
performs the following:
1. Select the next speaker
2. Calls the next speaker to send a message 
3. Broadcasts the message to all other agents
4. Update the step counter.
The selection of the next speaker can be implemented as any function,
but in this case we simply loop through the agents.
2023-04-25 16:10:32 -07:00
apurvsibal
af7906f100 Update Alchemy Key URL (#3559)
Update Alchemy Key URL in Blockchain Document Loader. I want to say
thank you for the incredible work the LangChain library creators have
done.

I am amazed at how seamlessly the Loader integrates with Ethereum
Mainnet, Ethereum Testnet, Polygon Mainnet, and Polygon Testnet, and I
am excited to see how this technology can be extended in the future.

@hwchase17 - Please let me know if I can improve or if I have missed any
community guidelines in making the edit? Thank you again for your hard
work and dedication to the open source community.
2023-04-25 16:08:42 -07:00
Tiago De Gaspari
4d53cefbe9 Fix agents' notebooks outputs (#3517)
Fix agents' notebooks to make the answer reflect what is being asked by
the user.
2023-04-25 16:06:47 -07:00
engkheng
5680fb6894 Fix typo in Prompts Templates Getting Started page (#3514)
`from_templates` -> `from_template`
2023-04-25 16:05:13 -07:00
Vincent
9e36d7b82c adding add_documents and aadd_documents to class RedisVectorStoreRetriever (#3419)
Ran into this issue In vectorstores/redis.py when trying to use the
AutoGPT agent with redis vector store. The error I received was

`
langchain/experimental/autonomous_agents/autogpt/agent.py", line 134, in
run
    self.memory.add_documents([Document(page_content=memory_to_add)])
AttributeError: 'RedisVectorStoreRetriever' object has no attribute
'add_documents'
`

Added the needed function to the class RedisVectorStoreRetriever which
did not have the functionality like the base VectorStoreRetriever in
vectorstores/base.py that, for example, vectorstores/faiss.py has
2023-04-25 13:53:20 -07:00
Davis Chase
d18b0caf0e Add Anthropic default request timeout (#3540)
thanks @hitflame!

---------

Co-authored-by: Wenqiang Zhao <hitzhaowenqiang@sina.com>
Co-authored-by: delta@com <delta@com>
2023-04-25 11:40:41 -07:00
Zander Chase
b49ee372f1 Change Chain Docs (#3537)
Co-authored-by: engkheng <60956360+outday29@users.noreply.github.com>
2023-04-25 10:51:09 -07:00
Ikko Eltociear Ashimine
cf71b5d396 fix typo in comet_tracking.ipynb (#3505)
intializing -> initializing
2023-04-25 10:50:58 -07:00
Zander Chase
64bbbf2cc2 Add DDG to load_tools (#3535)
Fix linting

---------

Co-authored-by: Mike Wang <62768671+skcoirz@users.noreply.github.com>
2023-04-25 10:40:37 -07:00
Roma
2b4e9a3efa Add unit test for _merge_splits function (#3513)
This commit adds a new unit test for the _merge_splits function in the
text splitter. The new test verifies that the function merges text into
chunks of the correct size and overlap, using a specified separator. The
test passes on the current implementation of the function.
2023-04-25 10:02:59 -07:00
Sami Liedes
61da2bb742 Pandas agent: Pass forward callback manager (#3518)
The Pandas agent fails to pass callback_manager forward, making it
impossible to use custom callbacks with it. Fix that.

Co-authored-by: Sami Liedes <sami.liedes@rocket-science.ch>
2023-04-25 09:58:56 -07:00
mbchang
a08e9a3109 Docs: fix naming typo (#3532) 2023-04-25 09:58:25 -07:00
Harrison Chase
dc2188b36d bump version to 149 (#3530) 2023-04-25 08:43:59 -07:00
mbchang
831ca61481 docs: two_player_dnd docs (#3528) 2023-04-25 08:24:53 -07:00
yakigac
f338d6251c Add a test for cosmos db memory (#3525)
Test for #3434 @eavanvalkenburg 
Initially, I was unaware and had submitted a pull request #3450 for the
same purpose, but I have now repurposed the one I used for that. And it
worked.
2023-04-25 08:10:02 -07:00
leo-gan
6b28cbe058 improved arxiv (#3495)
Improved `arxiv/tool.py` by adding more specific information to the
`description`. It would help with selecting `arxiv` tool between other
tools.
Improved `arxiv.ipynb` with more useful descriptions.
2023-04-25 08:09:17 -07:00
mbchang
29f321046e doc: add two player D&D game (#3476)
In this notebook, we show how we can use concepts from
[CAMEL](https://www.camel-ai.org/) to simulate a role-playing game with
a protagonist and a dungeon master. To simulate this game, we create a
`TwoAgentSimulator` class that coordinates the dialogue between the two
agents.
2023-04-25 08:07:18 -07:00
Harrison Chase
0fc0aa62f2 Harrison/blockchain docloader (#3491)
Co-authored-by: Jon Saginaw <saginawj@users.noreply.github.com>
2023-04-25 08:07:06 -07:00
Harrison Chase
bee59b4689 Updated missing refactor in docs "return_map_steps" (#2956) (#3469)
Minor rename in the documentation that was overlooked when refactoring.

---------

Co-authored-by: Ehmad Zubair <ehmad@cogentlabs.co>
2023-04-24 22:28:47 -07:00
Harrison Chase
707741de58 Harrison/prediction guard (#3490)
Co-authored-by: Daniel Whitenack <whitenack.daniel@gmail.com>
2023-04-24 22:27:22 -07:00
Harrison Chase
7257f9e015 Harrison/tfidf parameters (#3481)
Co-authored-by: pao <go5kuramubon@gmail.com>
Co-authored-by: KyoHattori <kyo.hattori@abejainc.com>
2023-04-24 22:19:58 -07:00
Harrison Chase
eda69b13f3 openai embeddings (#3488) 2023-04-24 22:19:47 -07:00
Harrison Chase
d3ce47414d Harrison/chroma update (#3489)
Co-authored-by: vyeevani <30946190+vyeevani@users.noreply.github.com>
Co-authored-by: Vineeth Yeevani <vineeth.yeevani@gmail.com>
2023-04-24 22:19:36 -07:00
Sami Liedes
c8b70e1c6a langchain-server: Do not expose postgresql port to host (#3431)
Apart from being unnecessary, postgresql is run on its default port,
which means that the langchain-server will fail to start if there is
already a postgresql server running on the host. This is obviously less
than ideal.

(Yeah, I don't understand why "expose" is the syntax that does not
expose the ports to the host...)

Tested by running langchain-server and trying out debugging on a host
that already has postgresql bound to the port 5432.

Co-authored-by: Sami Liedes <sami.liedes@rocket-science.ch>
2023-04-24 22:19:23 -07:00
Harrison Chase
7084d69ea7 Harrison/verbose conv ret (#3492)
Co-authored-by: makretch <max.kretchmer@gmail.com>
2023-04-24 22:16:07 -07:00
Harrison Chase
36a039d017 Harrison/prompt prefix (#3496)
Co-authored-by: Ian <ArGregoryIan@gmail.com>
2023-04-24 22:15:44 -07:00
Harrison Chase
408a0183cd Harrison/weaviate (#3494)
Co-authored-by: Nick Rubell <nick@rubell.com>
2023-04-24 22:15:32 -07:00
Eduard van Valkenburg
ba7a5ac9d7 Azure CosmosDB memory (#3434)
Still needs docs, otherwise works.
2023-04-24 22:15:12 -07:00
Lucas Vieira
e6c1c32aff Support GCS Objects with / in GCS Loaders (#3356)
So, this is basically fixing the same things as #1517 but for GCS.

### Problem
When loading GCS Objects with `/` in the object key (eg.
folder/some-document.txt) using `GCSFileLoader`, the objects are
downloaded into a temporary directory and saved as a file.

This errors out when the parent directory does not exist within the
temporary directory.

### What this pr does
Creates parent directories based on object key.

This also works with deeply nested keys:
folder/subfolder/some-document.txt
2023-04-24 22:05:44 -07:00
Mindaugas Sharskus
a4d85f7fd5 [Fix #3365]: Changed regex to cover new line before action serious (#3367)
Fix for: [Changed regex to cover new line before action
serious.](https://github.com/hwchase17/langchain/issues/3365)
---

This PR fixes the issue where `ValueError: Could not parse LLM output:`
was thrown on seems to be valid input.

Changed regex to cover new lines before action serious (after the
keywords "Action:" and "Action Input:").

regex101: https://regex101.com/r/CXl1kB/1

---------

Co-authored-by: msarskus <msarskus@cisco.com>
2023-04-24 22:05:31 -07:00
Maxwell Mullin
696f840426 GuessedAtParserWarning from RTD document loader documentation example (#3397)
Addresses #3396 by adding 

`features='html.parser'` in example
2023-04-24 21:54:39 -07:00
engkheng
06f6c49e61 Improve llm_chain.ipynb and getting_started.ipynb for chains docs (#3380)
My attempt at improving the `Chain`'s `Getting Started` docs and
`LLMChain` docs. Might need some proof-reading as English is not my
first language.

In LLM examples, I replaced the example use case when a simpler one
(shorter LLM output) to reduce cognitive load.
2023-04-24 21:49:55 -07:00
Zander Chase
b89c258bc5 Add retry logic for ChromaDB (#3372)
Rewrite of #3368

Mainly an issue for when people are just getting started, but still nice
to not throw an error if the number of docs is < k.

Add a little decorator utility to block mutually exclusive keyword
arguments
2023-04-24 21:48:29 -07:00
tkarper
6b49be9951 Add Databutton to list of Deployment options (#3364) 2023-04-24 21:45:38 -07:00
jrhe
980cc41709 Adds progress bar using tqdm to directory_loader (#3349)
Approach copied from `WebBaseLoader`. Assumes the user doesn't have
`tqdm` installed.
2023-04-24 21:42:42 -07:00
killpanda
344e3508b1 bug_fixes: use md5 instead of uuid id generation (#3442)
At present, the method of generating `point` in qdrant is to use random
`uuid`. The problem with this approach is that even documents with the
same content will be inserted repeatedly instead of updated. Using `md5`
as the `ID` of `point` to insert text can achieve true `update or
insert`.

Co-authored-by: mayue <mayue05@qiyi.com>
2023-04-24 21:39:51 -07:00
Jon Luo
b765805964 Support SQLAlchemy 2.0 (#3310)
With https://github.com/executablebooks/jupyter-cache/pull/93 merged and
`MyST-NB` updated, we can now support SQLAlchemy 2. Closes #1766
2023-04-24 21:10:56 -07:00
engkheng
7c2c73af5f Update Getting Started page of Prompt Templates (#3298)
Updated `Getting Started` page of `Prompt Templates` to showcase more
features provided by the class. Might need some proof reading because
apparently English is not my first language.
2023-04-24 21:10:22 -07:00
Hasan Patel
a14d1c02f8 Updated Readme.md (#3477)
Corrected some minor grammar issues, changed infra to infrastructure for
more clarity. Improved readability
2023-04-24 20:11:29 -07:00
Davis Chase
b2564a6391 fix #3884 (#3475)
fixes mar bug #3384
2023-04-24 19:54:15 -07:00
Prakhar Agarwal
53b14de636 pass list of strings to embed method in tf_hub (#3284)
This fixes the below mentioned issue. Instead of simply passing the text
to `tensorflow_hub`, we convert it to a list and then pass it.
https://github.com/hwchase17/langchain/issues/3282

Co-authored-by: Prakhar Agarwal <i.prakhar-agarwal@devrev.ai>
2023-04-24 19:51:53 -07:00
Beau Horenberger
2b9f1cea4e add LoRA loading for the LlamaCpp LLM (#3363)
First PR, let me know if this needs anything like unit tests,
reformatting, etc. Seemed pretty straightforward to implement. Only
hitch was that mmap needs to be disabled when loading LoRAs or else you
segfault.
2023-04-24 18:31:14 -07:00
Ehsan M. Kermani
5d0674fb46 Use a consistent poetry version everywhere (#3250)
Fixes the discrepancy of poetry version in Dockerfile and the GAs
2023-04-24 18:19:51 -07:00
Felipe Lopes
8c56e92566 feat: add private weaviate api_key support on from_texts (#3139)
This PR adds support for providing a Weaviate API Key to the VectorStore
methods `from_documents` and `from_texts`. With this addition, users can
authenticate to Weaviate and make requests to private Weaviate servers
when using these methods.

## Motivation
Currently, LangChain's VectorStore methods do not provide a way to
authenticate to Weaviate. This limits the functionality of the library
and makes it more difficult for users to take advantage of Weaviate's
features.

This PR addresses this issue by adding support for providing a Weaviate
API Key as extra parameter used in the `from_texts` method.

## Contributing Guidelines
I have read the [contributing
guidelines](72b7d76d79/.github/CONTRIBUTING.md)
and the PR code passes the following tests:

- [x] make format
- [x] make lint
- [x] make coverage
- [x] make test
2023-04-24 17:55:34 -07:00
Zzz233
239dc10852 ES similarity_search_with_score() and metadata filter (#3046)
Add similarity_search_with_score() to ElasticVectorSearch, add metadata
filter to both similarity_search() and similarity_search_with_score()
2023-04-24 17:20:08 -07:00
Zander Chase
416f3bdf11 Vwp/alpaca streaming (#3468)
Co-authored-by: Luke Stanley <306671+lukestanley@users.noreply.github.com>
2023-04-24 16:27:51 -07:00
Cao Hoang
26035dfa59 remove default usage of openai model in SQLDatabaseToolkit (#2884)
#2866

This toolkit used openai LLM as the default, which could incurr unwanted
cost.
2023-04-24 16:27:38 -07:00
Harrison Chase
675d86aa11 show how to use memory in convo chain (#3463) 2023-04-24 13:29:51 -07:00
leo-gan
d5086d4760 added integration links to the ecosystem.rst (#3453)
Now it is hard to search for the integration points between
data_loaders, retrievers, tools, etc.
I've placed links to all groups of providers and integrations on the
`ecosystem` page.
So, it is easy to navigate between all integrations from a single
location.
2023-04-24 12:17:44 -07:00
Davis Chase
2cbd41145c Bugfix: Not all combine docs chains takes kwargs prompt (#3462)
Generalize ConversationalRetrievalChain.from_llm kwargs

---------

Co-authored-by: shubham.suneja <shubham.suneja>
2023-04-24 12:13:06 -07:00
cs0lar
3033c6b964 fixes #1214 (#3003)
### Background

Continuing to implement all the interface methods defined by the
`VectorStore` class. This PR pertains to implementation of the
`max_marginal_relevance_search_by_vector` method.

### Changes

- a `max_marginal_relevance_search_by_vector` method implementation has
been added in `weaviate.py`
- tests have been added to the the new method
- vcr cassettes have been added for the weaviate tests

### Test Plan

Added tests for the `max_marginal_relevance_search_by_vector`
implementation

### Change Safety

- [x] I have added tests to cover my changes
2023-04-24 11:50:55 -07:00
Harrison Chase
434d8c4c0e Merge branch 'master' of github.com:hwchase17/langchain 2023-04-24 11:30:14 -07:00
Harrison Chase
bdb5f2f9fb update notebook 2023-04-24 11:30:06 -07:00
Zander Chase
d06d47bc92 LM Requests Wrapper (#3457)
Co-authored-by: jnmarti <88381891+jnmarti@users.noreply.github.com>
2023-04-24 11:12:47 -07:00
Harrison Chase
b64c86a25f bump version to 148 (#3458) 2023-04-24 11:08:32 -07:00
mbchang
82845e3821 add meta-prompt to autonomous agents use cases (#3254)
An implementation of
[meta-prompt](https://noahgoodman.substack.com/p/meta-prompt-a-simple-self-improving),
where the agent modifies its own instructions across episodes with a
user.

![figure](https://substackcdn.com/image/fetch/f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F468217b9-96d9-47c0-a08b-dbf6b21b9f49_492x384.png)
2023-04-24 10:48:38 -07:00
yunfeilu92
77235bbe43 propogate kwargs to cls in OpenSearchVectorSearch (#3416)
kwargs shoud be passed into cls so that opensearch client can be
properly initlized in __init__(). Otherwise logic like below will not
work. as auth will not be passed into __init__

```python
docsearch = OpenSearchVectorSearch.from_documents(docs, embeddings, opensearch_url="http://localhost:9200")

query = "What did the president say about Ketanji Brown Jackson"
docs = docsearch.similarity_search(query)
```

Co-authored-by: EC2 Default User <ec2-user@ip-172-31-28-97.ec2.internal>
2023-04-24 10:43:41 -07:00
Eduard van Valkenburg
46c9636012 small constructor change and updated notebook (#3426)
small change in the pydantic definitions, same api. 

updated notebook with right constructure and added few shot example
2023-04-24 10:42:38 -07:00
Zander Chase
49122a96e7 Structured Tool Bugfixes (#3324)
- Proactively raise error if a tool subclasses BaseTool, defines its
own schema, but fails to add the type-hints
- fix the auto-inferred schema of the decorator to strip the
unneeded virtual kwargs from the schema dict

Helps avoid silent instances of #3297
2023-04-24 09:58:29 -07:00
Bilal Mahmoud
f22b9d0e57 Do not await sync callback managers (#3440)
This fixes a bug in the math LLM, where even the sync manager was
awaited, creating a nasty `RuntimeError`
2023-04-24 09:52:04 -07:00
Dianliang233
0cf934ce7d Fix NoneType has no len() in DDG tool (#3334)
Per
46ac914daa/duckduckgo_search/ddg.py (L109),
ddg function actually returns None when there is no result.
2023-04-23 21:29:49 -07:00
Davit Buniatyan
2c0023393b Deep Lake mini upgrades (#3375)
Improvements
* set default num_workers for ingestion to 0
* upgraded notebooks for avoiding dataset creation ambiguity
* added `force_delete_dataset_by_path`
* bumped deeplake to 3.3.0
* creds arg passing to deeplake object that would allow custom S3

Notes
* please double check if poetry is not messed up (thanks!)

Asks
* Would be great to create a shared slack channel for quick questions

---------

Co-authored-by: Davit Buniatyan <d@activeloop.ai>
2023-04-23 21:23:54 -07:00
Haste171
93d53e417a Update unstructured_file.ipynb (#3377)
Fix typo in docs
2023-04-23 21:22:38 -07:00
张城铭
487a57ffe6 Optimize code (#3412)
Co-authored-by: assert <zhangchengming@kkguan.com>
2023-04-23 21:04:59 -07:00
Zander Chase
3d8243ec95 Catch all exceptions in autogpt (#3413)
Ought to be more autonomous
2023-04-23 20:02:37 -07:00
Zander Chase
738ee56b86 Move Generative Agent definition to Experimental (#3245)
Extending @BeautyyuYanli 's #3220 to move from the notebook

---------

Co-authored-by: BeautyyuYanli <beautyyuyanli@gmail.com>
2023-04-23 18:32:37 -07:00
Zander Chase
20f530e9c5 Add Sentence Transformers Embeddings (#3409)
Add embeddings based on the sentence transformers library.
Add a notebook and integration tests.

Co-authored-by: khimaros <me@khimaros.com>
2023-04-23 18:25:20 -07:00
Zander Chase
73bc70b4fa Update marathon notebook (#3408)
Fixes #3404
2023-04-23 18:14:11 -07:00
Luke Harris
b4de839ed8 Several confluence loader improvements (#3300)
This PR addresses several improvements:

- Previously it was not possible to load spaces of more than 100 pages.
The `limit` was being used both as an overall page limit *and* as a per
request pagination limit. This, in combination with the fact that
atlassian seem to use a server-side hard limit of 100 when page content
is expanded, meant it wasn't possible to download >100 pages. Now
`limit` is used *only* as a per-request pagination limit and `max_pages`
is introduced as the way to limit the total number of pages returned by
the paginator.
- Document metadata now includes `source` (the source url), making it
compatible with `RetrievalQAWithSourcesChain`.
 - It is now possible to include inline and footer comments.
- It is now possible to pass `verify_ssl=False` and other parameters to
the confluence object for use cases that require it.
2023-04-23 15:06:10 -07:00
zz
651cb62556 Add support for wikipedia's lang parameter (#3383)
Allow to hange the language of the wikipedia API being requested.

Co-authored-by: zhuohui <zhuohui@datastory.com.cn>
2023-04-23 15:02:18 -07:00
Johann-Peter Hartmann
199cb855ea Improve youtube loader (#3395)
Small improvements for the YouTube loader: 
a) use the YouTube API permission scope instead of Google Drive 
b) bugfix: allow transcript loading for single videos 
c) an additional parameter "continue_on_failure" for cases when videos
in a playlist do not have transcription enabled.
d) support automated translation for all languages, if available.

---------

Co-authored-by: Johann-Peter Hartmann <johann-peter.hartmann@mayflower.de>
2023-04-23 10:24:41 -07:00
Harrison Chase
e5ffbee5eb Harrison/hf document loader (#3394)
Co-authored-by: Azam Iftikhar <azamiftikhar1000@gmail.com>
2023-04-23 10:17:43 -07:00
Hadi Curtay
acfd11c8e4 Updated incorrect link to Weaviate notebook (#3362)
The detailed walkthrough of the Weaviate wrapper was pointing to the
getting-started notebook. Fixed it to point to the Weaviable notebook in
the examples folder.
2023-04-22 20:47:41 -07:00
Ismail Pelaseyed
b21fe0a18f Add example on deploying LangChain to Cloud Run (#3366)
## Summary

Adds a link to a minimal example of running LangChain on Google Cloud
Run.
2023-04-22 20:09:00 -07:00
Ivan Zatevakhin
77bb6c99f7 llamacpp wrong default value passed for f16_kv (#3320)
Fixes default f16_kv value in llamacpp; corrects incorrect parameter
passed.

See:
ba3959eafd/llama_cpp/llama.py (L33)

Fixes #3241
Fixes #3301
2023-04-22 18:46:55 -07:00
Harrison Chase
3a1bdce3f5 bump version to 147 (#3353) 2023-04-22 09:35:03 -07:00
Harrison Chase
a6664be79c Harrison/myscale (#3352)
Co-authored-by: Fangrui Liu <fangruil@moqi.ai>
Co-authored-by: 刘 方瑞 <fangrui.liu@outlook.com>
Co-authored-by: Fangrui.Liu <fangrui.liu@ubc.ca>
2023-04-22 09:17:38 -07:00
Harrison Chase
6200a2a00e Harrison/error hf (#3348)
Co-authored-by: Rui Melo <44201826+rufimelo99@users.noreply.github.com>
2023-04-22 09:06:36 -07:00
Honkware
a5ad1c270f Add ChatGPT Data Loader (#3336)
This pull request adds a ChatGPT document loader to the document loaders
module in `langchain/document_loaders/chatgpt.py`. Additionally, it
includes an example Jupyter notebook in
`docs/modules/indexes/document_loaders/examples/chatgpt_loader.ipynb`
which uses fake sample data based on the original structure of the
`conversations.json` file.

The following files were added/modified:
- `langchain/document_loaders/__init__.py`
- `langchain/document_loaders/chatgpt.py`
- `docs/modules/indexes/document_loaders/examples/chatgpt_loader.ipynb`
-
`docs/modules/indexes/document_loaders/examples/example_data/fake_conversations.json`

This pull request was made in response to the recent release of ChatGPT
data exports by email:
https://help.openai.com/en/articles/7260999-how-do-i-export-my-chatgpt-history
2023-04-22 09:06:24 -07:00
Zander Chase
61d40ba042 Fix Sagemaker Batch Endpoints (#3249)
Add different typing for @evandiewald 's heplful PR

---------

Co-authored-by: Evan Diewald <evandiewald@gmail.com>
2023-04-22 08:49:51 -07:00
Johann-Peter Hartmann
7e79f8c136 Support recursive sitemaps in SitemapLoader (#3146)
A (very) simple addition to support multiple sitemap urls.

---------

Co-authored-by: Johann-Peter Hartmann <johann-peter.hartmann@mayflower.de>
2023-04-22 08:48:04 -07:00
Filip Haltmayer
215dcc2d26 Refactor Milvus/Zilliz (#3047)
Refactoring milvus/zilliz to clean up and have a more consistent
experience.

Signed-off-by: Filip Haltmayer <filip.haltmayer@zilliz.com>
2023-04-22 08:26:19 -07:00
Harrison Chase
8191c6b81a Harrison/voice assistant (#3347)
Co-authored-by: Jaden <jaden.lorenc@gmail.com>
2023-04-22 08:25:50 -07:00
Richy Wang
88a8f59aa7 Add a full PostgresSQL syntax database 'AnalyticDB' as vector store. (#3135)
Hi there!
I'm excited to open this PR to add support for using a fully Postgres
syntax compatible database 'AnalyticDB' as a vector.
As AnalyticDB has been proved can be used with AutoGPT,
ChatGPT-Retrieve-Plugin, and LLama-Index, I think it is also good for
you.
AnalyticDB is a distributed Alibaba Cloud-Native vector database. It
works better when data comes to large scale. The PR includes:

- [x]  A new memory: AnalyticDBVector
- [x]  A suite of integration tests verifies the AnalyticDB integration

I have read your [contributing
guidelines](72b7d76d79/.github/CONTRIBUTING.md).
And I have passed the tests below
- [x]  make format
- [x]  make lint
- [x]  make coverage
- [x]  make test
2023-04-22 08:25:41 -07:00
Harrison Chase
cc6fe18152 Harrison/power bi (#3205)
Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com>
2023-04-22 08:24:48 -07:00
Daniel Chalef
61e09229c8 args_schema type hint on subclassing (#3323)
per https://github.com/hwchase17/langchain/issues/3297

Co-authored-by: Daniel Chalef <daniel.chalef@private.org>
2023-04-21 15:51:13 -07:00
Zander Chase
05a8aa5447 Fix linting on master (#3327) 2023-04-21 15:49:46 -07:00
Varun Srinivas
d2f922f525 Change in method name for creating an issue on JIRA (#3307)
The awesome JIRA tool created by @zywilliamli calls the `create_issue()`
method to create issues, however, the actual method is `issue_create()`.

Details in the Documentation here:
https://atlassian-python-api.readthedocs.io/jira.html#manage-issues
2023-04-21 13:01:33 -07:00
Davis Chase
e933be9605 Update docs api references (#3315) 2023-04-21 12:21:33 -07:00
Paul Garner
aa9d5707e0 Add PythonLoader which auto-detects encoding of Python files (#3311)
This PR contributes a `PythonLoader`, which inherits from
`TextLoader` but detects and sets the encoding automatically.
2023-04-21 10:47:57 -07:00
Daniel Chalef
1ecbeec24e Fix example match_documents fn table name, grammar (#3294)
ref
https://github.com/hwchase17/langchain/pull/3100#issuecomment-1517086472

Co-authored-by: Daniel Chalef <daniel.chalef@private.org>
2023-04-21 10:21:23 -07:00
Davis Chase
2fd24d31a4 Cleanup integration test dir (#3308) 2023-04-21 09:44:09 -07:00
leo-gan
3bc703b0d6 added links to the important YouTube videos (#3244)
Added links to the important YouTube videos
2023-04-21 01:31:42 -07:00
Sertaç Özercan
1e91266a8a fix: handle youtube TranscriptsDisabled (#3276)
handles error when youtube video has transcripts disabled

```
youtube_transcript_api._errors.TranscriptsDisabled: 
Could not retrieve a transcript for the video https://www.youtube.com/watch?v=<URL> This is most likely caused by:

Subtitles are disabled for this video

If you are sure that the described cause is not responsible for this error and that a transcript should be retrievable, please create an issue at https://github.com/jdepoix/youtube-transcript-api/issues. Please add which version of youtube_transcript_api you are using and provide the information needed to replicate the error. Also make sure that there are no open issues which already describe your problem!
```

Signed-off-by: Sertac Ozercan <sozercan@gmail.com>
2023-04-21 01:27:42 -07:00
Alexandre Pesant
04e1d6c699 Do not print openai settings (#3280)
There's no reason to print these settings like that, it just pollutes
the logs :)
2023-04-21 01:20:17 -07:00
Zander Chase
a71a2c0eb2 Handle null action in AutoGPT Agent (#3274)
Handle the case where the command is `null`
2023-04-20 23:18:46 -07:00
Harrison Chase
bf78200f55 bump version 146 (#3272) 2023-04-20 22:20:43 -07:00
Harrison Chase
87544d2378 gradio tools (#3255) 2023-04-20 22:09:15 -07:00
Naveen Tatikonda
bb6c459f7a OpenSearch: Add Support for Lucene Filter (#3201)
### Description
Add Support for Lucene Filter. When you specify a Lucene filter for a
k-NN search, the Lucene algorithm decides whether to perform an exact
k-NN search with pre-filtering or an approximate search with modified
post-filtering. This filter is supported only for approximate search
with the indexes that are created using `lucene` engine.

OpenSearch Documentation -
https://opensearch.org/docs/latest/search-plugins/knn/filter-search-knn/#lucene-k-nn-filter-implementation

Signed-off-by: Naveen Tatikonda <navtat@amazon.com>
2023-04-20 20:42:53 -07:00
Davis Chase
36720cb57f Hf emb device (#3266)
Make it possible to control the HuggingFaceEmbeddings and HuggingFaceInstructEmbeddings client model kwargs. Additionally, the cache folder was added for HuggingFaceInstructEmbedding as the client inherits from SentenceTransformer (client of HuggingFaceEmbeddings).

It can be useful, especially to control the client device, as it will be defaulted to GPU by sentence_transformers if there is any.

---------

Co-authored-by: Yoann Poupart <66315201+Xmaster6y@users.noreply.github.com>
2023-04-20 20:41:22 -07:00
Zach Jones
d7942a9f19 Fix type annotation for QueryCheckerTool.llm (#3237)
Currently `langchain.tools.sql_database.tool.QueryCheckerTool` has a
field `llm` with type `BaseLLM`. This breaks initialization for some
LLMs. For example, trying to use it with GPT4:

```python
from langchain.sql_database import SQLDatabase
from langchain.chat_models import ChatOpenAI
from langchain.tools.sql_database.tool import QueryCheckerTool


db = SQLDatabase.from_uri("some_db_uri")
llm = ChatOpenAI(model_name="gpt-4")
tool = QueryCheckerTool(db=db, llm=llm)

# pydantic.error_wrappers.ValidationError: 1 validation error for QueryCheckerTool
# llm
#   Can't instantiate abstract class BaseLLM with abstract methods _agenerate, _generate, _llm_type (type=type_error)
```

Seems like much of the rest of the codebase has switched from `BaseLLM`
to `BaseLanguageModel`. This PR makes the change for QueryCheckerTool as
well

Co-authored-by: Zachary Jones <zjones@zetaglobal.com>
2023-04-20 18:50:59 -07:00
Davis Chase
46542dc774 Contextual compression retriever (#2915)
Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-04-20 17:01:14 -07:00
Matt Robinson
3943759a90 feat: add loader for rich text files (#3227)
### Summary

Adds a loader for rich text files. Requires `unstructured>=0.5.12`.

### Testing

The following test uses the example RTF file from the [`unstructured`
repo](https://github.com/Unstructured-IO/unstructured/tree/main/example-docs).

```python
from langchain.document_loaders import UnstructuredRTFLoader

loader = UnstructuredRTFLoader("fake-doc.rtf", mode="elements")
docs = loader.load()
docs[0].page_content
```
2023-04-20 15:51:49 -07:00
Harrison Chase
5ef2d1e2a1 add to docs 2023-04-20 15:43:57 -07:00
Harrison Chase
4aedbeaffb Merge branch 'master' of github.com:hwchase17/langchain 2023-04-20 15:43:04 -07:00
Harrison Chase
2dbb5261b5 wikibase agent 2023-04-20 15:37:56 -07:00
Albert Castellana
0684aa081a Ecosystem/Yeager.ai (#3239)
Added yeagerai.md to ecosystem
2023-04-20 15:20:21 -07:00
Boris Feld
0e797a3ff9 Fixing issue link for Comet callback (#3212)
Sorry I fixed that link once but there was still a typo inside, this
time it should be good.
2023-04-20 14:57:41 -07:00
Daniel Chalef
ae528fd06e fix error msg ref to beautifulsoup4 (#3242)
Co-authored-by: Daniel Chalef <daniel.chalef@private.org>
2023-04-20 14:03:32 -07:00
Tom Dyson
7d3e6389f2 Add DuckDB prompt (#3233)
Adds a prompt template for the DuckDB SQL dialect.
2023-04-20 14:02:20 -07:00
Zander Chase
daee0b2b97 Patch Chat History Formatting (#3236)
While we work on solidifying the memory interfaces, handle common chat
history formats.

This may break linting on anyone who has been passing in
`get_chat_history` .

Somewhat handles #3077

Alternative to #3078 that updates the typing
2023-04-20 13:31:30 -07:00
Harrison Chase
8f22949dc4 update nnotebook title 2023-04-20 11:53:23 -07:00
leo-gan
130e4b9fcb fixed a link to the youtube page (#3232)
A link to the `YouTube` page was missing on the `index` page.
2023-04-20 10:47:16 -07:00
Peter Stolz
d54b977d4e Fix docstring of RetrievalQA (#3231)
Structure changed an RetrievalQA now expects BaseRetriever not
VectorStore
2023-04-20 10:46:51 -07:00
Harrison Chase
b7dea80cba bump version to 145 (#3229) 2023-04-20 08:30:38 -07:00
Harrison Chase
b7f2061736 Harrison/google places (#3207)
Co-authored-by: Cao Hoang <65607230+cnhhoang850@users.noreply.github.com>
Co-authored-by: vowelparrot <130414180+vowelparrot@users.noreply.github.com>
2023-04-20 07:57:07 -07:00
Gabriel Altay
34fb56b633 fix copy/pasta typos wikipedia->arxiv (#3222)
just updates a few module level docstrings from Wikipedia -> Arxiv
2023-04-20 07:15:41 -07:00
Harrison Chase
d2520a5f1e Harrison/ddg (#3206)
Co-authored-by: itai <itai.marks@gmail.com>
Co-authored-by: Itai Marks <itaim@users.noreply.github.com>
Co-authored-by: Tianyi Pan <60060750+tipani86@users.noreply.github.com>
Co-authored-by: Tianyi Pan <tianyi.pan@clobotics.com>
Co-authored-by: Adilzhan Ismailov <13088690+aismlv@users.noreply.github.com>
Co-authored-by: Justin Flick <Justinjayflick@gmail.com>
Co-authored-by: Justin Flick <jflick@homesite.com>
2023-04-19 21:32:26 -07:00
Harrison Chase
36c10f8a52 nits (#3203) 2023-04-19 21:14:46 -07:00
Daniel Chalef
27cdf8d675 supabase vectorstore - first cut (#3100)
First cut of a supabase vectorstore loosely patterned on the langchainjs
equivalent. Doesn't support async operations which is a limitation of
the supabase python client.

---------

Co-authored-by: Daniel Chalef <daniel.chalef@private.org>
2023-04-19 21:06:44 -07:00
Harrison Chase
9a0356d276 Harrison/file chat history (#3198)
Co-authored-by: Young Lee <joybro201@gmail.com>
2023-04-19 21:05:20 -07:00
Kazon Wilson
a66cab8b71 Add new line to refine prompt tmpl (#3197)
Adding a new line to fix issue #3117
2023-04-19 21:04:52 -07:00
Harrison Chase
96809b5794 Harrison/discord loader (#3200)
Co-authored-by: Rajtilak Bhattacharjee <rajtilak.blog@gmail.com>
2023-04-19 21:04:12 -07:00
Justin Flick
8faef1a91a Confluence DL retry/backoff (#3168)
Implemented a retry/backoff logic in response to #2473

---------

Co-authored-by: Justin Flick <jflick@homesite.com>
2023-04-19 20:50:39 -07:00
Adilzhan Ismailov
c03a65c6dc Fix from_embeddings method examples (#3174)
Fix examples for `from_embeddings` method for annoy and faiss
vectorstores
2023-04-19 20:49:33 -07:00
Harrison Chase
f19b3890c9 Harrison/site map tqdm (#3184)
Co-authored-by: Tianyi Pan <60060750+tipani86@users.noreply.github.com>
Co-authored-by: Tianyi Pan <tianyi.pan@clobotics.com>
2023-04-19 20:48:47 -07:00
Harrison Chase
e55db5841a Harrison/svm speedup (#3195)
Co-authored-by: Lance Martin <122662504+PineappleExpress808@users.noreply.github.com>
2023-04-19 20:14:01 -07:00
obbiondo
d6b2f2b9bd add ConfluenceLoader to document_loaders init (#3143)
Fix ConfluenceLoader import

Co-authored-by: Andrea Biondo <a.biondo@reply.it>
2023-04-19 20:05:31 -07:00
Zander Chase
c757c3cde4 Add HuggingFace Examples (#3187)
Add a Pipeline example and add other models in th ehub notebook

To close issue
[#3077](https://github.com/hwchase17/langchain/issues/3099)
2023-04-19 17:08:10 -07:00
Donald "Max" Ziff
6adf2d1c39 first draft (#2690)
There is a long way to go on this!

---------

Co-authored-by: Max Ziff <max.ziff@concur.com>
2023-04-19 17:06:55 -07:00
Harrison Chase
9181cd9b22 Harrison/playwright selector (#3185)
Co-authored-by: zhyuri <4649294+zhyuri@users.noreply.github.com>
2023-04-19 16:54:15 -07:00
Harrison Chase
68cd37175e Harrison/arxiv tool (#3186)
Co-authored-by: leo-gan <leo.gan.57@gmail.com>
2023-04-19 16:53:34 -07:00
Tunay Okumus
6e48107734 fix: separate model and deployment for OpenAIEmbeddings (#3076)
Separated the deployment from model to support Azure OpenAI Embeddings
properly.
Also removed the deprecated document_model_name and query_model_name
attributes.
2023-04-19 16:49:18 -07:00
Zander Chase
4adfd790f0 Update File Management Tools to Include Root Directory (#3112)
- Permit the specification of a `root_dir` to the read/write file tools
to specify a working directory
- Add validation for attempts to read/write outside the directory (e.g.,
through `../../` or symlinks or `/abs/path`'s that don't lie in the
correct path)
- Add some tests for all


One question is whether we should make a default root directory for
these? tradeoffs either way
2023-04-19 16:46:10 -07:00
John-David Wuarin
a63bfb6c9f fix: kwargs.pop("redis_url") KeyError: 'redis_url' (#3121)
This occurred when redis_url was not passed as a parameter even though a
REDIS_URL env variable was present.
This occurred for all methods that eventually called any of:
(from_texts, drop_index, from_existing_index) - i.e. virtually all
methods in the class.
This fixes it
2023-04-19 16:44:39 -07:00
engkheng
dbbc340f25 Validate input_variables when using jinja2 templates (#3140)
`langchain.prompts.PromptTemplate` and
`langchain.prompts.FewShotPromptTemplate` do not validate
`input_variables` when initialized as `jinja2` template.

```python
# Using langchain v0.0.144
template = """"\
Your variable: {{ foo }}
{% if bar %}
You just set bar boolean variable to true
{% endif %}
"""

# Missing variable, should raise ValueError
prompt_template = PromptTemplate(template=template, 
                                 input_variables=["bar"], 
                                 template_format="jinja2", 
                                 validate_template=True)

# Extra variable, should raise ValueError
prompt_template = PromptTemplate(template=template, 
                                 input_variables=["bar", "foo", "extra", "thing"], 
                                 template_format="jinja2", 
                                 validate_template=True)
```
2023-04-19 16:18:32 -07:00
Matt Robinson
3e0c44bae8 enhancement: support headers for non-html urls (#3166)
### Summary

Updates the `UnstructuredURLLoader` to support passing in headers for
non HTML content types. While this update maintains backward
compatibility with older versions of `unstructured`, we strongly
recommended upgrading to `unstructured>=0.5.13` if you are using the
`UnstructuredURLLoader`.

### Testing

#### With headers

```python
from langchain.document_loaders import UnstructuredURLLoader

urls = ["https://www.understandingwar.org/sites/default/files/Russian%20Offensive%20Campaign%20Assessment%2C%20April%2011%2C%202023.pdf"]

loader = UnstructuredURLLoader(urls=urls, headers={"Accept": "application/json"}, strategy="fast")
docs = loader.load()
print(docs[0].page_content[:1000])
```

#### Without headers

```python
from langchain.document_loaders import UnstructuredURLLoader

urls = ["https://www.understandingwar.org/sites/default/files/Russian%20Offensive%20Campaign%20Assessment%2C%20April%2011%2C%202023.pdf"]

loader = UnstructuredURLLoader(urls=urls, strategy="fast")
docs = loader.load()
print(docs[0].page_content[:1000])
```

---------

Co-authored-by: Zander Chase <130414180+vowelparrot@users.noreply.github.com>
2023-04-19 16:16:24 -07:00
Pranabendra Prasad Chandra
7b1f0656b8 Fix typo in ElasticSearch sample notebook (#3171)
Added missing parenthesis in example notebook
[elasticsearch.ipynb](https://github.com/hwchase17/langchain/blob/master/docs/modules/indexes/vectorstores/examples/elasticsearch.ipynb)
2023-04-19 16:06:31 -07:00
Davis Chase
10e4b32ecb Add document transformer abstraction (#3182)
Add DocumentTransformer abstraction so that in #2915 we don't have to
wrap TextSplitter and RedundantEmbeddingFilter (neither of which uses
the query) in the contextual doc compression abstractions. with this
change, doc filter (doc extractor, whatever we call it) would look
something like
```python
class BaseDocumentFilter(BaseDocumentTransformer[_RetrievedDocument], ABC):
  
  @abstractmethod
  def filter(self, documents: List[_RetrievedDocument], query: str) -> List[_RetrievedDocument]:
    ...
  
  def transform_documents(self, documents: List[_RetrievedDocument], query: Optional[str] = None, **kwargs: Any) -> List[_RetrievedDocument]:
    if query is None:
      raise ValueError("Must pass in non-null query to DocumentFilter")
    return self.filter(documents, query)
```
2023-04-19 16:05:05 -07:00
Zander Chase
74342ab209 Update the marathon notebook (#3183)
There were some steps that didn't make sense. Update now. This time it
produced a nice markdown formatted table too
2023-04-19 16:03:21 -07:00
leo-gan
a78f55b851 Additional resources - YouTube (#3180)
Added links to the YouTube tutorials and videos in the `youtube.md`. 
Added link to the ^ in `index.rst`.
2023-04-19 15:16:29 -07:00
det-sys
26c8cd1ea2 Update gallery.rst (#3176)
Add https://anysummary.app to the gallery
2023-04-19 15:06:59 -07:00
Happydog
5e66d05928 Fix: typo in custom_mrkl_agents.ipynb document (#3159)
I have noticed a typo error in the `custom_mrkl_agents.ipynb` document
while trying the example from the documentation page. As a result, I
have opened a pull request (PR) to address this minor issue, even though
it may seem insignificant 😂.
2023-04-19 14:57:33 -07:00
Harrison Chase
99b1983461 add example 2023-04-19 14:35:24 -07:00
Zander Chase
89c63cf8a6 Add Marathon Notebook (#3163)
Add an example using autogpt to get the boston marathon winning times

Add a web browser + summarization tool in the notebook
2023-04-19 11:23:08 -07:00
Dariel Dato-on
0b542661b4 Prevent kwargs from being overwritten (#3158)
Fixes #3157. Prevents `kwargs` from being overwritten by
`_to_args_and_kwargs()` and sending the wrong `kwargs` in line 109.
2023-04-19 09:00:10 -07:00
Quentin Pleplé
126d7f11dd Fix notebook example (#3142)
The following calls were throwing an exception:


575b717d10/docs/use_cases/evaluation/agent_vectordb_sota_pg.ipynb (L192)


575b717d10/docs/use_cases/evaluation/agent_vectordb_sota_pg.ipynb (L239)

Exception:

```
---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
Cell In[14], line 1
----> 1 chain_sota = RetrievalQA.from_chain_type(llm=OpenAI(temperature=0), chain_type="stuff", retriever=vectorstore_sota, input_key="question")

File ~/github/langchain/venv/lib/python3.9/site-packages/langchain/chains/retrieval_qa/base.py:89, in BaseRetrievalQA.from_chain_type(cls, llm, chain_type, chain_type_kwargs, **kwargs)
     85 _chain_type_kwargs = chain_type_kwargs or {}
     86 combine_documents_chain = load_qa_chain(
     87     llm, chain_type=chain_type, **_chain_type_kwargs
     88 )
---> 89 return cls(combine_documents_chain=combine_documents_chain, **kwargs)

File ~/github/langchain/venv/lib/python3.9/site-packages/pydantic/main.py:341, in pydantic.main.BaseModel.__init__()

ValidationError: 1 validation error for RetrievalQA
retriever
  instance of BaseRetriever expected (type=type_error.arbitrary_type; expected_arbitrary_type=BaseRetriever)
```

The vectorstores had to be converted to retrievers:
`vectorstore_sota.as_retriever()` and `vectorstore_pg.as_retriever()`.

The PR also:
- adds the file `paul_graham_essay.txt` referenced by this notebook
- adds to gitignore *.pkl and *.bin files that are generated by this
notebook

Interestingly enough, the performance of the prediction greatly
increased (new version of langchain or ne version of OpenAI models since
the last run of the notebook): from 19/33 correct to 28/33 correct!
2023-04-19 08:55:06 -07:00
Jakub Kukul
599e17cea8 Working example for Anthropic (#3151)
would be great if the provided example worked out of the box 😄
2023-04-19 08:52:33 -07:00
Harrison Chase
575b717d10 bump version to 144 (#3136) 2023-04-18 23:29:23 -07:00
ProxyCausal
72b7d76d79 Print exception type for Python tool (#3126)
Useful for debugging agents e.g. KeyError in addition to just printing
the missing key
2023-04-18 22:45:06 -07:00
Harrison Chase
b7dc04c086 fix links 2023-04-18 22:44:53 -07:00
Zander Chase
8a050ba4bf Notebook Nit (#3125)
The required arg is `question` not `query`
2023-04-18 22:43:52 -07:00
Harrison Chase
364257d967 agent docs fixes (#3128) 2023-04-18 21:54:30 -07:00
Zander Chase
f329196cf4 Agents 4 18 (#3122)
Creating an experimental agents folder, containing BabyAGI, AutoGPT, and
later, other examples

---------

Co-authored-by: Rahul Behal <rahulbehal01@hotmail.com>
Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-04-18 21:41:03 -07:00
engkheng
8e386613ac Import jinja2 only when used (#3123)
Addressing #3113
2023-04-18 21:23:03 -07:00
Zander Chase
90ef705ced Update Tool Input (#3103)
- Remove dynamic model creation in the `args()` property. _Only infer
for the decorator (and add an argument to NOT infer if someone wishes to
only pass as a string)_
- Update the validation example to make it less likely to be
misinterpreted as a "safe" way to run a repl


There is one example of "Multi-argument tools" in the custom_tools.ipynb
from yesterday, but we could add more. The output parsing for the base
MRKL agent hasn't been adapted to handle structured args at this point
in time

---------

Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-04-18 18:18:33 -07:00
Francesco
19116010ee Add exeption for when version metadata cannot be found for package (#3107)
Solves #3097

Already ran tests and lint.
2023-04-18 16:44:40 -07:00
Carmen Sam
d54c88aa21 Add allowed and disallowed special arguments to BaseOpenAI (#3012)
## Background
This PR fixes this error when there are special tokens when querying the
chain:
```
Encountered text corresponding to disallowed special token '<|endofprompt|>'.
If you want this text to be encoded as a special token, pass it to `allowed_special`, e.g. `allowed_special={'<|endofprompt|>', ...}`.
If you want this text to be encoded as normal text, disable the check for this token by passing `disallowed_special=(enc.special_tokens_set - {'<|endofprompt|>'})`.
To disable this check for all special tokens, pass `disallowed_special=()`.
```

Refer to the code snippet below, it breaks in the chain line.
```
        chain = ConversationalRetrievalChain.from_llm(
            ChatOpenAI(openai_api_key=OPENAI_API_KEY),
            retriever=vectorstore.as_retriever(),
            qa_prompt=prompt,
            condense_question_prompt=condense_prompt,
        )
        answer = chain({"question": f"{question}"})
```
However `ChatOpenAI` class is not accepting `allowed_special` and
`disallowed_special` at the moment so they cannot be passed to the
`encode()` in `get_num_tokens` method to avoid the errors.


## Change
- Add `allowed_special` and `disallowed_special` attributes to
`BaseOpenAI` class.
- Pass in `allowed_special` and `disallowed_special` as arguments of
`encode()` in tiktoken.

---------

Co-authored-by: samcarmen <“carmen.samkahman@gmail.com”>
2023-04-18 09:34:08 -07:00
Harrison Chase
9d23cfc7dd bump version to 143 (#3095) 2023-04-18 09:12:57 -07:00
Harrison Chase
aad0a498ac Harrison/output error (#3094)
Co-authored-by: yummydum <sumita@nowcast.co.jp>
2023-04-18 08:59:56 -07:00
Harrison Chase
1c1b77bbfe Harrison/discord (#3092)
Co-authored-by: Rajtilak Bhattacharjee <rajtilak.blog@gmail.com>
2023-04-18 08:19:23 -07:00
Boris Feld
14e4d30659 Comet ml updates 17 04 2023 (#3074)
I made a couple of improvements to the Comet tracker:

* The Comet project name is configurable in various ways (code,
environment variable or file), having a default value in code meant that
users couldn't set the project name in an environment variable or in a
file.
* I added error catching when the `flush_tracker` is called in order to
avoid crashing the whole process. Instead we are gonna display a warning
or error log message (`extra={"show_traceback": True}` is an internal
convention to force the display of the traceback when using our own
logger).

I decided to add the error catching after seeing the following error in
the third example of the notebook:
```
COMET ERROR: Failed to export agent or LLM to Comet
Traceback (most recent call last):
  File "/home/lothiraldan/project/cometml/langchain/langchain/callbacks/comet_ml_callback.py", line 484, in _log_model
    langchain_asset.save(langchain_asset_path)
  File "/home/lothiraldan/project/cometml/langchain/langchain/agents/agent.py", line 591, in save
    raise ValueError(
ValueError: Saving not supported for agent executors. If you are trying to save the agent, please use the `.save_agent(...)`

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/lothiraldan/project/cometml/langchain/langchain/callbacks/comet_ml_callback.py", line 449, in flush_tracker
    self._log_model(langchain_asset)
  File "/home/lothiraldan/project/cometml/langchain/langchain/callbacks/comet_ml_callback.py", line 488, in _log_model
    langchain_asset.save_agent(langchain_asset_path)
  File "/home/lothiraldan/project/cometml/langchain/langchain/agents/agent.py", line 599, in save_agent
    return self.agent.save(file_path)
  File "/home/lothiraldan/project/cometml/langchain/langchain/agents/agent.py", line 145, in save
    agent_dict = self.dict()
  File "/home/lothiraldan/project/cometml/langchain/langchain/agents/agent.py", line 119, in dict
    _dict = super().dict()
  File "pydantic/main.py", line 449, in pydantic.main.BaseModel.dict
  File "pydantic/main.py", line 868, in _iter
  File "pydantic/main.py", line 743, in pydantic.main.BaseModel._get_value
  File "/home/lothiraldan/project/cometml/langchain/langchain/schema.py", line 381, in dict
    output_parser_dict["_type"] = self._type
  File "/home/lothiraldan/project/cometml/langchain/langchain/schema.py", line 376, in _type
    raise NotImplementedError
NotImplementedError
```

I still need to investigate and try to fix it, it looks related to
saving an agent to a file.
2023-04-18 07:32:29 -07:00
engkheng
fe68051d34 Fix typo in docs/reference.rst (#3081)
fix typo
2023-04-18 07:31:00 -07:00
Azam Iftikhar
188e9b9beb Allowing HuggingFaceEmbeddings from the cached weight (#3084)
### https://github.com/hwchase17/langchain/issues/3079
Allow initializing HuggingFaceEmbeddings from the cached weight
2023-04-18 07:30:35 -07:00
Roma
55f6f80a59 fix typo (#3085) 2023-04-18 07:29:33 -07:00
TysBradford
7dae39b57d slightly clearer docs (#3088)
Took me a second to realise the examples required to manually print the
output of the conversation predict. This might make it clearer for
others
2023-04-18 07:28:29 -07:00
James O'Dwyer
0257829776 Bump Metal to use index_id (#3089)
## Use `index_id` over `app_id`
We made a major update to index + retrieve based on Metal Indexes
(instead of apps). With this change, we accept an index instead of an
app in each of our respective core apis. [More details
here](https://docs.getmetal.io/api-reference/core/indexing).
2023-04-18 07:28:13 -07:00
Hamza Kyamanywa
064a1db2b2 [Documentation] Show how to initiate pinecone from an existing index (#3070)
## What is this PR for:
* This PR adds a commented line of code in the documentation that shows
how someone can use the Pinecone client with an already existing
Pinecone index
* The documentation currently only shows how to create a pinecone index
from langchain documents but not how to load one that already exists
2023-04-18 07:27:46 -07:00
Harrison Chase
894c272a56 tool validation logic 2023-04-17 21:59:32 -07:00
Harrison Chase
1920536d99 Harrison/obsidian (#3060)
Co-authored-by: Ben Hofferber <hofferber.ben@gmail.com>
2023-04-17 21:57:32 -07:00
Zander Chase
93c0514105 Add Twitter Tweet Loader (#3050)
Reformatted version of #3022

---------

Co-authored-by: LiaoKong <568250549@qq.com>
2023-04-17 21:44:54 -07:00
__Jay__
2984ad3964 updated llm response parsing action (#3058)
Sometimes the LLM response (generated code) tends to miss the ending
ticks "```". Therefore causing the text parsing to fail due to not
enough values to unpack.

The 2 extra `_` don't add value and can cause errors. Suggest to simply
update the `_, action, _` to just `action` then with index.

Fixes issue #3057
2023-04-17 21:42:13 -07:00
Harrison Chase
db968284f8 tools refactor (#2961)
Co-authored-by: vowelparrot <130414180+vowelparrot@users.noreply.github.com>
2023-04-17 21:35:29 -07:00
Sebastian
7a8c935b90 Edited for better readability (#3059)
It looks like some dropdown functionality was intended, but it caused
the markdown code to glitch which hurt readability.
2023-04-17 21:34:57 -07:00
Matthieu
822cdb161b Adding shared chromaDB client option (#2886)
This pull request addresses the need to share a single `chromadb.Client`
instance across multiple instances of the `Chroma` class. By
implementing a shared client, we can maintain consistency and reduce
resource usage when multiple instances of the `Chroma` classes are
created. This is especially relevant in a web app, where having multiple
`Chroma` instances with a `persist_directory` leads to these clients not
being synced.

This PR implements this option while keeping the rest of the
architecture unchanged.

**Changes:**
1. Add a client attribute to the `Chroma` class to store the shared
`chromadb.Client` instance.
2. Modify the `from_documents` method to accept an optional client
parameter.
3. Update the `from_documents` method to use the shared client if
provided or create a new client if not provided.

Let me know if anything needs to be modified - thanks again for your
work on this incredible repo
2023-04-17 21:22:39 -07:00
Harrison Chase
b140d366e3 Harrison/jira (#3055)
Co-authored-by: William Li <32046231+zywilliamli@users.noreply.github.com>
Co-authored-by: William Li <twelvehertz@Williams-MacBook-Air.local>
2023-04-17 21:14:40 -07:00
Amir Karimi
ae7ed31386 Fix redundancy check about config_type in AGENT_TO_CLASS (#2934)
Fix of issue #2874
2023-04-17 21:05:48 -07:00
J Wynia
b40f90ea04 Spelling to correct conservation to conservation (#3049)
Issue #3048 corrected spelling
2023-04-17 21:03:03 -07:00
leo-gan
c33883a40e fixed the Cohere example title (#3053)
- fixed the Cohere example title (bug in #3041, sorry for it)
- fixed the runhouse.ipynb file name inconsistency
2023-04-17 21:02:52 -07:00
Harrison Chase
5107fac656 Harrison/rec gd (#3054)
Co-authored-by: Benjamin Scholtz <BenSchZA@users.noreply.github.com>
2023-04-17 21:02:35 -07:00
Harrison Chase
eee2f23a79 Harrison/qa eg (#3052)
Co-authored-by: Sukhpal Saini <bdcorps@users.noreply.github.com>
2023-04-17 20:56:42 -07:00
Harrison Chase
db7106cb79 Harrison/image caption loader (#3051)
Co-authored-by: Sean Saito <saitosean@ymail.com>
2023-04-17 20:49:10 -07:00
Benjamin Scholtz
36138f28c8 Add GoogleSQL prompt (#2992)
This PR extends upon @jzluo 's PR #2748 which addressed dialect-specific
issues with SQL prompts, and adds a prompt that uses backticks for
column names when querying BigQuery. See [GoogleSQL quoted
identifiers](https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_identifiers).

Additionally, the SQL agent currently uses a generic prompt. Not sure
how best to adopt the same optional dialect-specific prompts as above,
but will consider making an issue and PR for that too. See
[langchain/agents/agent_toolkits/sql/prompt.py](langchain/agents/agent_toolkits/sql/prompt.py).
2023-04-17 20:44:54 -07:00
Naveen Tatikonda
bb619cd535 Pass kwargs to get OpenSearch client from_texts (#2993)
### Description
Pass kwargs to get OpenSearch client from `from_texts` function

### Issues Resolved
https://github.com/hwchase17/langchain/issues/2819

Signed-off-by: Naveen Tatikonda <navtat@amazon.com>
2023-04-17 20:44:30 -07:00
Harutaka Kawamura
ba9cc230fa Stringify AgentType before saving to yaml (#2998)
Code to reproduce the issue (with `langchain==0.0.141`):

```python
from langchain.agents import initialize_agent, load_tools
from langchain.llms import OpenAI

llm = OpenAI(temperature=0.9, verbose=True)
tools = load_tools(["llm-math"], llm=llm)
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)
agent.save_agent("agent.yaml")
with open("agent.yaml") as f:
    print(f.read())
```

Output:

```
_type: !!python/object/apply:langchain.agents.agent_types.AgentType
- zero-shot-react-description
allowed_tools:
- Calculator
...
```

I expected `_type` to be `zero-shot-react-description` but it's actually
not. This PR fixes it by stringifying `AgentType` (`Enum`).

Signed-off-by: harupy <hkawamura0130@gmail.com>
2023-04-17 20:43:39 -07:00
Nuno Campos
e25528c4f0 Fix incorrect value of outputKeys on AnalyzeDocumentsChain (#3010) 2023-04-17 20:32:46 -07:00
engkheng
19febc77d6 Support inference of input_variables from jinja2 template (#3013)
`langchain.prompts.PromptTemplate` is unable to infer `input_variables`
from jinja2 template.

```python
# Using langchain v0.0.141
template_string = """\
Hello world
Your variable: {{ var }}
{# This will not get rendered #}

{% if verbose %}
Congrats! You just turned on verbose mode and got extra messages!
{% endif %}
"""

template = PromptTemplate.from_template(template_string, template_format="jinja2")
print(template.input_variables) # Output ['# This will not get rendered #', '% endif %', '% if verbose %']
```

---------

Co-authored-by: engkheng <ongengkheng929@example.com>
2023-04-17 20:31:03 -07:00
Nuno Campos
dac32c59e5 Nc/combining output parser (#3014)
Co-authored-by: vowelparrot <130414180+vowelparrot@users.noreply.github.com>
2023-04-17 20:29:53 -07:00
Nuno Campos
79bb5c4f95 Port format instructions fix from js (#3015) 2023-04-17 20:29:17 -07:00
Harrison Chase
e3cf00b88b redis from url (#3024) 2023-04-17 20:28:12 -07:00
Davis Chase
19c85aa990 Factor out doc formatting and add validation (#3026)
@cnhhoang850 slightly more generic fix for #2944, works for whatever the
expected metadata keys are not just `source`
2023-04-17 20:28:01 -07:00
Naveen Tatikonda
3453b7457c OpenSearch: Add Support for Boolean Filter with ANN search (#3038)
### Description
Add Support for Boolean Filter with ANN search
Documentation -
https://opensearch.org/docs/latest/search-plugins/knn/filter-search-knn/#boolean-filter-with-ann-search

### Issues Resolved
https://github.com/hwchase17/langchain/issues/2924

Signed-off-by: Naveen Tatikonda <navtat@amazon.com>
2023-04-17 20:26:26 -07:00
leo-gan
5420a0e404 updated langchain/docs/modules/models/llms/integrations/ notebooks (#3041)
- Updated `langchain/docs/modules/models/llms/integrations/` notebooks:
added links to the original sites, the install information, etc.
- Added the `nlpcloud` notebook.
- Removed "Example" from Titles of some notebooks, so all notebook
titles are consistent.
2023-04-17 20:25:32 -07:00
Azam Iftikhar
471ef84835 Examples fixed (#3042)
### https://github.com/hwchase17/langchain/issues/2997

Replaced `conversation.memory.store` to
`conversation.memory.entity_store.store`
As conversation.memory.store doesn't exist  and re-ran  the whole file.
2023-04-17 20:25:01 -07:00
Tim Asp
dcdcd3f636 bugfix: throw exception if structured output parser doesn't get what it wants (#3044)
allows the user to catch the issue and handle it rather than failing
hard.

This happens more than you'd expect when using output parsers with
chatgpt, especially if the temp is anything but 0. Sometimes it doesn't
want to listen and just does its own thing.
2023-04-17 20:24:40 -07:00
Harrison Chase
afd3e70ae5 Harrison/confluent loader (#2994)
Co-authored-by: Justin Flick <Justinjayflick@gmail.com>
2023-04-17 20:23:45 -07:00
Altay Sansal
95d578d246 Fix type hint regression (#3033)
Not sure what happened here but some of the file got overwritten by
#2859 which broke filtering logic.

Here is it fixed back to normal.

@hwchase17 can we expedite this if possible :-)

---------

Co-authored-by: Altay Sansal <altay.sansal@tgs.com>
2023-04-17 15:49:18 -07:00
Noah Gundotra
577ec92f16 Include testing instructions for getting setup in CONTRIBUTING.md (#3020)
Running tests is good sanity check for new users to ensure their
development environment is setup correctly.
2023-04-17 08:34:07 -07:00
Harrison Chase
98c70bc190 bump version to 142 (#3021) 2023-04-17 08:00:00 -07:00
vowelparrot
2356447323 Update Characters notebook (#3019)
- Most important - fixes the relevance_fn name in the notebook to align
with the docs

- Updates comments for the summary:
<img width="787" alt="image"
src="https://user-images.githubusercontent.com/130414180/232520616-2a99e8c3-a821-40c2-a0d5-3f3ea196c9bb.png">

- The new conversation is a bit better, still unfortunate they try to
schedule a followup.
- Rm the max dialogue turns argument to the conversation function
2023-04-17 07:48:48 -07:00
Harrison Chase
f1d15b4a75 update nb 2023-04-16 22:09:31 -07:00
Harrison Chase
e54f1b69ca add notebook 2023-04-16 21:54:15 -07:00
vowelparrot
99c0382209 Generative Characters (#2859)
Add a time-weighted memory retriever and a notebook that approximates a
Generative Agent from https://arxiv.org/pdf/2304.03442.pdf


The "daily plan" components are removed for now since they are less
useful without a virtual world, but the memory is an interesting
component to build off.

---------

Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-04-16 21:41:00 -07:00
Jan Backes
a9310a3e8b Add Annoy as VectorStore (#2939)
Adds Annoy (https://github.com/spotify/annoy) as vector Store. 

RESOLVES hwchase17/langchain#2842

discord ref:
https://discord.com/channels/1038097195422978059/1051632794427723827/1096089994168377354

---------

Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
Co-authored-by: vowelparrot <130414180+vowelparrot@users.noreply.github.com>
2023-04-16 13:44:04 -07:00
Harrison Chase
e12e00df12 use output parsers in agents (#2987) 2023-04-16 13:15:21 -07:00
cs0lar
8b9e02da9d Fix/issue 1213 (#2932)
### Background

Continuing to implement all the interface methods defined by the
`VectorStore` class. This PR pertains to implementation of the
`max_marginal_relevance_search` method.

### Changes

- a `max_marginal_relevance_search` method implementation has been added
in `weaviate.py`
- tests have been added to the the new method
- vcr cassettes have been added for the weaviate tests

### Test Plan

Added tests for the `max_marginal_relevance_search` implementation

### Change Safety

- [x] I have added tests to cover my changes
2023-04-16 13:11:30 -07:00
Harrison Chase
4c02f4bc30 Fix bug in svm.LinearSVC, add support for a relevancy_threshold (#2959) (#2981)
- Modify SVMRetriever class to add an optional relevancy_threshold
- Modify SVMRetriever.get_relevant_documents method to filter out
documents with similarity scores below the relevancy threshold
- Normalized the similarities to be between 0 and 1 so the
relevancy_threshold makes more sense
- The number of results are limited to the top k documents or the
maximum number of relevant documents above the threshold, whichever is
smaller

This code will now return the top self.k results (or less, if there are
not enough results that meet the self.relevancy_threshold criteria).

The svm.LinearSVC implementation in scikit-learn is non-deterministic,
which means
SVMRetriever.from_texts(["bar", "world", "foo", "hello", "foo bar"])
could return [3 0 5 4 2 1] instead of [0 3 5 4 2 1] with a query of
"foo".
If you pass in multiple "foo" texts, the order could be different each
time. Here, we only care if the 0 is the first element, otherwise it
will offset the text and similarities.


Example:
```python
retriever = SVMRetriever.from_texts(
  ["foo", "bar", "world", "hello", "foo bar"],
  OpenAIEmbeddings(),
  k=4,
  relevancy_threshold=.25
)

result = retriever.get_relevant_documents("foo")
```
yields
```python
[Document(page_content='foo', metadata={}), Document(page_content='foo bar', metadata={})]
```

---------

Co-authored-by: Brandon Sandoval <52767641+account00001@users.noreply.github.com>
2023-04-16 12:57:18 -07:00
Mauricio Scheffer
7302787a7b Fix docs for parse_with_prompt (#2986) 2023-04-16 12:57:04 -07:00
Paul Garner
69698be3e6 consistently use getLogger(__name__), no root logger (#2989)
re
https://github.com/hwchase17/langchain/issues/439#issuecomment-1510442791

I think it's not polite for a library to use the root logger

both of these forms are also used:
```
logger = logging.getLogger(__name__)
logger = logging.getLogger(__file__)
```
I am not sure if there is any reason behind one vs the other? (...I am
guessing maybe just contributed by different people)

it seems to me it'd be better to consistently use
`logging.getLogger(__name__)`

this makes it easier for consumers of the library to set up log
handlers, e.g. for everything with `langchain.` prefix
2023-04-16 12:49:35 -07:00
Harrison Chase
32db2a2c2f fix lint 2023-04-16 10:56:19 -07:00
Azam Iftikhar
1e655d5ffd Fixed Regular expression (#2933)
###  https://github.com/hwchase17/langchain/issues/2898
Instead of `"Action" and "Action Input"` keywords, we are getting
`"Action 1" and "Action 1 Input" or "Action Input 1" ` from
**gpt-3.5-turbo**

 Updated the Regular expression to handle all these cases
 
Attaching the screenshot of the result from the updated Regular
expression.
 
<img width="1036" alt="Screenshot 2023-04-16 at 1 39 00 AM"
src="https://user-images.githubusercontent.com/55012400/232251184-23ca6cc2-7229-411a-b6e1-53b2f5ec18a5.png">
2023-04-16 09:16:50 -07:00
Harrison Chase
88d3ce12b8 Harrison/diffbot (#2984)
Co-authored-by: Manuel Saelices <msaelices@gmail.com>
2023-04-16 09:11:24 -07:00
vowelparrot
5ca7ce77cd Remove pythonrepl from LLM-MathChain (#2943)
Use numexpr evaluate instead of the python REPL to avoid malicious code
injection.

Tested against the (limited) math dataset and got the same score as
before.

For more permissive tools (like the REPL tool itself), other approaches
ought to be provided (some combination of Sanitizer + Restricted python
+ unprivileged-docker + ...), but for a calculator tool, only
mathematical expressions should be permitted.

See https://github.com/hwchase17/langchain/issues/814
2023-04-16 08:50:32 -07:00
Daniel Nouri
2a0f65f7af tiktoken: Relax Python version check (#2966)
tiktoken supports Python >= 3.8, see here:

e1c661edf3/pyproject.toml (L10)

Also works fine when trying locally!
2023-04-16 08:44:21 -07:00
Chetanya Rastogi
aead062a70 Add an example tutorial for using PDFMinerPDFasHTMLLoader (#2960)
Last week I added the `PDFMinerPDFasHTMLLoader`. I am adding some
example code in the notebook to serve as a tutorial for how that loader
can be used to create snippets of a pdf that are structured within
sections. All the other loaders only provide the `Document` objects
segmented by pages but that's pretty loose given the amount of other
metadata that can be extracted.

With the new loader, one can leverage font-size of the text to decide
when a new sections starts and can segment the text more semantically as
shown in the tutorial notebook. The cell shows that we are able to find
the content of entire section under **Related Work** for the example pdf
which is spread across 2 pages and hence is stored as two separate
documents by other loaders
2023-04-16 08:34:39 -07:00
Tim Asp
51894ddd98 allow tokentextsplitters to use model name to select encoder (#2963)
Fixes a bug I was seeing when the `TokenTextSplitter` was correctly
splitting text under the gpt3.5-turbo token limit, but when firing the
prompt off too openai, it'd come back with an error that we were over
the context limit.

gpt3.5-turbo and gpt-4 use `cl100k_base` tokenizer, and so the counts
are just always off with the default `gpt-2` encoder.

It's possible to pass along the encoding to the `TokenTextSplitter`, but
it's much simpler to pass the model name of the LLM. No more concern
about keeping the tokenizer and llm model in sync :)
2023-04-16 08:33:47 -07:00
Alex Iribarren
706ebd8f9c Enforce maximum Wikipedia query length (#2969)
I got the following stacktrace when the agent was trying to search
Wikipedia with a huge query:

```
Thought:{
    "action": "Wikipedia",
    "action_input": "Outstanding is a song originally performed by the Gap Band and written by member Raymond Calhoun. The song originally appeared on the group's platinum-selling 1982 album Gap Band IV. It is one of their signature songs and biggest hits, reaching the number one spot on the U.S. R&B Singles Chart in February 1983.  \"Outstanding\" peaked at number 51 on the Billboard Hot 100."
}
Traceback (most recent call last):
  File "/usr/src/app/tests/chat.py", line 121, in <module>
    answer = agent_chain.run(input=question)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/langchain/chains/base.py", line 216, in run
    return self(kwargs)[self.output_keys[0]]
           ^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/langchain/chains/base.py", line 116, in __call__
    raise e
  File "/usr/local/lib/python3.11/site-packages/langchain/chains/base.py", line 113, in __call__
    outputs = self._call(inputs)
              ^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/langchain/agents/agent.py", line 828, in _call
    next_step_output = self._take_next_step(
                       ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/langchain/agents/agent.py", line 725, in _take_next_step
    observation = tool.run(
                  ^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/langchain/tools/base.py", line 73, in run
    raise e
  File "/usr/local/lib/python3.11/site-packages/langchain/tools/base.py", line 70, in run
    observation = self._run(tool_input)
                  ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/langchain/agents/tools.py", line 17, in _run
    return self.func(tool_input)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/langchain/utilities/wikipedia.py", line 40, in run
    search_results = self.wiki_client.search(query)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/wikipedia/util.py", line 28, in __call__
    ret = self._cache[key] = self.fn(*args, **kwargs)
                             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/wikipedia/wikipedia.py", line 109, in search
    raise WikipediaException(raw_results['error']['info'])
wikipedia.exceptions.WikipediaException: An unknown error occured: "Search request is longer than the maximum allowed length. (Actual: 373; allowed: 300)". Please report it on GitHub!
```

This commit limits the maximum size of the query passed to Wikipedia to
avoid this issue.
2023-04-16 08:30:57 -07:00
Nahin Khan
9a03f00e6c Fix typos (#2977) 2023-04-16 08:28:36 -07:00
Altay Sansal
9d8ab28837 Add top_k and filter fields to ChatGPTPluginRetriever (#2852)
This allows to adjust the number of results to retrieve and filter
documents based on metadata.

---------

Co-authored-by: Altay Sansal <altay.sansal@tgs.com>
2023-04-15 21:07:53 -07:00
vowelparrot
4ffc58e07b Add similarity_search_with_normalized_similarities (#2916)
Add a method that exposes a similarity search with corresponding
normalized similarity scores. Implement only for FAISS now.

### Motivation:

Some memory definitions combine `relevance` with other scores, like
recency , importance, etc.

While many (but not all) of the `VectorStore`'s expose a
`similarity_search_with_score` method, they don't all interpret the
units of that score (depends on the distance metric and whether or not
the the embeddings are normalized).

This PR proposes a `similarity_search_with_normalized_similarities`
method that lets consumers of the vector store not have to worry about
the metric and embedding scale.

*Most providers default to euclidean distance, with Pinecone being one
exception (defaults to cosine _similarity_).*

---------

Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-04-15 21:06:08 -07:00
Tim Asp
b9db20481f Fix wrong token counts from get_num_tokens from openai llms (#2952)
The encoding fetch was out of date. Luckily OpenAI has a nice[
`encoding_for_model`](46287bfa49/tiktoken/model.py)
function in `tiktoken` we can use now.
2023-04-15 16:09:17 -07:00
Tim Asp
fea5619ce9 Add title, lang, description to Web loader document metadata (#2955)
Title, lang and description are on almost every web page, and are
incredibly useful pieces of information that currently isn't captured
with the current web base loader

I thought about adding the title and description to the content of the
document, as
that content could be useful in search, but I left it out for right now.
If you think
it'd be worth adding, happy to add it.


I've found it's nice to have the title/description in the metadata to
have some structured data
when retrieving rows from vectordbs for use with summary and source
citation, so if we do want to add it to the `page_content`, i'd advocate
for it to also be included in metadata.
2023-04-15 16:07:08 -07:00
Maciej Pióro
f7bf917baf Fix missing docker-compose (#2899)
Fix missing `docker-compose` command if only `docker compose` (note
space) is available.
2023-04-15 16:05:11 -07:00
Harrison Chase
b634489b2e bump version to 141 (#2950) 2023-04-15 12:56:39 -07:00
Harrison Chase
274b25c010 SVM retriever (#2947) (#2949)
Add SVM retriever class, based on
https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb.

Testing still WIP, but the logic is correct (I have a local
implementation outside of Langchain working).

---------

Co-authored-by: Lance Martin <122662504+PineappleExpress808@users.noreply.github.com>
Co-authored-by: rlm <31treehaus@31s-MacBook-Pro.local>
2023-04-15 12:49:59 -07:00
Harrison Chase
baf350e32b parametrize redis (#2946) 2023-04-15 12:47:36 -07:00
dev2049
36aa7f30e4 Move PythonRepl -> langchain.utilities (#2917) 2023-04-15 10:50:25 -07:00
dev2049
7c73e9df5d Add kwargs to VectorStore.maximum_marginal_relevance (#2921)
Same as similarity_search, allows child classes to add vector
store-specific args (this was technically already happening in couple
places but now typing is correct).
2023-04-15 10:49:49 -07:00
Davit Buniatyan
b3a5b51728 [minor] Deep Lake auth improvements in docs, kwargs pass, faster tests (#2927)
Minor cosmetic changes 
- Activeloop environment cred authentication in notebooks with
`getpass.getpass` (instead of CLI which not always works)
- much faster tests with Deep Lake pytest mode on 
- Deep Lake kwargs pass

Notes
- I put pytest environment creds inside `vectorstores/conftest.py`, but
feel free to suggest a better location. For context, if I put in
`test_deeplake.py`, `ruff` doesn't let me to set them before import
deeplake

---------

Co-authored-by: Davit Buniatyan <d@activeloop.ai>
2023-04-15 10:49:16 -07:00
Harrison Chase
c4ae8c1d24 bump ver to 140 (#2895) 2023-04-15 09:23:19 -07:00
Nahin Khan
ad3973a3b8 Fix typo (#2942) 2023-04-15 08:53:25 -07:00
Harrison Chase
cf2789d86d delete antropic chat notebook (#2945) 2023-04-15 08:48:51 -07:00
Hai Nguyen Mau
0aa828b1dc typo fix (#2937)
missing w in link
2023-04-15 08:31:43 -07:00
Ankush Gola
ec59e9d886 Fix ChatAnthropic stop_sequences error (#2919) (#2920)
Note to self: Always run integration tests, even on "that last minute
change you thought would be safe" :)

---------

Co-authored-by: Mike Lambert <mike.lambert@anthropic.com>
2023-04-14 17:22:01 -07:00
Akash NP
13a0ed064b add encoding to avoid UnicodeDecodeError (#2908)
**About**
Specify encoding to avoid UnicodeDecodeError when reading .txt for users
who are following the tutorial.

**Reference**
```
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 1205: character maps to <undefined>
```

**Environment**
OS: Win 11
Python: 3.8
2023-04-14 16:36:03 -07:00
Mike Lambert
392f1b3218 Add Anthropic ChatModel to langchain (#2293)
* Adds an Anthropic ChatModel
* Factors out common code in our LLMModel and ChatModel
* Supports streaming llm-tokens to the callbacks on a delta basis (until
a future V2 API does that for us)
* Some fixes
2023-04-14 15:09:07 -07:00
Kwuang Tang
66bef1d7ed Ignore files from .gitignore in Git loader (#2909)
fixes #2905 

extends #2851
2023-04-14 15:02:21 -07:00
Boris Feld
7ee87eb0c8 Comet callback updates (#2889)
I'm working with @DN6 and I made some small fixes and
improvements after playing with the integration.
2023-04-14 13:19:58 -07:00
dev2049
634358db5e Fix OpenAI LLM docstring (#2910) 2023-04-14 11:09:36 -07:00
pranjaldoshi96
30573b2e30 Correct instruction to use openweathermap utility in docstring (#2906)
Co-authored-by: Pranjal Doshi <pranjald@nvidia.com>
2023-04-14 10:46:20 -07:00
Kwuang Tang
a508afa91c Add file filter param to Git loader (#2904)
Allows users to specify what files should be loaded instead of
indiscriminately loading the entire repo.

extends #2851 

NOTE: for reviewers, `hide whitespace` option recommended since I
changed the indentation of an if-block to use `continue` instead so it
looks less like a Christmas tree :)
2023-04-14 10:45:54 -07:00
Ismail Pelaseyed
7e525a3b91 Add link to repo for deploying LangChain to Digitalocean App Platform (#2894)
This PR adds a link to a minimal example of deploying `LangChain` to
`Digitalocean App Platform`.
2023-04-14 08:55:21 -07:00
Peter Stolz
ccacf804a8 Fix format string in pinecone error handling (#2897) 2023-04-14 08:53:02 -07:00
Francis Felici
86189cdcf9 Update load_qa_chain() docstring (#2900)
Seems to be missing `map_rerank` as a potential argument of
`chain_type`
2023-04-14 08:51:30 -07:00
Harrison Chase
8fef69296d nits (#2873) 2023-04-14 07:55:12 -07:00
Harrison Chase
0a38bbc750 updates to vectorstore memory (#2875) 2023-04-14 07:54:57 -07:00
Ikko Eltociear Ashimine
203c0eb2ae docs: update getting_started.ipynb (#2883)
HuggingFace -> Hugging Face
2023-04-14 07:40:26 -07:00
ecneladis
1a44b71ddf Fix Baby AGI notebooks (#2882)
- fix broken notebook cell in
ae485b623d
- Python Black formatting
2023-04-14 07:40:04 -07:00
Nicolas
3c7204d604 docs: Quick fix to Mendable Search (#2876)
Fixed a small issue on the icon UI when using in Safari.
2023-04-13 23:15:57 -07:00
Harrison Chase
1e9378d0a8 Harrison/weaviate fixes (#2872)
Co-authored-by: cs0lar <cristiano.solarino@gmail.com>
Co-authored-by: cs0lar <cristiano.solarino@brightminded.com>
2023-04-13 22:37:34 -07:00
Harrison Chase
07d7096de6 Harrison/playwright (#2871)
Co-authored-by: Manuel Saelices <msaelices@gmail.com>
2023-04-13 22:15:03 -07:00
Jon Luo
5565f56273 Use SQL dialect-specific prompts for SQLDatabaseChain (#2748)
Mentioned the idea here initially:
https://github.com/hwchase17/langchain/pull/2106#issuecomment-1487509106

Since there have been dialect-specific issues, we should use
dialect-specific prompts. This way, each prompt can be separately
modified to best suit each dialect as needed. This adds a prompt for
each dialect supported in sqlalchemy (mssql, mysql, mariadb, postgres,
oracle, sqlite). For this initial implementation, the only differencse
between the prompts is the instruction for the clause to use to limit
the number of rows queried for, and the instruction for wrapping column
names using each dialect's identifier quote character.
2023-04-13 22:10:49 -07:00
drod
9907cb0485 Refactor similarity_search function in elastic_vector_search.py (#2761)
Optimization :Limit search results when k < 10
Fix issue when k > 10: Elasticsearch will return only 10 docs


[default-search-result](https://www.elastic.co/guide/en/elasticsearch/reference/current/paginate-search-results.html)
By default, searches return the top 10 matching hits

Add size parameter to the search request to limit the number of returned
results from Elasticsearch. Remove slicing of the hits list, since the
response will already contain the desired number of results.
2023-04-13 22:09:00 -07:00
rafael
1cc7ea333c chat_models.openai: Set tenacity timeout to openai's recommendation (#2768)
[OpenAI's
cookbook](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb)
suggest a tenacity backoff between 1 and 60 seconds. Currently
langchain's backoff is between 4 and 10 seconds, which causes frequent
timeout errors on my end.

This PR changes the timeout to the suggested values.
2023-04-13 22:08:46 -07:00
Harrison Chase
705596b46a Harrison/fix create sql agent (#2870)
Co-authored-by: Timothé Pearce <timothe.pearce@gmail.com>
2023-04-13 22:07:58 -07:00
Harrison Chase
8a98e5b50b Harrison/index name (#2869)
Co-authored-by: Mesum Raza Hemani <mes.javacca@gmail.com>
2023-04-13 22:01:32 -07:00
Andrey Vasnetsov
dcb17503f2 Update qdrant.py (#2750)
At the moment of upload we should already know the format of data,
therefore we can skip the costly pydantic validation.
2023-04-13 21:57:05 -07:00
ecneladis
74abeb8c53 Update output in Git notebook (#2868)
Supplemental to https://github.com/hwchase17/langchain/pull/2851.
Updates one notebook cell that I forgot to commit before.
2023-04-13 21:56:17 -07:00
Nicolas
0226b375d9 docs: Mendable Search integration (#2803)
Mendable Seach Integration is Finally here!

Hey yall, 

After various requests for Mendable in Python docs, we decided to get
our hands dirty and try to implement it.
Here is a version where we implement our **floating button** that sits
on the bottom right of the screen that once triggered (via press or CMD
K) will work the same as the js langchain docs.

Super excited about this and hopefully the community will be too.
@hwchase17 will send you the admin details via dm etc. The anon_key is
fine to be public.

Let me know if you need any further customization. I added the langchain
logo to it.
2023-04-13 21:52:25 -07:00
sergerdn
04c458a270 feat: improve pinecone tests (#2806)
Improve the integration tests for Pinecone by adding an `.env.example`
file for local testing. Additionally, add some dev dependencies
specifically for integration tests.

This change also helps me understand how Pinecone deals with certain
things, see related issues
https://github.com/hwchase17/langchain/issues/2484
https://github.com/hwchase17/langchain/issues/2816
2023-04-13 21:49:31 -07:00
ecneladis
016738e676 Add GitLoader (#2851) 2023-04-13 21:39:20 -07:00
lizelive
8cfec2c5fe torch 2 support (#2865)
Lang-chain seems to work with torch 2
2023-04-13 21:38:49 -07:00
vowelparrot
bf0887c486 Add Slack Directory Loader (#2841)
Fixes linting issue from #2835 

Adds a loader for Slack Exports which can be a very valuable source of
knowledge to use for internal QA bots and other use cases.

```py
# Export data from your Slack Workspace first.
from langchain.document_loaders import SLackDirectoryLoader

SLACK_WORKSPACE_URL = "https://awesome.slack.com"

loader = ("Slack_Exports", SLACK_WORKSPACE_URL)
docs = loader.load()
```
2023-04-13 21:31:59 -07:00
Harrison Chase
ed2ef5cbe4 Harrison/rwkv utf8 (#2867)
Co-authored-by: Akihiro <ueyama0105@gmail.com>
2023-04-13 21:31:18 -07:00
Adam McCabe
6be5d7c612 Update reduce_openapi_spec for PATCH and DELETE (#2861)
My recent pull request (#2729) neglected to update the
`reduce_openapi_spec` in spec.py to also accommodate PATCH and DELETE
added to planner.py and prompt_planner.py.
2023-04-13 20:27:40 -07:00
Benjamin Tan Wei Hao
c26a259ba6 Fix tiny typo (#2863) 2023-04-13 20:26:26 -07:00
Jon Luo
f3180f05f9 Update sql chain notebook to clarify use of SQLAlchemy for connections (#2850)
Have seen questions about whether or not the `SQLDatabaseChain` supports
more than just sqlite, which was unclear in the docs, so tried to
clarify that and how to connect to other dialects.
2023-04-13 11:46:59 -07:00
leo-gan
ecc1a0c051 added code-analysis-deeplake.ipynb (#2844)
This notebook is heavily copied from the
`twitter-the-algorithm-analysis-deeplake.ipynb`
2023-04-13 11:29:59 -07:00
Tim Asp
70ffe470aa Add easy print method to openai callback (#2848)
Found myself constantly copying the snippet outputting all the callback
tracking details. so adding a simple way to output the full context
2023-04-13 11:28:42 -07:00
Tim Asp
be4fb24b32 OpenAI LLM: update modelname_to_contextsize with new models (#2843)
Token counts pulled from https://openai.com/pricing
2023-04-13 11:13:34 -07:00
vowelparrot
82d1d5f24e Fix grammar in Vector Memory Docs (#2847) 2023-04-13 11:00:09 -07:00
Tim Asp
53dc157145 [Docs] minor fixes to loaders links and rst warnings (#2846)
The doc loaders index was picking up a bunch of subheadings because I
mistakenly made the MD titles H1s. Fixed that.

also the easy minor warnings from docs_build
2023-04-13 10:54:40 -07:00
Harrison Chase
1609950597 Harrison/retriever memory (#2804)
Co-authored-by: vowelparrot <130414180+vowelparrot@users.noreply.github.com>
2023-04-13 10:03:43 -07:00
Rounak Datta
7688bf9182 WhatsApp document loader - update regex (#2776)
I was testing out the WhatsApp Document loader, and noticed that
sometimes the date is of the following format (notice the additional
underscore):
```
3/24/23, 1:54_PM - +91 99999 99999 joined using this group's invite link
3/24/23, 6:29_PM - +91 99999 99999: When are we starting then?
```

Wierdly, the underscore is visible in Vim, but not on editors like
VSCode. I presume it is some unusual character/line terminator.
Nevertheless, I think handling this edge case will make the document
loader more robust.
2023-04-13 09:48:32 -07:00
vowelparrot
2db9b7a45d Revert "Add Slack Directory Loader (#2835)" (#2839)
This reverts commit a6f767ae7a.

To fix the linting error.
2023-04-13 09:42:54 -07:00
KullTC
802363eb6a Remove print statement from test (#2809)
Remove unnecessary print statement.
2023-04-13 09:31:48 -07:00
Azam Iftikhar
2a89dc8c1c Fixing factually incorrect example (#2810)
### https://github.com/hwchase17/langchain/issues/2802
It appears that Google's Flan model may not perform as well as other
models, I used a simple example to get factually correct answer.
2023-04-13 08:42:39 -07:00
vowelparrot
a6f767ae7a Add Slack Directory Loader (#2835)
Adds a loader for Slack Exports which can be a very valuable source of
    knowledge to use for internal QA bots and other use cases.

    ```py
    # Export data from your Slack Workspace first.
    from langchain.document_loaders import SLackDirectoryLoader

    SLACK_WORKSPACE_URL = "https://awesome.slack.com"

    loader = ("Slack_Exports", SLACK_WORKSPACE_URL)
    docs = loader.load()
```

---------

Co-authored-by: Mikhail Dubov <mikhail@chattermill.io>
2023-04-13 08:39:07 -07:00
st01cs
4f231b46ee Add openai.api_base to support openapi proxy (#2823)
I need access openai api through a proxy, so to add openai.api_base to
support this method.

Co-authored-by: bijia <bijia1@xiaomi.com>
2023-04-13 08:35:36 -07:00
Harrison Chase
414dc803b6 bump version to 139 (#2834) 2023-04-13 08:34:08 -07:00
Preetesh Jain
61858c5a08 Fix headings in docs (ClearML and Comet) (#2808)
This PR fixes the document structure in the
[Ecosystem](https://python.langchain.com/en/latest/ecosystem.html) page.
Also adds a fix for the heading on the
[Comet](https://python.langchain.com/en/latest/ecosystem/comet_tracking.html)
page for more consistency with other ecosystem tools.

## Screenshot

<img width="878" alt="image"
src="https://user-images.githubusercontent.com/6207830/231674921-9bf25376-cf14-4dba-be3c-08e0abda6154.png">

<img width="869" alt="image"
src="https://user-images.githubusercontent.com/6207830/231675105-d8e42df4-2d01-435b-9e09-3371522fd2ce.png">
2023-04-13 08:24:16 -07:00
Harrison Chase
9a96691803 cr 2023-04-13 08:23:33 -07:00
了空
324e9c83d5 Add BiliBiliLoader to langchain.document_loaders.__init__.py (#2826) 2023-04-13 06:47:27 -07:00
Nuhman Pk
ed03e965de Update README.md (#2805)
Added total download in a month (https://pepy.tech/project/langchain)
2023-04-12 22:02:06 -07:00
KullTC
64596b23b9 Return output of PythonAstREPLTool when falling back to exec() (#2780)
When the code ran by the PythonAstREPLTool contains multiple statements
it will fallback to exec() instead of using eval(). With this change, it
will also return the output of the code in the same way the
PythonREPLTool will.
2023-04-12 21:22:46 -07:00
Harrison Chase
1bb0706955 Harrison/comet ml (#2799)
Co-authored-by: Dhruv Nair <dhruv.nair@gmail.com>
Co-authored-by: Boris Feld <lothiraldan@gmail.com>
2023-04-12 21:21:51 -07:00
Harrison Chase
b2bc5ef56a agent refactor (#2801) 2023-04-12 21:21:41 -07:00
Zach Jones
abfca72c0b Add max_execution_time to openapi, pandas, and sql creators (#2779)
In #2399 we added the ability to set `max_execution_time` when creating
an AgentExecutor. This PR adds the `max_execution_time` argument to the
built-in pandas, sql, and openapi agents.

Co-authored-by: Zachary Jones <zjones@zetaglobal.com>
2023-04-12 17:09:42 -07:00
Matt Robinson
f0be3b0689 feat: add support for non-html in UnstructuredURLLoader (#2793)
### Summary

Adds support for processing non HTML document types in the URL loader.
For example, the URL loader can now process a PDF or markdown files
hosted at a URL.

### Testing

```python
from langchain.document_loaders import UnstructuredURLLoader

urls = ["https://www.understandingwar.org/sites/default/files/Russian%20Offensive%20Campaign%20Assessment%2C%20April%2011%2C%202023.pdf"]

loader = UnstructuredURLLoader(urls=urls, strategy="fast")
docs = loader.load()
print(docs[0].page_content[:1000])
```
2023-04-12 17:06:28 -07:00
Tim Connors
e081c62aac Fixed k=0 bug on ConversationBufferWindowMemory (#2796)
Updated the "load_memory_variables" function of the
ConversationBufferWindowMemory to support a window size of 0 (k=0).
Previous behavior would return the full memory instead of an empty
array.
2023-04-12 17:05:54 -07:00
dev2049
a094b7f807 Improve eval chain prompt (#2798)
Eval chain is currently very sensitive to differences in phrasing,
punctuation, and tangential information. This prompt has worked better
for me on my examples.

More general q: Do we have any framework for evaluating default prompt
changes? Could maybe start doing some regression testing?
2023-04-12 17:05:20 -07:00
Kah Keng Tay
1c7fb31bba Weaviate attributes and error handling (#2800) 2023-04-12 17:04:42 -07:00
dev2049
0e763677e4 Fix typo in qa eval chain prompt (#2797) 2023-04-12 14:17:25 -07:00
Harrison Chase
e49f1e628c Harrison/gpt cache (#2744)
Co-authored-by: SimFG <bang.fu@zilliz.com>
2023-04-12 14:16:58 -07:00
Harrison Chase
425c437cd3 cr 2023-04-12 13:46:58 -07:00
Harrison Chase
a2d729e537 cr 2023-04-12 13:44:21 -07:00
Harrison Chase
7adbc4fbb4 agent memory (#2792) 2023-04-12 12:51:15 -07:00
Nuno Campos
1bea9ea4be Fix async task being destroyed before cancelled (#2787) 2023-04-12 12:38:38 -07:00
Harrison Chase
819d72614a version 138 (#2782) 2023-04-12 11:10:47 -07:00
wangml999
fa0c9390c2 Update custom_agent.ipynb (#2767)
Fixed an issue the agent is not taking the user's question as input.
2023-04-12 09:13:46 -07:00
Joshua Snyder
59d054308c Add type inference for output parsers (#2769)
Currently, the output type of a number of OutputParser's `parse` methods
is `Any` when it can in fact be inferred.

This PR makes BaseOutputParser use a generic type and fixes the output
types of the following parsers:
- `PydanticOutputParser`
- `OutputFixingParser`
- `RetryOutputParser`
- `RetryWithErrorOutputParser`

The output of the `StructuredOutputParser` is corrected from `BaseModel`
to `Any` since there are no type guarantees provided by the parser.

Fixes issue #2715
2023-04-12 09:12:20 -07:00
Nuhman Pk
789cc314c5 Typo (#2747) 2023-04-12 09:06:30 -07:00
Harrison Chase
b92a89e29f cr 2023-04-11 23:52:14 -07:00
vowelparrot
94a92abf24 Add Retrieval Example for AI Plugins (#2737)
This PR proposes
- An NLAToolkit method to instantiate from an AI Plugin URL
- A notebook that shows how to use that alongside an example of using a
Retriever object to lookup specs and route queries to them on the fly

---------

Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-04-11 23:22:14 -07:00
Nuhman Pk
b5bbe601fb Update chatgpt_plugins.ipynb (#2745)
Changed deprecated requests to requests_all in plugins example
2023-04-11 22:45:31 -07:00
Harrison Chase
b38a6ea7df Harrison/apply llm flag (#2743)
Co-authored-by: Nick Gibb <gibbnick@gmail.com>
Co-authored-by: Nick Gibb <nick.gibb@bluedot.global>
2023-04-11 22:02:37 -07:00
vr140
dd59193757 Remove unnecessary method from Qdrant vectorstore and clean up docstrings (#2700)
**Problem:**

The `from_documents` method in Qdrant vectorstore is unnecessary because
it does not change any default behavior from the abstract base class
method of `from_documents` (contrast this with the method in Chroma
which makes a change from default and turns `embeddings` into an
Optional parameter).

Also, the docstrings need some cleanup.

**Solution:**

Remove unnecessary method and improve docstrings.

---------

Co-authored-by: Vijay Rajaram <vrajaram3@gatech.edu>
2023-04-11 21:34:22 -07:00
Matthew Plachter
933dfac583 Add Zapier NLA OAuth access_token to be used (#2726)
This change allows the user to initialize the ZapierNLAWrapper with a
valid Zapier NLA OAuth Access_Token, which would be used to make
requests back to the Zapier NLA API.

When a `zapier_nla_oauth_access_token` is passed to the ZapierNLAWrapper
it is no longer required for the `ZAPIER_NLA_API_KEY ` environment
variable to be set, still having it set will not affect the behavior as
the `zapier_nla_oauth_access_token` will be used over the
`ZAPIER_NLA_API_KEY`
2023-04-11 21:32:54 -07:00
Harrison Chase
507cee5ee5 Harrison/pinecone hybrid update (#2742)
Co-authored-by: acatav <39461369+acatav@users.noreply.github.com>
Co-authored-by: Amnon Catav <catav.amnon1@gmail.com>
2023-04-11 21:32:17 -07:00
Johnny Lee
744c25cd0a Updating YoutubeLoader.from_youtube_channel name and doc to reflect actual usage (#2734)
the function actually updates video_id from URL not channel.

The docs still reflect the previous old function name
`from_youtube_url`. Resolves #1962


https://python.langchain.com/en/latest/modules/indexes/document_loaders/examples/youtube.html
2023-04-11 21:12:58 -07:00
Johnny Lee
0ab364404e add continue to fix 'continue_on_failure' parameter for URL doc loader (#2735)
Currently, the function still fails if `continue_on_failure` is set to
True, because `elements` is not set.

---------

Co-authored-by: leecjohnny <johnny-lee1255@users.noreply.github.com>
2023-04-11 21:12:39 -07:00
sergerdn
4bdcedab54 fix: some imports for integration tests (#2612)
Add more missed imports for integration tests. Bump `pytest` to the
current latest version.
Fix `tests/integration_tests/vectorstores/test_elasticsearch.py` to
update its cassette(easy fix).

Related PR: https://github.com/hwchase17/langchain/pull/2560
2023-04-11 20:45:36 -07:00
Ankush Gola
c1521ddbdb Add workaround for not having async vector store methods (#2733)
This allows us to use the async API for the Retrieval chains, though it is not guaranteed to be thread safe.
2023-04-11 18:49:08 -07:00
vowelparrot
0806951c07 Update VectorStore Class Method Typing (#2731)
Avoid using placeholder methods that only perform a `cast()`
operation because the typing would otherwise be inferred to be the
parent `VectorStore` class. This is unnecessary with TypeVar's.
2023-04-11 14:14:49 -07:00
Adam McCabe
446c3d586c Add PATCH and DELETE to OpenAPI Agent (#2729)
This PR proposes an update to the OpenAPI Planner and Planner Prompts to
make Patch and Delete available to the planner and executor. I followed
the same patterns as for GET and POST, and made some updates to the
examples available to the Planner and Orchestrator.

Of note, I tried to write prompts for DELETE such that the model will
only execute that job if the User specifically asks for a 'Delete' (see
the Prompt_planner.py examples to see specificity), or if the User had
previously authorized the Delete in the Conversation memory. Although
PATCH also modifies existing data, I considered it lower risk and so did
not try to enforce the same restrictions on the Planner.
2023-04-11 13:26:04 -07:00
vinoyang
8073bc849f Minor: Remove duplicated word in error message (#2706)
Removed the duplicated word "it" from the error message.
From:
`Please it install it with xxx`
To:
`Please install it with xxx`.
2023-04-11 13:10:33 -07:00
134ARG
1e60e6e15b Fix the unset argument in calling llama model (#2714)
When using the llama.cpp together with agent like
zero-shot-react-description, the missing branch will cause the parameter
`stop` left empty, resulting in unexpected output format from the model.

This patch fixes that issue.
2023-04-11 11:02:39 -07:00
Joshua Snyder
f435f2267c Use tiktoken for Python 3.8 (#2709)
Fixes issue #2677

`tiktoken` is supported for Python 3.8, so there is no need to use the
fallback GPT-2 tokenizer.
2023-04-11 11:02:28 -07:00
Kei Kamikawa
186ca9d3e4 fixed aiohttp.client_exceptions.ClientConnectionError: Connection closed (#2718)
I fixed an issue where an error would always occur when making a request
using the `TextRequestsWrapper` with async API.

This is caused by escaping the scope of the context, which causes the
connection to be broken when reading the response body.

The correct usage is as described in the [official
tutorial](https://docs.aiohttp.org/en/stable/client_quickstart.html#make-a-request),
where the text method must also be handled in the context scope.

<details>

<summary>Stacktrace</summary>

```
  File "/home/vscode/.cache/pypoetry/virtualenvs/codehex-workspace-xS3fZVNL-py3.11/lib/python3.11/site-packages/langchain/tools/base.py", line 116, in arun
    raise e
  File "/home/vscode/.cache/pypoetry/virtualenvs/codehex-workspace-xS3fZVNL-py3.11/lib/python3.11/site-packages/langchain/tools/base.py", line 110, in arun
    observation = await self._arun(tool_input)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.cache/pypoetry/virtualenvs/codehex-workspace-xS3fZVNL-py3.11/lib/python3.11/site-packages/langchain/agents/tools.py", line 22, in _arun
    return await self.coroutine(tool_input)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.cache/pypoetry/virtualenvs/codehex-workspace-xS3fZVNL-py3.11/lib/python3.11/site-packages/langchain/chains/base.py", line 234, in arun
    return (await self.acall(args[0]))[self.output_keys[0]]
            ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.cache/pypoetry/virtualenvs/codehex-workspace-xS3fZVNL-py3.11/lib/python3.11/site-packages/langchain/chains/base.py", line 154, in acall
    raise e
  File "/home/vscode/.cache/pypoetry/virtualenvs/codehex-workspace-xS3fZVNL-py3.11/lib/python3.11/site-packages/langchain/chains/base.py", line 148, in acall
    outputs = await self._acall(inputs)
              ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/src/tools/example.py", line 153, in _acall
    api_response = await self.requests_wrapper.aget("http://example.com")
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.cache/pypoetry/virtualenvs/codehex-workspace-xS3fZVNL-py3.11/lib/python3.11/site-packages/langchain/requests.py", line 130, in aget
    return await response.text()
           ^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.cache/pypoetry/virtualenvs/codehex-workspace-xS3fZVNL-py3.11/lib/python3.11/site-packages/aiohttp/client_reqrep.py", line 1081, in text
    await self.read()
  File "/home/vscode/.cache/pypoetry/virtualenvs/codehex-workspace-xS3fZVNL-py3.11/lib/python3.11/site-packages/aiohttp/client_reqrep.py", line 1037, in read
    self._body = await self.content.read()
                 ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.cache/pypoetry/virtualenvs/codehex-workspace-xS3fZVNL-py3.11/lib/python3.11/site-packages/aiohttp/streams.py", line 349, in read
  raise self._exception
aiohttp.client_exceptions.ClientConnectionError: Connection closed
```

</details>
2023-04-11 10:52:55 -07:00
Dogan Can Bakir
3623bdb31b Make the OpenAPI agent's verbose print optional (#2666) 2023-04-11 10:42:39 -07:00
vowelparrot
709f26b69e Added bilibili loader (#2673) (#2724)
I've added a bilibili loader, bilibili is a very active video site in
China and I think we need this loader.

Example:
```python
from langchain.document_loaders.bilibili import BiliBiliLoader

loader = BiliBiliLoader(
       ["https://www.bilibili.com/video/BV1xt411o7Xu/",
       "https://www.bilibili.com/video/av330407025/"]
)
docs = loader.load()
```

Co-authored-by: 了空 <568250549@qq.com>
2023-04-11 10:40:32 -07:00
David Wu
d42deff402 fixed typo (#2720)
changed "to" to "too" in the memory notebook
2023-04-11 09:53:38 -07:00
David Wu
263ce40844 added a missing word (typo) (#2719)
Changed from "You may often to" to "You may often have to" to fix the
sentence.
2023-04-11 09:09:28 -07:00
Harrison Chase
66786b0f0f cr 2023-04-11 08:16:06 -07:00
Harrison Chase
948b14b52a agents docs and version bump (#2717) 2023-04-11 08:08:43 -07:00
Abhik Singla
955bd2e1db Fixed Ast Python Repl for Chatgpt multiline commands (#2406)
Resolves issue https://github.com/hwchase17/langchain/issues/2252

---------

Co-authored-by: Abhik Singla <abhiksingla@microsoft.com>
2023-04-10 21:25:03 -07:00
Harrison Chase
1271c00ff0 Harrison/openapi planner (#2692)
Co-authored-by: Adam McCabe <adam.r.mccabe@gmail.com>
2023-04-10 21:22:42 -07:00
Harrison Chase
e0a13e9355 Harrison/postgres (#2691)
Co-authored-by: Ankit Jain <ankneo@users.noreply.github.com>
2023-04-10 21:15:42 -07:00
Guohao Li
bb5118f4c9 Add notebook example for camel role playing (#2689)
This PR adds a LangChain implementation of CAMEL role-playing example:
https://github.com/lightaime/camel.

I am sorry that I am not that familiar with LangChain. So I only
implement it in a naive way. There may be a better way to implement it.
2023-04-10 21:12:45 -07:00
Harrison Chase
d3f779d61d baby agi agent (#2648)
Co-authored-by: William FH <13333726+hinthornw@users.noreply.github.com>
2023-04-10 21:03:30 -07:00
Naveen Tatikonda
4364d3316e Add custom vector fields and text fields for OpenSearch (#2652)
**Description**
Add custom vector field name and text field name while indexing and
querying for OpenSearch

**Issues**
https://github.com/hwchase17/langchain/issues/2500

Signed-off-by: Naveen Tatikonda <navtat@amazon.com>
2023-04-10 21:02:02 -07:00
Pavel Shibanov
023de9a70b Add OpenAIEmbeddings special token params for tiktoken (#2682)
#2681 

Original type hints
```python
allowed_special: Union[Literal["all"], AbstractSet[str]] = set(),  # noqa: B006
disallowed_special: Union[Literal["all"], Collection[str]] = "all",
```
from

46287bfa49/tiktoken/core.py (L79-L80)
are not compatible with pydantic

<img width="718" alt="image"
src="https://user-images.githubusercontent.com/5096640/230993236-c744940e-85fb-4baa-b9da-8b00fb60a2a8.png">

I think we could use
```python
allowed_special: Union[Literal["all"], Set[str]] = set()
disallowed_special: Union[Literal["all"], Set[str], Tuple[()]] = "all"
```

Please let me know if you would like to implement it differently.
2023-04-10 21:00:55 -07:00
Nikita Zavgorodnii
1c979e320d docs: update tokenizer notice in llms/getting_started (#2641)
A tiny update in docs which is spotted here:
https://github.com/hwchase17/langchain/issues/2439
2023-04-10 20:55:45 -07:00
Yasin Tatar
9d20fd5135 add: conda installation instructions (#2678)
Hi, 

just wanted to mention that I added `langchain` to
[conda-forge](https://github.com/conda-forge/langchain-feedstock), so
that it can be installed with `conda`/`mamba` etc.
This makes it available to some corporate users with custom
conda-servers and people who like to manage their python envs with
conda.
2023-04-10 20:54:13 -07:00
vr140
28bef6f87d Clean up OpenAI Embeddings to fix method name and comments (#2687)
**Problem:**

OpenAI Embeddings has a few minor issues: method name and comment for
_completion_with_retry seems to be a copypasta error and a few comments
around usage of embedding_ctx_length seem to be incorrect.

**Solution:**

Clean up issues.

---------

Co-authored-by: Vijay Rajaram <vrajaram3@gatech.edu>
2023-04-10 20:53:56 -07:00
Harrison Chase
ad3c5dd186 Harrison/databerry (#2688)
Co-authored-by: Georges Petrov <georgesm.petrov@gmail.com>
2023-04-10 18:49:47 -07:00
Filip Haltmayer
b286d0e63f Adding milvus/zilliz into docs (#2686)
Adding Milvus and Zilliz to integrations.md and creating an ecosystems
doc for Zilliz.

Signed-off-by: Filip Haltmayer <filip.haltmayer@zilliz.com>
2023-04-10 18:08:41 -07:00
Sean Sheng
90d5328eda docs: Update deployments.md to include a BentoML example (#2661)
Add a new deployment example with BentoML, see more
https://github.com/ssheng/BentoChain.
2023-04-10 14:57:32 -07:00
Tommertom
bd9f095ed2 Doc - Update google_search.ipynb - more explicit reference to places where to create API keys (#2670)
Took me a bit to find the proper places to get the API keys. The link
earlier provided to setup search is still good, but why not provide
direct link to the Google cloud tools that give you ability to create
keys?
2023-04-10 12:36:52 -07:00
Ankush Gola
e23a596a18 SqlDatabaseToolkit should have custom llm for QueryChecke… (#2676)
…rTool (#2655)

---------

Co-authored-by: Rushabh Agarwal <26388764+rushout09@users.noreply.github.com>
2023-04-10 11:43:24 -07:00
Ankush Gola
8d3b059332 Add docs for callbacks (#2643)
Basically copy what's in the ts docs:
https://js.langchain.com/docs/production/callbacks


Discovered a bug wrt not awaiting callbacks in `LLMMathChain` so fixed
that
2023-04-10 10:23:11 -07:00
Dmitri Melikyan
1931d4495e Update Graphsignal ecosystem page (#2662)
Added/updated information due to new automatic data recording feature.
2023-04-10 08:00:26 -07:00
Harrison Chase
e63f9a846b Harrison/docs agents (#2647) 2023-04-09 22:34:34 -07:00
Ankush Gola
b82cbd1be0 Use run and arun in place of combine_docs and acombine_docs (#2635)
`combine_docs` does not go through the standard chain call path which
means that chain callbacks won't be triggered, meaning QA chains won't
be traced properly, this fixes that.

Also fix several errors in the chat_vector_db notebook
2023-04-09 18:47:59 -07:00
Chetanya Rastogi
50c511d75f Add new loader to load pdf as html content (#2607)
Adds a new pdf loader using the existing dependency on PDFMiner. 

The new loader can be helpful for chunking texts semantically into
sections as the output html content can be parsed via `BeautifulSoup` to
get more structured and rich information about font size, page numbers,
pdf headers/footers, etc. which may not be available otherwise with
other pdf loaders
2023-04-09 17:57:25 -07:00
Ankush Gola
61f7bd7a3a fix question answering nb (#2637)
Was throwing exception bc `VectorIndexWrapper` did not have
`similarity_search` -- changed to just use retriever
2023-04-09 17:56:49 -07:00
William FH
10ff1fda8e Add Streaming for GPT4All (#2642)
- Adds  support for callback handlers in GPT4All models
- Updates notebook and docs
2023-04-09 17:54:26 -07:00
Ankush Gola
c51753250d Add async call to APIChain. (#2583) (#2644)
Co-authored-by: Yan <32036413+Yan-Zero@users.noreply.github.com>
2023-04-09 16:28:16 -07:00
William FH
e56673c7f9 BabyAGI Notebook Example (#2559)
Create a notebook implementing
[BabyAGI](https://github.com/yoheinakajima/babyagi/tree/main) by [Yohei
Nakajima](https://twitter.com/yoheinakajima) as LLM Chains.
2023-04-09 13:54:23 -07:00
Harrison Chase
7c1dd3057f cr 2023-04-09 13:10:46 -07:00
Harrison Chase
412397ad55 bump version to 136 (#2634) 2023-04-09 13:08:05 -07:00
Harrison Chase
7aba18ea77 Harrison/docs cleanup (#2633) 2023-04-09 12:55:22 -07:00
Jan
e57f0e38c1 Fix small typo in SemanticSimilarityExampleSelector (#2629) 2023-04-09 12:53:02 -07:00
Nick Gibb
63175eb696 Fix typo in docs (#2601)
Minor typo in the docs ("reccomended" -> "recommended")

Co-authored-by: Nick Gibb <nick.gibb@bluedot.global>
2023-04-09 12:52:35 -07:00
blob42
54b1645d13 fix: ReadTheDocs loader main content filter (#2609)
It seems the main element wrapper changed in ReadTheDocs website or for
some reason it's different for me ?

This adds an extra filter for the main content wrapper if the first one
returns no text.


![2023-04-09-043315_1178x873_scrot](https://user-images.githubusercontent.com/210457/230751369-24b69cb9-1601-4540-b5f3-d115165f55f6.jpg)

Co-authored-by: blob42 <spike@w530>
2023-04-09 12:51:56 -07:00
Davit Buniatyan
aaac7071a3 Deep Lake retriever example analyzing Twitter the-algorithm source code (#2602)
Improvements to Deep Lake Vector Store
- much faster view loading of embeddings after filters with
`fetch_chunks=True`
- 2x faster ingestion
- use np.float32 for embeddings to save 2x storage, LZ4 compression for
text and metadata storage (saves up to 4x storage for text data)
- user defined functions as filters

Docs
- Added retriever full example for analyzing twitter the-algorithm
source code with GPT4
- Added a use case for code analysis (please let us know your thoughts
how we can improve it)

---------

Co-authored-by: Davit Buniatyan <d@activeloop.ai>
2023-04-09 12:29:47 -07:00
William FH
5c0c5fafb2 Multi-Hop / Multi-Spec LLM Chain (#2549)
Add a notebook showing how to make a chain that composes multiple
OpenAPI Endpoint operations to accomplish tasks.
2023-04-09 12:29:16 -07:00
Jan
d2f8ddab10 Fix typo in PromptTemplate from_examples (#2628) 2023-04-09 12:28:50 -07:00
ecneladis
9a49f5763d Add missing comma in async_agent.ipynb (#2614) 2023-04-09 12:28:28 -07:00
Jan
166624d005 Fix typo in error message (#2622) 2023-04-09 12:25:49 -07:00
Girish Sharma
9aed565f13 Fix missing import in AzureOpenAI embeddings example (#2625)
## Why this PR?

Fixes #2624
There's a missing import statement in AzureOpenAI embeddings example.

## What's new in this PR?

- Import `OpenAIEmbeddings` before creating it's object.

## How it's tested?
- By running notebook and creating embedding object.

Signed-off-by: letmerecall <girishsharma001@gmail.com>
2023-04-09 12:25:31 -07:00
Tommertom
0f5d3b3390 Typo docs - Update data_augmented_question_answering.ipynb propriterary-> proprietary (#2626)
Minor typo propritary -> proprietary
2023-04-09 12:24:53 -07:00
Nuno Campos
5376799a23 Allow recovering from JSONDecoder errors in StructuredOutputParser (#2616) 2023-04-09 07:32:49 -07:00
Nuno Campos
6f39e88a2c Add AsyncIteratorCallbackHandler (#2329) 2023-04-08 14:34:55 -07:00
Harrison Chase
6e4e7d2637 bump version to 135 (#2600) 2023-04-08 13:46:35 -07:00
rkeshwani
5e57496225 #2595 ChromaDB: Add ability to adjust metadata for indexes upon creating co… (#2597)
Referencing #2595
Added optional default parameter to adjust index metadata upon
collection creation per chroma code

ce0bc89777/chromadb/api/local.py (L74)

Allowing for user to have the ability to adjust distance calculation
functions.
2023-04-08 13:31:17 -07:00
Harrison Chase
b9e5b27a99 Harrison/motorhead (#2599)
Co-authored-by: James O'Dwyer <100361543+softboyjimbo@users.noreply.github.com>
2023-04-08 13:27:20 -07:00
Johnny Lim
79a44c8225 Remove unnecessary question mark in link in README (#2589)
This PR removes an unnecessary question mark in link in the `README.md`
file.
2023-04-08 12:41:25 -07:00
Harrison Chase
2f49c96532 Harrison/redis (#2588)
Co-authored-by: Tyler Hutcherson <tyler.hutcherson@redis.com>
2023-04-08 10:55:52 -07:00
Yuchu Luo
40469eef7f fix temperature parameter not used in chat models (#2558) 2023-04-08 08:47:50 -07:00
Will Henchy
125afb51d7 Add shared Google Drive folder support (#2562)
closes #1634

Adds support for loading files from a shared Google Drive folder to
`GoogleDriveLoader`. Shared drives are commonly used by businesses on
their Google Workspace accounts (this is my particular use case).
2023-04-08 08:46:55 -07:00
Alex Rad
7bf5b0ccd3 RWKV: do not propagate model_state between calls (#2565)
RWKV is an RNN with a hidden state that is part of its inference.
However, the model state should not be carried across uses and it's a
bug to do so.

This resets the state for multiple invocations
2023-04-08 08:36:16 -07:00
Venky
7a4e1b72a8 Fix docs links (#2572)
Fix broken links in documentation.
2023-04-08 08:33:28 -07:00
Roy Xue
f5afb60116 doc: change comment with correct name (#2580)
In this comment, it should be **ConversationalRetrievalChain** instead
of **ChatVectorDBChain**
2023-04-08 08:31:33 -07:00
Shishin Mo
f7f118e021 use openai_organization as argument (#2566)
Added support for passing the openai_organization as an argument, as it
was only supported by the environment variable but openai_api_key was
supported by both environment variables and arguments.

`ChatOpenAI(temperature=0, model_name="gpt-4", openai_api_key="sk-****",
openai_organization="org-****")`
2023-04-07 22:02:02 -07:00
akmhmgc
544cc7f395 Modified doc (#2568)
# description
Remove unnecessary codes and made the output easier to check in docs :)
2023-04-07 22:01:53 -07:00
sergerdn
cd9336469e fix: missed deps integrations tests (#2560)
Almost all integration tests have failed, but we haven't encountered any
import errors yet. Some tests failed due to lazy import issues. It
doesn't seem like a problem to resolve some of these errors in the next
PR.
I have a headache from resolving conflicts with `deeplake` and `boto3`,
so I will temporarily comment out `boto3`.


fix https://github.com/hwchase17/langchain/issues/2426
2023-04-07 20:43:53 -07:00
Kacper Łukawski
d8967e28d0 Upgrade Qdrant to 1.1.2 (#2554)
This is a minor upgrade for Qdrant. We made a small bugfix in the local
mode, so it might also be good to upgrade Qdrant for LangChain users.
2023-04-07 12:24:32 -07:00
joaoareis
b4d6a425a2 Fix typo in ChatGPT plugins (#2553)
This PR adds a `,` that was missing in the ChatGPT plugins examples.
2023-04-07 11:17:15 -07:00
Ikko Eltociear Ashimine
fc1d48814c fix typo in summary_buffer.ipynb (#2547)
ouput -> output
2023-04-07 11:16:53 -07:00
Duncan Brown
9b78bb7393 Fix a typo in the SQL agent prompt prefix (#2552)
Fix the grammar in this sentence, and remove the redundant "few"

"only ask for a the few relevant columns" -> "only ask for the relevant
columns"
2023-04-07 11:15:47 -07:00
1090 changed files with 303950 additions and 11566 deletions

42
.devcontainer/Dockerfile Normal file
View File

@@ -0,0 +1,42 @@
# This is a Dockerfile for Developer Container
# Use the Python base image
ARG VARIANT="3.11-bullseye"
FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} AS langchain-dev-base
USER vscode
# Define the version of Poetry to install (default is 1.4.2)
# Define the directory of python virtual environment
ARG PYTHON_VIRTUALENV_HOME=/home/vscode/langchain-py-env \
POETRY_VERSION=1.4.2
ENV POETRY_VIRTUALENVS_IN_PROJECT=false \
POETRY_NO_INTERACTION=true
# Create a Python virtual environment for Poetry and install it
RUN python3 -m venv ${PYTHON_VIRTUALENV_HOME} && \
$PYTHON_VIRTUALENV_HOME/bin/pip install --upgrade pip && \
$PYTHON_VIRTUALENV_HOME/bin/pip install poetry==${POETRY_VERSION}
ENV PATH="$PYTHON_VIRTUALENV_HOME/bin:$PATH" \
VIRTUAL_ENV=$PYTHON_VIRTUALENV_HOME
# Setup for bash
RUN poetry completions bash >> /home/vscode/.bash_completion && \
echo "export PATH=$PYTHON_VIRTUALENV_HOME/bin:$PATH" >> ~/.bashrc
# Set the working directory for the app
WORKDIR /workspaces/langchain
# Use a multi-stage build to install dependencies
FROM langchain-dev-base AS langchain-dev-dependencies
ARG PYTHON_VIRTUALENV_HOME
# Copy only the dependency files for installation
COPY pyproject.toml poetry.lock poetry.toml ./
# Install the Poetry dependencies (this layer will be cached as long as the dependencies don't change)
RUN poetry install --no-interaction --no-ansi --with dev,test,docs

View File

@@ -0,0 +1,33 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/docker-existing-dockerfile
{
"dockerComposeFile": "./docker-compose.yaml",
"service": "langchain",
"workspaceFolder": "/workspaces/langchain",
"name": "langchain",
"customizations": {
"vscode": {
"extensions": [
"ms-python.python"
],
"settings": {
"python.defaultInterpreterPath": "/home/vscode/langchain-py-env/bin/python3.11"
}
}
},
// Features to add to the dev container. More info: https://containers.dev/features.
"features": {},
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Uncomment the next line to run commands after the container is created.
// "postCreateCommand": "cat /etc/os-release",
// Uncomment to connect as an existing user other than the container default. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "devcontainer"
"remoteUser": "vscode",
"overrideCommand": true
}

View File

@@ -0,0 +1,31 @@
version: '3'
services:
langchain:
build:
dockerfile: .devcontainer/Dockerfile
context: ../
volumes:
- ../:/workspaces/langchain
networks:
- langchain-network
# environment:
# MONGO_ROOT_USERNAME: root
# MONGO_ROOT_PASSWORD: example123
# depends_on:
# - mongo
# mongo:
# image: mongo
# restart: unless-stopped
# environment:
# MONGO_INITDB_ROOT_USERNAME: root
# MONGO_INITDB_ROOT_PASSWORD: example123
# ports:
# - "27017:27017"
# networks:
# - langchain-network
networks:
langchain-network:
driver: bridge

View File

@@ -2,60 +2,62 @@
Hi there! Thank you for even being interested in contributing to LangChain.
As an open source project in a rapidly developing field, we are extremely open
to contributions, whether it be in the form of a new feature, improved infra, or better documentation.
to contributions, whether they be in the form of new features, improved infra, better documentation, or bug fixes.
## 🗺️ Guidelines
### 👩‍💻 Contributing Code
To contribute to this project, please follow a ["fork and pull request"](https://docs.github.com/en/get-started/quickstart/contributing-to-projects) workflow.
Please do not try to push directly to this repo unless you are maintainer.
## 🗺Contributing Guidelines
Please follow the checked-in pull request template when opening pull requests. Note related issues and tag relevant
maintainers.
Pull requests cannot land without passing the formatting, linting and testing checks first. See
[Common Tasks](#-common-tasks) for how to run these checks locally.
It's essential that we maintain great documentation and testing. If you:
- Fix a bug
- Add a relevant unit or integration test when possible. These live in `tests/unit_tests` and `tests/integration_tests`.
- Make an improvement
- Update any affected example notebooks and documentation. These lives in `docs`.
- Update unit and integration tests when relevant.
- Add a feature
- Add a demo notebook in `docs/modules`.
- Add unit and integration tests.
We're a small, building-oriented team. If there's something you'd like to add or change, opening a pull request is the
best way to get our attention.
### 🚩GitHub Issues
Our [issues](https://github.com/hwchase17/langchain/issues) page is kept up to date
with bugs, improvements, and feature requests. There is a taxonomy of labels to help
with sorting and discovery of issues of interest. These include:
with bugs, improvements, and feature requests.
- prompts: related to prompt tooling/infra.
- llms: related to LLM wrappers/tooling/infra.
- chains
- utilities: related to different types of utilities to integrate with (Python, SQL, etc.).
- agents
- memory
- applications: related to example applications to build
There is a taxonomy of labels to help with sorting and discovery of issues of interest. Please use these to help
organize issues.
If you start working on an issue, please assign it to yourself.
If you are adding an issue, please try to keep it focused on a single modular bug/improvement/feature.
If the two issues are related, or blocking, please link them rather than keep them as one single one.
If you are adding an issue, please try to keep it focused on a single, modular bug/improvement/feature.
If two issues are related, or blocking, please link them rather than combining them.
We will try to keep these issues as up to date as possible, though
with the rapid rate of develop in this field some may get out of date.
If you notice this happening, please just let us know.
If you notice this happening, please let us know.
### 🙋Getting Help
Although we try to have a developer setup to make it as easy as possible for others to contribute (see below)
it is possible that some pain point may arise around environment setup, linting, documentation, or other.
Should that occur, please contact a maintainer! Not only do we want to help get you unblocked,
but we also want to make sure that the process is smooth for future contributors.
Our goal is to have the simplest developer setup possible. Should you experience any difficulty getting setup, please
contact a maintainer! Not only do we want to help get you unblocked, but we also want to make sure that the process is
smooth for future contributors.
In a similar vein, we do enforce certain linting, formatting, and documentation standards in the codebase.
If you are finding these difficult (or even just annoying) to work with,
feel free to contact a maintainer for help - we do not want these to get in the way of getting
good code into the codebase.
If you are finding these difficult (or even just annoying) to work with, feel free to contact a maintainer for help -
we do not want these to get in the way of getting good code into the codebase.
### 🏭Release process
As of now, LangChain has an ad hoc release process: releases are cut with high frequency by
a developer and published to [PyPI](https://pypi.org/project/langchain/).
LangChain follows the [semver](https://semver.org/) versioning standard. However, as pre-1.0 software,
even patch releases may contain [non-backwards-compatible changes](https://semver.org/#spec-item-4).
If your contribution has made its way into a release, we will want to give you credit on Twitter (only if you want though)!
If you have a Twitter account you would like us to mention, please let us know in the PR or in another manner.
## 🚀Quick Start
## 🚀 Quick Start
This project uses [Poetry](https://python-poetry.org/) as a dependency manager. Check out Poetry's [documentation on how to install it](https://python-poetry.org/docs/#installation) on your system before proceeding.
@@ -75,9 +77,9 @@ This will install all requirements for running the package, examples, linting, f
❗Note: If you're running Poetry 1.4.1 and receive a `WheelFileValidationError` for `debugpy` during installation, you can try either downgrading to Poetry 1.4.0 or disabling "modern installation" (`poetry config installer.modern-installation false`) and re-install requirements. See [this `debugpy` issue](https://github.com/microsoft/debugpy/issues/1246) for more details.
Now, you should be able to run the common tasks in the following section.
Now, you should be able to run the common tasks in the following section. To double check, run `make test`, all tests should pass. If they don't you may need to pip install additional dependencies, such as `numexpr` and `openapi_schema_pydantic`.
## ✅Common Tasks
## ✅ Common Tasks
Type `make` for a list of common tasks.
@@ -188,3 +190,17 @@ Finally, you can build the documentation as outlined below:
```bash
make docs_build
```
## 🏭 Release Process
As of now, LangChain has an ad hoc release process: releases are cut with high frequency by
a developer and published to [PyPI](https://pypi.org/project/langchain/).
LangChain follows the [semver](https://semver.org/) versioning standard. However, as pre-1.0 software,
even patch releases may contain [non-backwards-compatible changes](https://semver.org/#spec-item-4).
### 🌟 Recognition
If your contribution has made its way into a release, we will want to give you credit on Twitter (only if you want though)!
If you have a Twitter account you would like us to mention, please let us know in the PR or in another manner.

106
.github/ISSUE_TEMPLATE/bug-report.yml vendored Normal file
View File

@@ -0,0 +1,106 @@
name: "\U0001F41B Bug Report"
description: Submit a bug report to help us improve LangChain
labels: ["02 Bug Report"]
body:
- type: markdown
attributes:
value: >
Thank you for taking the time to file a bug report. Before creating a new
issue, please make sure to take a few moments to check the issue tracker
for existing issues about the bug.
- type: textarea
id: system-info
attributes:
label: System Info
description: Please share your system info with us.
placeholder: LangChain version, platform, python version, ...
validations:
required: true
- type: textarea
id: who-can-help
attributes:
label: Who can help?
description: |
Your issue will be replied to more quickly if you can figure out the right person to tag with @
If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
The core maintainers strive to read all issues, but tagging them will help them prioritize.
Please tag fewer than 3 people.
@hwchase17 - project lead
Tracing / Callbacks
- @agola11
Async
- @agola11
DataLoader Abstractions
- @eyurtsev
LLM/Chat Wrappers
- @hwchase17
- @agola11
Tools / Toolkits
- @vowelparrot
placeholder: "@Username ..."
- type: checkboxes
id: information-scripts-examples
attributes:
label: Information
description: "The problem arises when using:"
options:
- label: "The official example notebooks/scripts"
- label: "My own modified scripts"
- type: checkboxes
id: related-components
attributes:
label: Related Components
description: "Select the components related to the issue (if applicable):"
options:
- label: "LLMs/Chat Models"
- label: "Embedding Models"
- label: "Prompts / Prompt Templates / Prompt Selectors"
- label: "Output Parsers"
- label: "Document Loaders"
- label: "Vector Stores / Retrievers"
- label: "Memory"
- label: "Agents / Agent Executors"
- label: "Tools / Toolkits"
- label: "Chains"
- label: "Callbacks/Tracing"
- label: "Async"
- type: textarea
id: reproduction
validations:
required: true
attributes:
label: Reproduction
description: |
Please provide a [code sample](https://stackoverflow.com/help/minimal-reproducible-example) that reproduces the problem you ran into. It can be a Colab link or just a code snippet.
If you have code snippets, error messages, stack traces please provide them here as well.
Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting
Avoid screenshots when possible, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.
placeholder: |
Steps to reproduce the behavior:
1.
2.
3.
- type: textarea
id: expected-behavior
validations:
required: true
attributes:
label: Expected behavior
description: "A clear and concise description of what you would expect to happen."

6
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,6 @@
blank_issues_enabled: true
version: 2.1
contact_links:
- name: Discord
url: https://discord.gg/6adMQxSpJS
about: General community discussions

View File

@@ -0,0 +1,19 @@
name: Documentation
description: Report an issue related to the LangChain documentation.
title: "DOC: <Please write a comprehensive title after the 'DOC: ' prefix>"
labels: [03 - Documentation]
body:
- type: textarea
attributes:
label: "Issue with current documentation:"
description: >
Please make sure to leave a reference to the document/code you're
referring to.
- type: textarea
attributes:
label: "Idea or request for content:"
description: >
Please describe as clearly as possible what topics you think are missing
from the current documentation.

View File

@@ -0,0 +1,30 @@
name: "\U0001F680 Feature request"
description: Submit a proposal/request for a new LangChain feature
labels: ["02 Feature Request"]
body:
- type: textarea
id: feature-request
validations:
required: true
attributes:
label: Feature request
description: |
A clear and concise description of the feature proposal. Please provide links to any relevant GitHub repos, papers, or other resources if relevant.
- type: textarea
id: motivation
validations:
required: true
attributes:
label: Motivation
description: |
Please outline the motivation for the proposal. Is your feature request related to a problem? e.g., I'm always frustrated when [...]. If this is related to another GitHub issue, please link here too.
- type: textarea
id: contribution
validations:
required: true
attributes:
label: Your contribution
description: |
Is there any way that you could help, e.g. by submitting a PR? Make sure to read the CONTRIBUTING.MD [readme](https://github.com/hwchase17/langchain/blob/master/.github/CONTRIBUTING.md)

18
.github/ISSUE_TEMPLATE/other.yml vendored Normal file
View File

@@ -0,0 +1,18 @@
name: Other Issue
description: Raise an issue that wouldn't be covered by the other templates.
title: "Issue: <Please write a comprehensive title after the 'Issue: ' prefix>"
labels: [04 - Other]
body:
- type: textarea
attributes:
label: "Issue you'd like to raise."
description: >
Please describe the issue you'd like to raise as clearly as possible.
Make sure to include any relevant links or references.
- type: textarea
attributes:
label: "Suggestion:"
description: >
Please outline a suggestion to improve the issue here.

46
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,46 @@
# Your PR Title (What it does)
<!--
Thank you for contributing to LangChain! Your PR will appear in our next release under the title you set. Please make sure it highlights your valuable contribution.
Replace this with a description of the change, the issue it fixes (if applicable), and relevant context. List any dependencies required for this change.
After you're done, someone will review your PR. They may suggest improvements. If no one reviews your PR within a few days, feel free to @-mention the same people again, as notifications can get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
<!-- If you're adding a new integration, include an integration test and an example notebook showing its use! -->
## Who can review?
Community members can review the PR once tests pass. Tag maintainers/contributors who might be interested:
<!-- For a quicker response, figure out the right person to tag with @
@hwchase17 - project lead
Tracing / Callbacks
- @agola11
Async
- @agola11
DataLoaders
- @eyurtsev
Models
- @hwchase17
- @agola11
Agents / Tools / Toolkits
- @vowelparrot
VectorStores / Retrievers / Memory
- @dev2049
-->

64
.github/actions/poetry_setup/action.yml vendored Normal file
View File

@@ -0,0 +1,64 @@
# An action for setting up poetry install with caching.
# Using a custom action since the default action does not
# take poetry install groups into account.
# Action code from:
# https://github.com/actions/setup-python/issues/505#issuecomment-1273013236
name: poetry-install-with-caching
description: Poetry install with support for caching of dependency groups.
inputs:
python-version:
description: Python version, supporting MAJOR.MINOR only
required: true
poetry-version:
description: Poetry version
required: true
install-command:
description: Command run for installing dependencies
required: false
default: poetry install
cache-key:
description: Cache key to use for manual handling of caching
required: true
working-directory:
description: Directory to run install-command in
required: false
default: ""
runs:
using: composite
steps:
- uses: actions/setup-python@v4
with:
python-version: ${{ inputs.python-version }}
- uses: actions/cache@v3
id: cache-pip
env:
SEGMENT_DOWNLOAD_TIMEOUT_MIN: "15"
with:
path: |
~/.cache/pip
key: pip-${{ runner.os }}-${{ runner.arch }}-py-${{ inputs.python-version }}
- run: pipx install poetry==${{ inputs.poetry-version }} --python python${{ inputs.python-version }}
shell: bash
- uses: actions/cache@v3
id: cache-poetry
env:
SEGMENT_DOWNLOAD_TIMEOUT_MIN: "15"
with:
path: |
~/.cache/pypoetry/virtualenvs
~/.cache/pypoetry/cache
~/.cache/pypoetry/artifacts
key: poetry-${{ runner.os }}-${{ runner.arch }}-py-${{ inputs.python-version }}-poetry-${{ inputs.poetry-version }}-${{ inputs.cache-key }}-${{ hashFiles('poetry.lock') }}
- run: ${{ inputs.install-command }}
working-directory: ${{ inputs.working-directory }}
shell: bash

View File

@@ -6,7 +6,7 @@ on:
pull_request:
env:
POETRY_VERSION: "1.3.1"
POETRY_VERSION: "1.4.2"
jobs:
build:

View File

@@ -6,7 +6,7 @@ on:
pull_request:
env:
POETRY_VERSION: "1.3.1"
POETRY_VERSION: "1.4.2"
jobs:
build:

View File

@@ -10,7 +10,7 @@ on:
- 'pyproject.toml'
env:
POETRY_VERSION: "1.3.1"
POETRY_VERSION: "1.4.2"
jobs:
if_release:
@@ -45,5 +45,5 @@ jobs:
- name: Publish to PyPI
env:
POETRY_PYPI_TOKEN_PYPI: ${{ secrets.PYPI_API_TOKEN }}
run: |
run: |
poetry publish

View File

@@ -6,7 +6,7 @@ on:
pull_request:
env:
POETRY_VERSION: "1.3.1"
POETRY_VERSION: "1.4.2"
jobs:
build:
@@ -18,17 +18,31 @@ jobs:
- "3.9"
- "3.10"
- "3.11"
test_type:
- "core"
- "extended"
name: Python ${{ matrix.python-version }} ${{ matrix.test_type }}
steps:
- uses: actions/checkout@v3
- name: Install poetry
run: pipx install poetry==$POETRY_VERSION
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
uses: "./.github/actions/poetry_setup"
with:
python-version: ${{ matrix.python-version }}
cache: "poetry"
- name: Install dependencies
run: poetry install
- name: Run unit tests
poetry-version: "1.4.2"
cache-key: ${{ matrix.test_type }}
install-command: |
if [ "${{ matrix.test_type }}" == "core" ]; then
echo "Running core tests, installing dependencies with poetry..."
poetry install
else
echo "Running extended tests, installing dependencies with poetry..."
poetry install -E extended_testing
fi
- name: Run ${{matrix.test_type}} tests
run: |
make test
if [ "${{ matrix.test_type }}" == "core" ]; then
make test
else
make extended_tests
fi
shell: bash

8
.gitignore vendored
View File

@@ -1,3 +1,4 @@
.vs/
.vscode/
.idea/
# Byte-compiled / optimized / DLL files
@@ -142,3 +143,10 @@ wandb/
# asdf tool versions
.tool-versions
/.ruff_cache/
*.pkl
*.bin
# integration test artifacts
data_map*
\[('_type', 'fake'), ('stop', None)]

26
.readthedocs.yaml Normal file
View File

@@ -0,0 +1,26 @@
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Set the version of Python and other tools you might need
build:
os: ubuntu-22.04
tools:
python: "3.11"
# Build documentation in the docs/ directory with Sphinx
sphinx:
configuration: docs/conf.py
# If using Sphinx, optionally build your docs in additional formats such as PDF
# formats:
# - pdf
# Optionally declare the Python requirements required to build your docs
python:
install:
- requirements: docs/requirements.txt
- method: pip
path: .

View File

@@ -1,5 +1,7 @@
# This is a Dockerfile for running unit tests
ARG POETRY_HOME=/opt/poetry
# Use the Python base image
FROM python:3.11.2-bullseye AS builder
@@ -7,7 +9,7 @@ FROM python:3.11.2-bullseye AS builder
ARG POETRY_VERSION=1.4.2
# Define the directory to install Poetry to (default is /opt/poetry)
ARG POETRY_HOME=/opt/poetry
ARG POETRY_HOME
# Create a Python virtual environment for Poetry and install it
RUN python3 -m venv ${POETRY_HOME} && \
@@ -23,6 +25,8 @@ WORKDIR /app
# Use a multi-stage build to install dependencies
FROM builder AS dependencies
ARG POETRY_HOME
# Copy only the dependency files for installation
COPY pyproject.toml poetry.lock poetry.toml ./

View File

@@ -1,4 +1,4 @@
.PHONY: all clean format lint test tests test_watch integration_tests docker_tests help
.PHONY: all clean format lint test tests test_watch integration_tests docker_tests help extended_tests
all: help
@@ -32,11 +32,16 @@ lint lint_diff:
poetry run black $(PYTHON_FILES) --check
poetry run ruff .
TEST_FILE ?= tests/unit_tests/
test:
poetry run pytest tests/unit_tests
poetry run pytest $(TEST_FILE)
tests:
poetry run pytest tests/unit_tests
poetry run pytest $(TEST_FILE)
extended_tests:
poetry run pytest --only-extended tests/unit_tests
test_watch:
poetry run ptw --now . -- tests/unit_tests
@@ -50,13 +55,16 @@ docker_tests:
help:
@echo '----'
@echo 'coverage - run unit tests and generate coverage report'
@echo 'docs_build - build the documentation'
@echo 'docs_clean - clean the documentation build artifacts'
@echo 'docs_linkcheck - run linkchecker on the documentation'
@echo 'format - run code formatters'
@echo 'lint - run linters'
@echo 'test - run unit tests'
@echo 'test_watch - run unit tests in watch mode'
@echo 'integration_tests - run integration tests'
@echo 'docker_tests - run unit tests in docker'
@echo 'coverage - run unit tests and generate coverage report'
@echo 'docs_build - build the documentation'
@echo 'docs_clean - clean the documentation build artifacts'
@echo 'docs_linkcheck - run linkchecker on the documentation'
@echo 'format - run code formatters'
@echo 'lint - run linters'
@echo 'test - run unit tests'
@echo 'test - run unit tests'
@echo 'test TEST_FILE=<test_file> - run all tests in file'
@echo 'extended_tests - run only extended unit tests'
@echo 'test_watch - run unit tests in watch mode'
@echo 'integration_tests - run integration tests'
@echo 'docker_tests - run unit tests in docker'

View File

@@ -2,7 +2,19 @@
⚡ Building applications with LLMs through composability ⚡
[![lint](https://github.com/hwchase17/langchain/actions/workflows/lint.yml/badge.svg)](https://github.com/hwchase17/langchain/actions/workflows/lint.yml) [![test](https://github.com/hwchase17/langchain/actions/workflows/test.yml/badge.svg)](https://github.com/hwchase17/langchain/actions/workflows/test.yml) [![linkcheck](https://github.com/hwchase17/langchain/actions/workflows/linkcheck.yml/badge.svg)](https://github.com/hwchase17/langchain/actions/workflows/linkcheck.yml) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/langchainai.svg?style=social&label=Follow%20%40LangChainAI)](https://twitter.com/langchainai) [![](https://dcbadge.vercel.app/api/server/6adMQxSpJS?compact=true&style=flat)](https://discord.gg/6adMQxSpJS)
[![lint](https://github.com/hwchase17/langchain/actions/workflows/lint.yml/badge.svg)](https://github.com/hwchase17/langchain/actions/workflows/lint.yml)
[![test](https://github.com/hwchase17/langchain/actions/workflows/test.yml/badge.svg)](https://github.com/hwchase17/langchain/actions/workflows/test.yml)
[![linkcheck](https://github.com/hwchase17/langchain/actions/workflows/linkcheck.yml/badge.svg)](https://github.com/hwchase17/langchain/actions/workflows/linkcheck.yml)
[![Downloads](https://static.pepy.tech/badge/langchain/month)](https://pepy.tech/project/langchain)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Twitter](https://img.shields.io/twitter/url/https/twitter.com/langchainai.svg?style=social&label=Follow%20%40LangChainAI)](https://twitter.com/langchainai)
[![](https://dcbadge.vercel.app/api/server/6adMQxSpJS?compact=true&style=flat)](https://discord.gg/6adMQxSpJS)
[![Open in Dev Containers](https://img.shields.io/static/v1?label=Dev%20Containers&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/hwchase17/langchain)
[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/hwchase17/langchain)
[![GitHub star chart](https://img.shields.io/github/stars/hwchase17/langchain?style=social)](https://star-history.com/#hwchase17/langchain)
Looking for the JS/TS version? Check out [LangChain.js](https://github.com/hwchase17/langchainjs).
**Production Support:** As you move your LangChains into production, we'd love to offer more comprehensive support.
Please fill out [this form](https://forms.gle/57d8AmXBYp8PP8tZA) and we'll set up a dedicated support Slack channel.
@@ -10,15 +22,14 @@ Please fill out [this form](https://forms.gle/57d8AmXBYp8PP8tZA) and we'll set u
## Quick Install
`pip install langchain`
or
`conda install langchain -c conda-forge`
## 🤔 What is this?
Large language models (LLMs) are emerging as a transformative technology, enabling
developers to build applications that they previously could not.
But using these LLMs in isolation is often not enough to
create a truly powerful app - the real power comes when you can combine them with other sources of computation or knowledge.
Large language models (LLMs) are emerging as a transformative technology, enabling developers to build applications that they previously could not. However, using these LLMs in isolation is often insufficient for creating a truly powerful app - the real power comes when you can combine them with other sources of computation or knowledge.
This library is aimed at assisting in the development of those types of applications. Common examples of these types of applications include:
This library aims to assist in the development of those types of applications. Common examples of these applications include:
**❓ Question Answering over specific documents**
@@ -51,32 +62,32 @@ These are, in increasing order of complexity:
**📃 LLMs and Prompts:**
This includes prompt management, prompt optimization, generic interface for all LLMs, and common utilities for working with LLMs.
This includes prompt management, prompt optimization, a generic interface for all LLMs, and common utilities for working with LLMs.
**🔗 Chains:**
Chains go beyond just a single LLM call, and are sequences of calls (whether to an LLM or a different utility). LangChain provides a standard interface for chains, lots of integrations with other tools, and end-to-end chains for common applications.
Chains go beyond a single LLM call and involve sequences of calls (whether to an LLM or a different utility). LangChain provides a standard interface for chains, lots of integrations with other tools, and end-to-end chains for common applications.
**📚 Data Augmented Generation:**
Data Augmented Generation involves specific types of chains that first interact with an external datasource to fetch data to use in the generation step. Examples of this include summarization of long pieces of text and question/answering over specific data sources.
Data Augmented Generation involves specific types of chains that first interact with an external data source to fetch data for use in the generation step. Examples include summarization of long pieces of text and question/answering over specific data sources.
**🤖 Agents:**
Agents involve an LLM making decisions about which Actions to take, taking that Action, seeing an Observation, and repeating that until done. LangChain provides a standard interface for agents, a selection of agents to choose from, and examples of end to end agents.
Agents involve an LLM making decisions about which Actions to take, taking that Action, seeing an Observation, and repeating that until done. LangChain provides a standard interface for agents, a selection of agents to choose from, and examples of end-to-end agents.
**🧠 Memory:**
Memory is the concept of persisting state between calls of a chain/agent. LangChain provides a standard interface for memory, a collection of memory implementations, and examples of chains/agents that use memory.
Memory refers to persisting state between calls of a chain/agent. LangChain provides a standard interface for memory, a collection of memory implementations, and examples of chains/agents that use memory.
**🧐 Evaluation:**
[BETA] Generative models are notoriously hard to evaluate with traditional metrics. One new way of evaluating them is using language models themselves to do the evaluation. LangChain provides some prompts/chains for assisting in this.
For more information on these concepts, please see our [full documentation](https://langchain.readthedocs.io/en/latest/?).
For more information on these concepts, please see our [full documentation](https://langchain.readthedocs.io/en/latest/).
## 💁 Contributing
As an open source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infra, or better documentation.
As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.
For detailed information on how to contribute, see [here](.github/CONTRIBUTING.md).

BIN
docs/_static/DataberryDashboard.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

BIN
docs/_static/MetalDash.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 MiB

View File

@@ -11,3 +11,7 @@ pre {
max-width: 2560px !important;
}
}
#my-component-root *, #headlessui-portal-root * {
z-index: 1000000000000;
}

58
docs/_static/js/mendablesearch.js vendored Normal file
View File

@@ -0,0 +1,58 @@
document.addEventListener('DOMContentLoaded', () => {
// Load the external dependencies
function loadScript(src, onLoadCallback) {
const script = document.createElement('script');
script.src = src;
script.onload = onLoadCallback;
document.head.appendChild(script);
}
function createRootElement() {
const rootElement = document.createElement('div');
rootElement.id = 'my-component-root';
document.body.appendChild(rootElement);
return rootElement;
}
function initializeMendable() {
const rootElement = createRootElement();
const { MendableFloatingButton } = Mendable;
const iconSpan1 = React.createElement('span', {
}, '🦜');
const iconSpan2 = React.createElement('span', {
}, '🔗');
const icon = React.createElement('p', {
style: { color: '#ffffff', fontSize: '22px',width: '48px', height: '48px', margin: '0px', padding: '0px', display: 'flex', alignItems: 'center', justifyContent: 'center', textAlign: 'center' },
}, [iconSpan1, iconSpan2]);
const mendableFloatingButton = React.createElement(
MendableFloatingButton,
{
style: { darkMode: false, accentColor: '#010810' },
floatingButtonStyle: { color: '#ffffff', backgroundColor: '#010810' },
anon_key: '82842b36-3ea6-49b2-9fb8-52cfc4bde6bf', // Mendable Search Public ANON key, ok to be public
messageSettings: {
openSourcesInNewTab: false,
},
icon: icon,
}
);
ReactDOM.render(mendableFloatingButton, rootElement);
}
loadScript('https://unpkg.com/react@17/umd/react.production.min.js', () => {
loadScript('https://unpkg.com/react-dom@17/umd/react-dom.production.min.js', () => {
loadScript('https://unpkg.com/@mendable/search@0.0.93/dist/umd/mendable.min.js', initializeMendable);
});
});
});

View File

@@ -103,5 +103,10 @@ html_static_path = ["_static"]
html_css_files = [
"css/custom.css",
]
html_js_files = [
"js/mendablesearch.js",
]
nb_execution_mode = "off"
myst_enable_extensions = ["colon_fence"]

View File

@@ -1,14 +1,10 @@
# Deployments
So you've made a really cool chain - now what? How do you deploy it and make it easily sharable with the world?
So, you've created a really cool chain - now what? How do you deploy it and make it easily shareable with the world?
This section covers several options for that.
Note that these are meant as quick deployment options for prototypes and demos, and not for production systems.
If you are looking for help with deployment of a production system, please contact us directly.
This section covers several options for that. Note that these options are meant for quick deployment of prototypes and demos, not for production systems. If you need help with the deployment of a production system, please contact us directly.
What follows is a list of template GitHub repositories aimed that are intended to be
very easy to fork and modify to use your chain.
This is far from an exhaustive list of options, and we are EXTREMELY open to contributions here.
What follows is a list of template GitHub repositories designed to be easily forked and modified to use your chain. This list is far from exhaustive, and we are EXTREMELY open to contributions here.
## [Streamlit](https://github.com/hwchase17/langchain-streamlit-template)
@@ -33,10 +29,34 @@ It implements a Question Answering app and contains instructions for deploying t
A minimal example on how to run LangChain on Vercel using Flask.
## [Kinsta](https://github.com/kinsta/hello-world-langchain)
A minimal example on how to deploy LangChain to [Kinsta](https://kinsta.com) using Flask.
## [Fly.io](https://github.com/fly-apps/hello-fly-langchain)
A minimal example of how to deploy LangChain to [Fly.io](https://fly.io/) using Flask.
## [Digitalocean App Platform](https://github.com/homanp/digitalocean-langchain)
A minimal example on how to deploy LangChain to DigitalOcean App Platform.
## [Google Cloud Run](https://github.com/homanp/gcp-langchain)
A minimal example on how to deploy LangChain to Google Cloud Run.
## [SteamShip](https://github.com/steamship-core/steamship-langchain/)
This repository contains LangChain adapters for Steamship, enabling LangChain developers to rapidly deploy their apps on Steamship.
This includes: production ready endpoints, horizontal scaling across dependencies, persistant storage of app state, multi-tenancy support, etc.
This repository contains LangChain adapters for Steamship, enabling LangChain developers to rapidly deploy their apps on Steamship. This includes: production-ready endpoints, horizontal scaling across dependencies, persistent storage of app state, multi-tenancy support, etc.
## [Langchain-serve](https://github.com/jina-ai/langchain-serve)
This repository allows users to serve local chains and agents as RESTful, gRPC, or Websocket APIs thanks to [Jina](https://docs.jina.ai/). Deploy your chains & agents with ease and enjoy independent scaling, serverless and autoscaling APIs, as well as a Streamlit playground on Jina AI Cloud.
This repository allows users to serve local chains and agents as RESTful, gRPC, or WebSocket APIs, thanks to [Jina](https://docs.jina.ai/). Deploy your chains & agents with ease and enjoy independent scaling, serverless and autoscaling APIs, as well as a Streamlit playground on Jina AI Cloud.
## [BentoML](https://github.com/ssheng/BentoChain)
This repository provides an example of how to deploy a LangChain application with [BentoML](https://github.com/bentoml/BentoML). BentoML is a framework that enables the containerization of machine learning applications as standard OCI images. BentoML also allows for the automatic generation of OpenAPI and gRPC endpoints. With BentoML, you can integrate models from all popular ML frameworks and deploy them as microservices running on the most optimal hardware and scaling independently.
## [Databutton](https://databutton.com/home?new-data-app=true)
These templates serve as examples of how to build, deploy, and share LangChain applications using Databutton. You can create user interfaces with Streamlit, automate tasks by scheduling Python code, and store files and data in the built-in store. Examples include a Chatbot interface with conversational memory, a Personal search engine, and a starter template for LangChain apps. Deploying and sharing is just one click away.

View File

@@ -3,6 +3,25 @@ LangChain Ecosystem
Guides for how other companies/products can be used with LangChain
Groups
----------
LangChain provides integration with many LLMs and systems:
- `LLM Providers <./modules/models/llms/integrations.html>`_
- `Chat Model Providers <./modules/models/chat/integrations.html>`_
- `Text Embedding Model Providers <./modules/models/text_embedding.html>`_
- `Document Loader Integrations <./modules/indexes/document_loaders.html>`_
- `Text Splitter Integrations <./modules/indexes/text_splitters.html>`_
- `Vectorstore Providers <./modules/indexes/vectorstores.html>`_
- `Retriever Providers <./modules/indexes/retrievers.html>`_
- `Tool Providers <./modules/agents/tools.html>`_
- `Toolkit Integrations <./modules/agents/toolkits.html>`_
Companies / Products
----------
.. toctree::
:maxdepth: 1
:glob:

View File

@@ -61,7 +61,6 @@
"from datetime import datetime\n",
"\n",
"from langchain.llms import OpenAI\n",
"from langchain.callbacks.base import CallbackManager\n",
"from langchain.callbacks import AimCallbackHandler, StdOutCallbackHandler"
]
},
@@ -109,8 +108,8 @@
" experiment_name=\"scenario 1: OpenAI LLM\",\n",
")\n",
"\n",
"manager = CallbackManager([StdOutCallbackHandler(), aim_callback])\n",
"llm = OpenAI(temperature=0, callback_manager=manager, verbose=True)"
"callbacks = [StdOutCallbackHandler(), aim_callback]\n",
"llm = OpenAI(temperature=0, callbacks=callbacks)"
]
},
{
@@ -177,7 +176,7 @@
"Title: {title}\n",
"Playwright: This is a synopsis for the above play:\"\"\"\n",
"prompt_template = PromptTemplate(input_variables=[\"title\"], template=template)\n",
"synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callback_manager=manager)\n",
"synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callbacks=callbacks)\n",
"\n",
"test_prompts = [\n",
" {\"title\": \"documentary about good video games that push the boundary of game design\"},\n",
@@ -249,13 +248,12 @@
],
"source": [
"# scenario 3 - Agent with Tools\n",
"tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm, callback_manager=manager)\n",
"tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm, callbacks=callbacks)\n",
"agent = initialize_agent(\n",
" tools,\n",
" llm,\n",
" agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n",
" callback_manager=manager,\n",
" verbose=True,\n",
" callbacks=callbacks,\n",
")\n",
"agent.run(\n",
" \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"\n",

View File

@@ -0,0 +1,15 @@
# AnalyticDB
This page covers how to use the AnalyticDB ecosystem within LangChain.
### VectorStore
There exists a wrapper around AnalyticDB, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
To import this vectorstore:
```python
from langchain.vectorstores import AnalyticDB
```
For a more detailed walkthrough of the AnalyticDB wrapper, see [this notebook](../modules/indexes/vectorstores/examples/analyticdb.ipynb)

View File

@@ -0,0 +1,17 @@
# Anyscale
This page covers how to use the Anyscale ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Anyscale wrappers.
## Installation and Setup
- Get an Anyscale Service URL, route and API key and set them as environment variables (`ANYSCALE_SERVICE_URL`,`ANYSCALE_SERVICE_ROUTE`, `ANYSCALE_SERVICE_TOKEN`).
- Please see [the Anyscale docs](https://docs.anyscale.com/productionize/services-v2/get-started) for more details.
## Wrappers
### LLM
There exists an Anyscale LLM wrapper, which you can access with
```python
from langchain.llms import Anyscale
```

View File

@@ -19,7 +19,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Getting API Credentials\n",
"## Getting API Credentials\n",
"\n",
"We'll be using quite some APIs in this notebook, here is a list and where to get them:\n",
"\n",
@@ -47,7 +47,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Setting Up"
"## Setting Up"
]
},
{
@@ -79,7 +79,6 @@
"source": [
"from datetime import datetime\n",
"from langchain.callbacks import ClearMLCallbackHandler, StdOutCallbackHandler\n",
"from langchain.callbacks.base import CallbackManager\n",
"from langchain.llms import OpenAI\n",
"\n",
"# Setup and use the ClearML Callback\n",
@@ -93,9 +92,9 @@
" complexity_metrics=True,\n",
" stream_logs=True\n",
")\n",
"manager = CallbackManager([StdOutCallbackHandler(), clearml_callback])\n",
"callbacks = [StdOutCallbackHandler(), clearml_callback]\n",
"# Get the OpenAI model ready to go\n",
"llm = OpenAI(temperature=0, callback_manager=manager, verbose=True)"
"llm = OpenAI(temperature=0, callbacks=callbacks)"
]
},
{
@@ -103,7 +102,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Scenario 1: Just an LLM\n",
"## Scenario 1: Just an LLM\n",
"\n",
"First, let's just run a single LLM a few times and capture the resulting prompt-answer conversation in ClearML"
]
@@ -361,7 +360,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Scenario 2: Creating a agent with tools\n",
"## Scenario 2: Creating an agent with tools\n",
"\n",
"To show a more advanced workflow, let's create an agent with access to tools. The way ClearML tracks the results is not different though, only the table will look slightly different as there are other types of actions taken when compared to the earlier, simpler example.\n",
"\n",
@@ -523,13 +522,12 @@
"from langchain.agents import AgentType\n",
"\n",
"# SCENARIO 2 - Agent with Tools\n",
"tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm, callback_manager=manager)\n",
"tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm, callbacks=callbacks)\n",
"agent = initialize_agent(\n",
" tools,\n",
" llm,\n",
" agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n",
" callback_manager=manager,\n",
" verbose=True,\n",
" callbacks=callbacks,\n",
")\n",
"agent.run(\n",
" \"Who is the wife of the person who sang summer of 69?\"\n",
@@ -542,7 +540,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Tips and Next Steps\n",
"## Tips and Next Steps\n",
"\n",
"- Make sure you always use a unique `name` argument for the `clearml_callback.flush_tracker` function. If not, the model parameters used for a run will override the previous run!\n",
"\n",

View File

@@ -0,0 +1,347 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Comet"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](https://user-images.githubusercontent.com/7529846/230328046-a8b18c51-12e3-4617-9b39-97614a571a2d.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this guide we will demonstrate how to track your Langchain Experiments, Evaluation Metrics, and LLM Sessions with [Comet](https://www.comet.com/site/?utm_source=langchain&utm_medium=referral&utm_campaign=comet_notebook). \n",
"\n",
"<a target=\"_blank\" href=\"https://colab.research.google.com/github/hwchase17/langchain/blob/master/docs/ecosystem/comet_tracking.ipynb\">\n",
" <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
"</a>\n",
"\n",
"**Example Project:** [Comet with LangChain](https://www.comet.com/examples/comet-example-langchain/view/b5ZThK6OFdhKWVSP3fDfRtrNF/panels?utm_source=langchain&utm_medium=referral&utm_campaign=comet_notebook)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img width=\"1280\" alt=\"comet-langchain\" src=\"https://user-images.githubusercontent.com/7529846/230326720-a9711435-9c6f-4edb-a707-94b67271ab25.png\">\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Install Comet and Dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install comet_ml langchain openai google-search-results spacy textstat pandas\n",
"\n",
"import sys\n",
"!{sys.executable} -m spacy download en_core_web_sm"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Initialize Comet and Set your Credentials"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can grab your [Comet API Key here](https://www.comet.com/signup?utm_source=langchain&utm_medium=referral&utm_campaign=comet_notebook) or click the link after initializing Comet"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import comet_ml\n",
"\n",
"comet_ml.init(project_name=\"comet-example-langchain\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Set OpenAI and SerpAPI credentials"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You will need an [OpenAI API Key](https://platform.openai.com/account/api-keys) and a [SerpAPI API Key](https://serpapi.com/dashboard) to run the following examples"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"\n",
"os.environ[\"OPENAI_API_KEY\"] = \"...\"\n",
"#os.environ[\"OPENAI_ORGANIZATION\"] = \"...\"\n",
"os.environ[\"SERPAPI_API_KEY\"] = \"...\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Scenario 1: Using just an LLM"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"from langchain.callbacks import CometCallbackHandler, StdOutCallbackHandler\n",
"from langchain.llms import OpenAI\n",
"\n",
"comet_callback = CometCallbackHandler(\n",
" project_name=\"comet-example-langchain\",\n",
" complexity_metrics=True,\n",
" stream_logs=True,\n",
" tags=[\"llm\"],\n",
" visualizations=[\"dep\"],\n",
")\n",
"callbacks = [StdOutCallbackHandler(), comet_callback]\n",
"llm = OpenAI(temperature=0.9, callbacks=callbacks, verbose=True)\n",
"\n",
"llm_result = llm.generate([\"Tell me a joke\", \"Tell me a poem\", \"Tell me a fact\"] * 3)\n",
"print(\"LLM result\", llm_result)\n",
"comet_callback.flush_tracker(llm, finish=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Scenario 2: Using an LLM in a Chain"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from langchain.callbacks import CometCallbackHandler, StdOutCallbackHandler\n",
"from langchain.chains import LLMChain\n",
"from langchain.llms import OpenAI\n",
"from langchain.prompts import PromptTemplate\n",
"\n",
"comet_callback = CometCallbackHandler(\n",
" complexity_metrics=True,\n",
" project_name=\"comet-example-langchain\",\n",
" stream_logs=True,\n",
" tags=[\"synopsis-chain\"],\n",
")\n",
"callbacks = [StdOutCallbackHandler(), comet_callback]\n",
"llm = OpenAI(temperature=0.9, callbacks=callbacks)\n",
"\n",
"template = \"\"\"You are a playwright. Given the title of play, it is your job to write a synopsis for that title.\n",
"Title: {title}\n",
"Playwright: This is a synopsis for the above play:\"\"\"\n",
"prompt_template = PromptTemplate(input_variables=[\"title\"], template=template)\n",
"synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callbacks=callbacks)\n",
"\n",
"test_prompts = [{\"title\": \"Documentary about Bigfoot in Paris\"}]\n",
"print(synopsis_chain.apply(test_prompts))\n",
"comet_callback.flush_tracker(synopsis_chain, finish=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Scenario 3: Using An Agent with Tools "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import initialize_agent, load_tools\n",
"from langchain.callbacks import CometCallbackHandler, StdOutCallbackHandler\n",
"from langchain.llms import OpenAI\n",
"\n",
"comet_callback = CometCallbackHandler(\n",
" project_name=\"comet-example-langchain\",\n",
" complexity_metrics=True,\n",
" stream_logs=True,\n",
" tags=[\"agent\"],\n",
")\n",
"callbacks = [StdOutCallbackHandler(), comet_callback]\n",
"llm = OpenAI(temperature=0.9, callbacks=callbacks)\n",
"\n",
"tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm, callbacks=callbacks)\n",
"agent = initialize_agent(\n",
" tools,\n",
" llm,\n",
" agent=\"zero-shot-react-description\",\n",
" callbacks=callbacks,\n",
" verbose=True,\n",
")\n",
"agent.run(\n",
" \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"\n",
")\n",
"comet_callback.flush_tracker(agent, finish=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Scenario 4: Using Custom Evaluation Metrics"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `CometCallbackManager` also allows you to define and use Custom Evaluation Metrics to assess generated outputs from your model. Let's take a look at how this works. \n",
"\n",
"\n",
"In the snippet below, we will use the [ROUGE](https://huggingface.co/spaces/evaluate-metric/rouge) metric to evaluate the quality of a generated summary of an input prompt. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install rouge-score"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from rouge_score import rouge_scorer\n",
"\n",
"from langchain.callbacks import CometCallbackHandler, StdOutCallbackHandler\n",
"from langchain.chains import LLMChain\n",
"from langchain.llms import OpenAI\n",
"from langchain.prompts import PromptTemplate\n",
"\n",
"\n",
"class Rouge:\n",
" def __init__(self, reference):\n",
" self.reference = reference\n",
" self.scorer = rouge_scorer.RougeScorer([\"rougeLsum\"], use_stemmer=True)\n",
"\n",
" def compute_metric(self, generation, prompt_idx, gen_idx):\n",
" prediction = generation.text\n",
" results = self.scorer.score(target=self.reference, prediction=prediction)\n",
"\n",
" return {\n",
" \"rougeLsum_score\": results[\"rougeLsum\"].fmeasure,\n",
" \"reference\": self.reference,\n",
" }\n",
"\n",
"\n",
"reference = \"\"\"\n",
"The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building.\n",
"It was the first structure to reach a height of 300 metres.\n",
"\n",
"It is now taller than the Chrysler Building in New York City by 5.2 metres (17 ft)\n",
"Excluding transmitters, the Eiffel Tower is the second tallest free-standing structure in France .\n",
"\"\"\"\n",
"rouge_score = Rouge(reference=reference)\n",
"\n",
"template = \"\"\"Given the following article, it is your job to write a summary.\n",
"Article:\n",
"{article}\n",
"Summary: This is the summary for the above article:\"\"\"\n",
"prompt_template = PromptTemplate(input_variables=[\"article\"], template=template)\n",
"\n",
"comet_callback = CometCallbackHandler(\n",
" project_name=\"comet-example-langchain\",\n",
" complexity_metrics=False,\n",
" stream_logs=True,\n",
" tags=[\"custom_metrics\"],\n",
" custom_metrics=rouge_score.compute_metric,\n",
")\n",
"callbacks = [StdOutCallbackHandler(), comet_callback]\n",
"llm = OpenAI(temperature=0.9)\n",
"\n",
"synopsis_chain = LLMChain(llm=llm, prompt=prompt_template)\n",
"\n",
"test_prompts = [\n",
" {\n",
" \"article\": \"\"\"\n",
" The tower is 324 metres (1,063 ft) tall, about the same height as\n",
" an 81-storey building, and the tallest structure in Paris. Its base is square,\n",
" measuring 125 metres (410 ft) on each side.\n",
" During its construction, the Eiffel Tower surpassed the\n",
" Washington Monument to become the tallest man-made structure in the world,\n",
" a title it held for 41 years until the Chrysler Building\n",
" in New York City was finished in 1930.\n",
"\n",
" It was the first structure to reach a height of 300 metres.\n",
" Due to the addition of a broadcasting aerial at the top of the tower in 1957,\n",
" it is now taller than the Chrysler Building by 5.2 metres (17 ft).\n",
"\n",
" Excluding transmitters, the Eiffel Tower is the second tallest\n",
" free-standing structure in France after the Millau Viaduct.\n",
" \"\"\"\n",
" }\n",
"]\n",
"print(synopsis_chain.apply(test_prompts, callbacks=callbacks))\n",
"comet_callback.flush_tracker(synopsis_chain, finish=True)"
]
}
],
"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.15"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,25 @@
# Databerry
This page covers how to use the [Databerry](https://databerry.ai) within LangChain.
## What is Databerry?
Databerry is an [open source](https://github.com/gmpetrov/databerry) document retrievial platform that helps to connect your personal data with Large Language Models.
![Databerry](../_static/DataberryDashboard.png)
## Quick start
Retrieving documents stored in Databerry from LangChain is very easy!
```python
from langchain.retrievers import DataberryRetriever
retriever = DataberryRetriever(
datastore_url="https://api.databerry.ai/query/clg1xg2h80000l708dymr0fxc",
# api_key="DATABERRY_API_KEY", # optional if datastore is public
# top_k=10 # optional
)
docs = retriever.get_relevant_documents("What's Databerry?")
```

View File

@@ -8,8 +8,9 @@ This page covers how to use the Deep Lake ecosystem within LangChain.
## More Resources
1. [Ultimate Guide to LangChain & Deep Lake: Build ChatGPT to Answer Questions on Your Financial Data](https://www.activeloop.ai/resources/ultimate-guide-to-lang-chain-deep-lake-build-chat-gpt-to-answer-questions-on-your-financial-data/)
1. Here is [whitepaper](https://www.deeplake.ai/whitepaper) and [academic paper](https://arxiv.org/pdf/2209.10785.pdf) for Deep Lake
2. Here is a set of additional resources available for review: [Deep Lake](https://github.com/activeloopai/deeplake), [Getting Started](https://docs.activeloop.ai/getting-started) and [Tutorials](https://docs.activeloop.ai/hub-tutorials)
2. [Twitter the-algorithm codebase analysis with Deep Lake](../use_cases/code/twitter-the-algorithm-analysis-deeplake.ipynb)
3. Here is [whitepaper](https://www.deeplake.ai/whitepaper) and [academic paper](https://arxiv.org/pdf/2209.10785.pdf) for Deep Lake
4. Here is a set of additional resources available for review: [Deep Lake](https://github.com/activeloopai/deeplake), [Getting Started](https://docs.activeloop.ai/getting-started) and [Tutorials](https://docs.activeloop.ai/hub-tutorials)
## Installation and Setup
- Install the Python package with `pip install deeplake`

View File

@@ -1,21 +1,22 @@
# GPT4All
This page covers how to use the `GPT4All` wrapper within LangChain.
It is broken into two parts: installation and setup, and then usage with an example.
This page covers how to use the `GPT4All` wrapper within LangChain. The tutorial is divided into two parts: installation and setup, followed by usage with an example.
## Installation and Setup
- Install the Python package with `pip install pyllamacpp`
- Download a [GPT4All model](https://github.com/nomic-ai/gpt4all) and place it in your desired directory
- Download a [GPT4All model](https://github.com/nomic-ai/pyllamacpp#supported-model) and place it in your desired directory
## Usage
### GPT4All
To use the GPT4All wrapper, you need to provide the path to the pre-trained model file and the model's configuration.
```python
from langchain.llms import GPT4All
# Instantiate the model
# Instantiate the model. Callbacks support token-wise streaming
model = GPT4All(model="./models/gpt4all-model.bin", n_ctx=512, n_threads=8)
# Generate text
@@ -24,14 +25,24 @@ response = model("Once upon a time, ")
You can also customize the generation parameters, such as n_predict, temp, top_p, top_k, and others.
Example:
To stream the model's predictions, add in a CallbackManager.
```python
model = GPT4All(model="./models/gpt4all-model.bin", n_predict=55, temp=0)
response = model("Once upon a time, ")
from langchain.llms import GPT4All
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
# There are many CallbackHandlers supported, such as
# from langchain.callbacks.streamlit import StreamlitCallbackHandler
callbacks = [StreamingStdOutCallbackHandler()]
model = GPT4All(model="./models/gpt4all-model.bin", n_ctx=512, n_threads=8)
# Generate text. Tokens are streamed through the callback manager.
model("Once upon a time, ", callbacks=callbacks)
```
## Model File
You can find links to model file downloads at the [GPT4all](https://github.com/nomic-ai/gpt4all) repository. They will need to be converted to `ggml` format to work, as specified in the [pyllamacpp](https://github.com/nomic-ai/pyllamacpp) repository.
You can find links to model file downloads in the [pyllamacpp](https://github.com/nomic-ai/pyllamacpp) repository.
For a more detailed walkthrough of this, see [this notebook](../modules/models/llms/integrations/gpt4all.ipynb)
For a more detailed walkthrough of this, see [this notebook](../modules/models/llms/integrations/gpt4all.ipynb)

View File

@@ -1,6 +1,6 @@
# Graphsignal
This page covers how to use the Graphsignal ecosystem to trace and monitor LangChain.
This page covers how to use [Graphsignal](https://app.graphsignal.com) to trace and monitor LangChain. Graphsignal enables full visibility into your application. It provides latency breakdowns by chains and tools, exceptions with full context, data monitoring, compute/GPU utilization, OpenAI cost analytics, and more.
## Installation and Setup
@@ -10,7 +10,7 @@ This page covers how to use the Graphsignal ecosystem to trace and monitor LangC
## Tracing and Monitoring
Graphsignal automatically instruments and starts tracing and monitoring chains. Traces, metrics and errors are then available in your [Graphsignal dashboard](https://app.graphsignal.com/). No prompts or other sensitive data are sent to Graphsignal cloud, only statistics and metadata.
Graphsignal automatically instruments and starts tracing and monitoring chains. Traces and metrics are then available in your [Graphsignal dashboards](https://app.graphsignal.com).
Initialize the tracer by providing a deployment name:
@@ -20,7 +20,13 @@ import graphsignal
graphsignal.configure(deployment='my-langchain-app-prod')
```
In order to trace full runs and see a breakdown by chains and tools, you can wrap the calling routine or use a decorator:
To additionally trace any function or code, you can use a decorator or a context manager:
```python
@graphsignal.trace_function
def handle_request():
chain.run("some initial text")
```
```python
with graphsignal.start_trace('my-chain'):

23
docs/ecosystem/lancedb.md Normal file
View File

@@ -0,0 +1,23 @@
# LanceDB
This page covers how to use [LanceDB](https://github.com/lancedb/lancedb) within LangChain.
It is broken into two parts: installation and setup, and then references to specific LanceDB wrappers.
## Installation and Setup
- Install the Python SDK with `pip install lancedb`
## Wrappers
### VectorStore
There exists a wrapper around LanceDB databases, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
To import this vectorstore:
```python
from langchain.vectorstores import LanceDB
```
For a more detailed walkthrough of the LanceDB wrapper, see [this notebook](../modules/indexes/vectorstores/examples/lancedb.ipynb)

26
docs/ecosystem/metal.md Normal file
View File

@@ -0,0 +1,26 @@
# Metal
This page covers how to use [Metal](https://getmetal.io) within LangChain.
## What is Metal?
Metal is a managed retrieval & memory platform built for production. Easily index your data into `Metal` and run semantic search and retrieval on it.
![Metal](../_static/MetalDash.png)
## Quick start
Get started by [creating a Metal account](https://app.getmetal.io/signup).
Then, you can easily take advantage of the `MetalRetriever` class to start retrieving your data for semantic search, prompting context, etc. This class takes a `Metal` instance and a dictionary of parameters to pass to the Metal API.
```python
from langchain.retrievers import MetalRetriever
from metal_sdk.metal import Metal
metal = Metal("API_KEY", "CLIENT_ID", "INDEX_ID");
retriever = MetalRetriever(metal, params={"limit": 2})
docs = retriever.get_relevant_documents("search term")
```

View File

@@ -0,0 +1,172 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# MLflow\n",
"\n",
"This notebook goes over how to track your LangChain experiments into your MLflow Server"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install azureml-mlflow\n",
"!pip install pandas\n",
"!pip install textstat\n",
"!pip install spacy\n",
"!pip install openai\n",
"!pip install google-search-results\n",
"!python -m spacy download en_core_web_sm"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"os.environ[\"MLFLOW_TRACKING_URI\"] = \"\"\n",
"os.environ[\"OPENAI_API_KEY\"] = \"\"\n",
"os.environ[\"SERPAPI_API_KEY\"] = \"\"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from langchain.callbacks import MlflowCallbackHandler\n",
"from langchain.llms import OpenAI"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\"\"\"Main function.\n",
"\n",
"This function is used to try the callback handler.\n",
"Scenarios:\n",
"1. OpenAI LLM\n",
"2. Chain with multiple SubChains on multiple generations\n",
"3. Agent with Tools\n",
"\"\"\"\n",
"mlflow_callback = MlflowCallbackHandler()\n",
"llm = OpenAI(model_name=\"gpt-3.5-turbo\", temperature=0, callbacks=[mlflow_callback], verbose=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# SCENARIO 1 - LLM\n",
"llm_result = llm.generate([\"Tell me a joke\"])\n",
"\n",
"mlflow_callback.flush_tracker(llm)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from langchain.prompts import PromptTemplate\n",
"from langchain.chains import LLMChain"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# SCENARIO 2 - Chain\n",
"template = \"\"\"You are a playwright. Given the title of play, it is your job to write a synopsis for that title.\n",
"Title: {title}\n",
"Playwright: This is a synopsis for the above play:\"\"\"\n",
"prompt_template = PromptTemplate(input_variables=[\"title\"], template=template)\n",
"synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callbacks=[mlflow_callback])\n",
"\n",
"test_prompts = [\n",
" {\n",
" \"title\": \"documentary about good video games that push the boundary of game design\"\n",
" },\n",
"]\n",
"synopsis_chain.apply(test_prompts)\n",
"mlflow_callback.flush_tracker(synopsis_chain)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_jN73xcPVEpI"
},
"outputs": [],
"source": [
"from langchain.agents import initialize_agent, load_tools\n",
"from langchain.agents import AgentType"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Gpq4rk6VT9cu"
},
"outputs": [],
"source": [
"# SCENARIO 3 - Agent with Tools\n",
"tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm, callbacks=[mlflow_callback])\n",
"agent = initialize_agent(\n",
" tools,\n",
" llm,\n",
" agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n",
" callbacks=[mlflow_callback],\n",
" verbose=True,\n",
")\n",
"agent.run(\n",
" \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"\n",
")\n",
"mlflow_callback.flush_tracker(agent, finish=True)"
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"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.16"
}
},
"nbformat": 4,
"nbformat_minor": 1
}

65
docs/ecosystem/myscale.md Normal file
View File

@@ -0,0 +1,65 @@
# MyScale
This page covers how to use MyScale vector database within LangChain.
It is broken into two parts: installation and setup, and then references to specific MyScale wrappers.
With MyScale, you can manage both structured and unstructured (vectorized) data, and perform joint queries and analytics on both types of data using SQL. Plus, MyScale's cloud-native OLAP architecture, built on top of ClickHouse, enables lightning-fast data processing even on massive datasets.
## Introduction
[Overview to MyScale and High performance vector search](https://docs.myscale.com/en/overview/)
You can now register on our SaaS and [start a cluster now!](https://docs.myscale.com/en/quickstart/)
If you are also interested in how we managed to integrate SQL and vector, please refer to [this document](https://docs.myscale.com/en/vector-reference/) for further syntax reference.
We also deliver with live demo on huggingface! Please checkout our [huggingface space](https://huggingface.co/myscale)! They search millions of vector within a blink!
## Installation and Setup
- Install the Python SDK with `pip install clickhouse-connect`
### Setting up envrionments
There are two ways to set up parameters for myscale index.
1. Environment Variables
Before you run the app, please set the environment variable with `export`:
`export MYSCALE_URL='<your-endpoints-url>' MYSCALE_PORT=<your-endpoints-port> MYSCALE_USERNAME=<your-username> MYSCALE_PASSWORD=<your-password> ...`
You can easily find your account, password and other info on our SaaS. For details please refer to [this document](https://docs.myscale.com/en/cluster-management/)
Every attributes under `MyScaleSettings` can be set with prefix `MYSCALE_` and is case insensitive.
2. Create `MyScaleSettings` object with parameters
```python
from langchain.vectorstores import MyScale, MyScaleSettings
config = MyScaleSetting(host="<your-backend-url>", port=8443, ...)
index = MyScale(embedding_function, config)
index.add_documents(...)
```
## Wrappers
supported functions:
- `add_texts`
- `add_documents`
- `from_texts`
- `from_documents`
- `similarity_search`
- `asimilarity_search`
- `similarity_search_by_vector`
- `asimilarity_search_by_vector`
- `similarity_search_with_relevance_scores`
### VectorStore
There exists a wrapper around MyScale database, allowing you to use it as a vectorstore,
whether for semantic search or similar example retrieval.
To import this vectorstore:
```python
from langchain.vectorstores import MyScale
```
For a more detailed walkthrough of the MyScale wrapper, see [this notebook](../modules/indexes/vectorstores/examples/myscale.ipynb)

View File

@@ -0,0 +1,19 @@
# PipelineAI
This page covers how to use the PipelineAI ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific PipelineAI wrappers.
## Installation and Setup
- Install with `pip install pipeline-ai`
- Get a Pipeline Cloud api key and set it as an environment variable (`PIPELINE_API_KEY`)
## Wrappers
### LLM
There exists a PipelineAI LLM wrapper, which you can access with
```python
from langchain.llms import PipelineAI
```

View File

@@ -0,0 +1,56 @@
# Prediction Guard
This page covers how to use the Prediction Guard ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Prediction Guard wrappers.
## Installation and Setup
- Install the Python SDK with `pip install predictionguard`
- Get an Prediction Guard access token (as described [here](https://docs.predictionguard.com/)) and set it as an environment variable (`PREDICTIONGUARD_TOKEN`)
## LLM Wrapper
There exists a Prediction Guard LLM wrapper, which you can access with
```python
from langchain.llms import PredictionGuard
```
You can provide the name of your Prediction Guard "proxy" as an argument when initializing the LLM:
```python
pgllm = PredictionGuard(name="your-text-gen-proxy")
```
Alternatively, you can use Prediction Guard's default proxy for SOTA LLMs:
```python
pgllm = PredictionGuard(name="default-text-gen")
```
You can also provide your access token directly as an argument:
```python
pgllm = PredictionGuard(name="default-text-gen", token="<your access token>")
```
## Example usage
Basic usage of the LLM wrapper:
```python
from langchain.llms import PredictionGuard
pgllm = PredictionGuard(name="default-text-gen")
pgllm("Tell me a joke")
```
Basic LLM Chaining with the Prediction Guard wrapper:
```python
from langchain import PromptTemplate, LLMChain
from langchain.llms import PredictionGuard
template = """Question: {question}
Answer: Let's think step by step."""
prompt = PromptTemplate(template=template, input_variables=["question"])
llm_chain = LLMChain(prompt=prompt, llm=PredictionGuard(name="default-text-gen"), verbose=True)
question = "What NFL team won the Super Bowl in the year Justin Beiber was born?"
llm_chain.predict(question=question)
```

79
docs/ecosystem/redis.md Normal file
View File

@@ -0,0 +1,79 @@
# Redis
This page covers how to use the [Redis](https://redis.com) ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Redis wrappers.
## Installation and Setup
- Install the Redis Python SDK with `pip install redis`
## Wrappers
### Cache
The Cache wrapper allows for [Redis](https://redis.io) to be used as a remote, low-latency, in-memory cache for LLM prompts and responses.
#### Standard Cache
The standard cache is the Redis bread & butter of use case in production for both [open source](https://redis.io) and [enterprise](https://redis.com) users globally.
To import this cache:
```python
from langchain.cache import RedisCache
```
To use this cache with your LLMs:
```python
import langchain
import redis
redis_client = redis.Redis.from_url(...)
langchain.llm_cache = RedisCache(redis_client)
```
#### Semantic Cache
Semantic caching allows users to retrieve cached prompts based on semantic similarity between the user input and previously cached results. Under the hood it blends Redis as both a cache and a vectorstore.
To import this cache:
```python
from langchain.cache import RedisSemanticCache
```
To use this cache with your LLMs:
```python
import langchain
import redis
# use any embedding provider...
from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings
redis_url = "redis://localhost:6379"
langchain.llm_cache = RedisSemanticCache(
embedding=FakeEmbeddings(),
redis_url=redis_url
)
```
### VectorStore
The vectorstore wrapper turns Redis into a low-latency [vector database](https://redis.com/solutions/use-cases/vector-database/) for semantic search or LLM content retrieval.
To import this vectorstore:
```python
from langchain.vectorstores import Redis
```
For a more detailed walkthrough of the Redis vectorstore wrapper, see [this notebook](../modules/indexes/vectorstores/examples/redis.ipynb).
### Retriever
The Redis vector store retriever wrapper generalizes the vectorstore class to perform low-latency document retrieval. To create the retriever, simply call `.as_retriever()` on the base vectorstore class.
### Memory
Redis can be used to persist LLM conversations.
#### Vector Store Retriever Memory
For a more detailed walkthrough of the `VectorStoreRetrieverMemory` wrapper, see [this notebook](../modules/memory/types/vectorstore_retriever_memory.ipynb).
#### Chat Message History Memory
For a detailed example of Redis to cache conversation message history, see [this notebook](../modules/memory/examples/redis_chat_message_history.ipynb).

View File

@@ -9,7 +9,7 @@ This page covers how to run models on Replicate within LangChain.
Find a model on the [Replicate explore page](https://replicate.com/explore), and then paste in the model name and version in this format: `owner-name/model-name:version`
For example, for this [flan-t5 model](https://replicate.com/daanelson/flan-t5), click on the API tab. The model name/version would be: `daanelson/flan-t5:04e422a9b85baed86a4f24981d7f9953e20c5fd82f6103b74ebc431588e1cec8`
For example, for this [dolly model](https://replicate.com/replicate/dolly-v2-12b), click on the API tab. The model name/version would be: `"replicate/dolly-v2-12b:ef0e1aefc61f8e096ebe4db6b2bacc297daf2ef6899f0f7e001ec445893500e5"`
Only the `model` param is required, but any other model parameters can also be passed in with the format `input={model_param: value, ...}`
@@ -24,7 +24,7 @@ Replicate(model="stability-ai/stable-diffusion:db21e45d3f7023abc2a46ee38a23973f6
From here, we can initialize our model:
```python
llm = Replicate(model="daanelson/flan-t5:04e422a9b85baed86a4f24981d7f9953e20c5fd82f6103b74ebc431588e1cec8")
llm = Replicate(model="replicate/dolly-v2-12b:ef0e1aefc61f8e096ebe4db6b2bacc297daf2ef6899f0f7e001ec445893500e5")
```
And run it:
@@ -40,8 +40,7 @@ llm(prompt)
We can call any Replicate model (not just LLMs) using this syntax. For example, we can call [Stable Diffusion](https://replicate.com/stability-ai/stable-diffusion):
```python
text2image = Replicate(model="stability-ai/stable-diffusion:db21e45d3f7023abc2a46ee38a23973f6dce16bb082a930b0c49861f96d1e5bf",
input={'image_dimensions'='512x512'}
text2image = Replicate(model="stability-ai/stable-diffusion:db21e45d3f7023abc2a46ee38a23973f6dce16bb082a930b0c49861f96d1e5bf", input={'image_dimensions':'512x512'})
image_output = text2image("A cat riding a motorcycle by Picasso")
```

View File

@@ -15,7 +15,7 @@ custom LLMs, you can use the `SelfHostedPipeline` parent class.
from langchain.llms import SelfHostedPipeline, SelfHostedHuggingFaceLLM
```
For a more detailed walkthrough of the Self-hosted LLMs, see [this notebook](../modules/models/llms/integrations/self_hosted_examples.ipynb)
For a more detailed walkthrough of the Self-hosted LLMs, see [this notebook](../modules/models/llms/integrations/runhouse.ipynb)
## Self-hosted Embeddings
There are several ways to use self-hosted embeddings with LangChain via Runhouse.

22
docs/ecosystem/tair.md Normal file
View File

@@ -0,0 +1,22 @@
# Tair
This page covers how to use the Tair ecosystem within LangChain.
## Installation and Setup
Install Tair Python SDK with `pip install tair`.
## Wrappers
### VectorStore
There exists a wrapper around TairVector, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
To import this vectorstore:
```python
from langchain.vectorstores import Tair
```
For a more detailed walkthrough of the Tair wrapper, see [this notebook](../modules/indexes/vectorstores/examples/tair.ipynb)

View File

@@ -10,6 +10,10 @@ This page is broken into two parts: installation and setup, and then references
`unstructured` wrappers.
## Installation and Setup
If you are using a loader that runs locally, use the following steps to get `unstructured` and
its dependencies running locally.
- Install the Python SDK with `pip install "unstructured[local-inference]"`
- Install the following system dependencies if they are not already available on your system.
Depending on what document types you're parsing, you may not need all of these.
@@ -25,6 +29,15 @@ This page is broken into two parts: installation and setup, and then references
using the `"fast"` strategy, which uses `pdfminer` directly and doesn't require
`detectron2`.
If you want to get up and running with less set up, you can
simply run `pip install unstructured` and use `UnstructuredAPIFileLoader` or
`UnstructuredAPIFileIOLoader`. That will process your document using the hosted Unstructured API.
Note that currently (as of 1 May 2023) the Unstructured API is open, but it will soon require
an API. The [Unstructured documentation page](https://unstructured-io.github.io/) will have
instructions on how to generate an API key once they're available. Check out the instructions
[here](https://github.com/Unstructured-IO/unstructured-api#dizzy-instructions-for-using-the-docker-image)
if you'd like to self-host the Unstructured API or run it locally.
## Wrappers
### Data Loaders

View File

@@ -50,7 +50,6 @@
"source": [
"from datetime import datetime\n",
"from langchain.callbacks import WandbCallbackHandler, StdOutCallbackHandler\n",
"from langchain.callbacks.base import CallbackManager\n",
"from langchain.llms import OpenAI"
]
},
@@ -196,8 +195,8 @@
" name=\"llm\",\n",
" tags=[\"test\"],\n",
")\n",
"manager = CallbackManager([StdOutCallbackHandler(), wandb_callback])\n",
"llm = OpenAI(temperature=0, callback_manager=manager, verbose=True)"
"callbacks = [StdOutCallbackHandler(), wandb_callback]\n",
"llm = OpenAI(temperature=0, callbacks=callbacks)"
]
},
{
@@ -484,7 +483,7 @@
"Title: {title}\n",
"Playwright: This is a synopsis for the above play:\"\"\"\n",
"prompt_template = PromptTemplate(input_variables=[\"title\"], template=template)\n",
"synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callback_manager=manager)\n",
"synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callbacks=callbacks)\n",
"\n",
"test_prompts = [\n",
" {\n",
@@ -577,16 +576,15 @@
],
"source": [
"# SCENARIO 3 - Agent with Tools\n",
"tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm, callback_manager=manager)\n",
"tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm)\n",
"agent = initialize_agent(\n",
" tools,\n",
" llm,\n",
" agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n",
" callback_manager=manager,\n",
" verbose=True,\n",
")\n",
"agent.run(\n",
" \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"\n",
" \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\",\n",
" callbacks=callbacks,\n",
")\n",
"wandb_callback.flush_tracker(agent, reset=False, finish=True)"
]

View File

@@ -30,4 +30,4 @@ To import this vectorstore:
from langchain.vectorstores import Weaviate
```
For a more detailed walkthrough of the Weaviate wrapper, see [this notebook](../modules/indexes/vectorstores/getting_started.ipynb)
For a more detailed walkthrough of the Weaviate wrapper, see [this notebook](../modules/indexes/vectorstores/examples/weaviate.ipynb)

View File

@@ -0,0 +1,43 @@
# Yeager.ai
This page covers how to use [Yeager.ai](https://yeager.ai) to generate LangChain tools and agents.
## What is Yeager.ai?
Yeager.ai is an ecosystem designed to simplify the process of creating AI agents and tools.
It features yAgents, a No-code LangChain Agent Builder, which enables users to build, test, and deploy AI solutions with ease. Leveraging the LangChain framework, yAgents allows seamless integration with various language models and resources, making it suitable for developers, researchers, and AI enthusiasts across diverse applications.
## yAgents
Low code generative agent designed to help you build, prototype, and deploy Langchain tools with ease.
### How to use?
```
pip install yeagerai-agent
yeagerai-agent
```
Go to http://127.0.0.1:7860
This will install the necessary dependencies and set up yAgents on your system. After the first run, yAgents will create a .env file where you can input your OpenAI API key. You can do the same directly from the Gradio interface under the tab "Settings".
`OPENAI_API_KEY=<your_openai_api_key_here>`
We recommend using GPT-4,. However, the tool can also work with GPT-3 if the problem is broken down sufficiently.
### Creating and Executing Tools with yAgents
yAgents makes it easy to create and execute AI-powered tools. Here's a brief overview of the process:
1. Create a tool: To create a tool, provide a natural language prompt to yAgents. The prompt should clearly describe the tool's purpose and functionality. For example:
`create a tool that returns the n-th prime number`
2. Load the tool into the toolkit: To load a tool into yAgents, simply provide a command to yAgents that says so. For example:
`load the tool that you just created it into your toolkit`
3. Execute the tool: To run a tool or agent, simply provide a command to yAgents that includes the name of the tool and any required parameters. For example:
`generate the 50th prime number`
You can see a video of how it works [here](https://www.youtube.com/watch?v=KA5hCM3RaWE).
As you become more familiar with yAgents, you can create more advanced tools and agents to automate your work and enhance your productivity.
For more information, see [yAgents' Github](https://github.com/yeagerai/yeagerai-agent) or our [docs](https://yeagerai.gitbook.io/docs/general/welcome-to-yeager.ai)

21
docs/ecosystem/zilliz.md Normal file
View File

@@ -0,0 +1,21 @@
# Zilliz
This page covers how to use the Zilliz Cloud ecosystem within LangChain.
Zilliz uses the Milvus integration.
It is broken into two parts: installation and setup, and then references to specific Milvus wrappers.
## Installation and Setup
- Install the Python SDK with `pip install pymilvus`
## Wrappers
### VectorStore
There exists a wrapper around Zilliz indexes, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
To import this vectorstore:
```python
from langchain.vectorstores import Milvus
```
For a more detailed walkthrough of the Miluvs wrapper, see [this notebook](../modules/indexes/vectorstores/examples/zilliz.ipynb)

View File

@@ -1,5 +1,5 @@
LangChain Gallery
=============
=================
Lots of people have built some pretty awesome stuff with LangChain.
This is a collection of our favorites.
@@ -223,7 +223,7 @@ Open Source
Answer questions about the documentation of any project
Misc. Colab Notebooks
~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~
.. panels::
:body: text-center
@@ -280,6 +280,17 @@ Proprietary
---
.. link-button:: https://anysummary.app
:type: url
:text: Summarize any file with AI
:classes: stretched-link btn-lg
+++
Summarize not only long docs, interview audio or video files quickly, but also entire websites and YouTube videos. Share or download your generated summaries to collaborate with others, or revisit them at any time! Bonus: `@anysummary <https://twitter.com/anysummary>`_ on Twitter will also summarize any thread it is tagged in.
---
.. link-button:: https://twitter.com/dory111111/status/1608406234646052870?s=20&t=XYlrbKM0ornJsrtGa0br-g
:type: url
:text: AI Assisted SQL Query Generator
@@ -332,4 +343,12 @@ Proprietary
+++
A journaling app for self-care that uses AI to uncover insights and patterns over time.
Articles on **Google Scholar**
-----------------------------
LangChain is used in many scientific and research projects.
**Google Scholar** presents a `list of the papers <https://scholar.google.com/scholar?q=%22langchain%22&hl=en&as_sdt=0,5&as_vis=1>`_
with references to LangChain.

View File

@@ -9,6 +9,8 @@ To get started, install LangChain with the following command:
```bash
pip install langchain
# or
conda install langchain -c conda-forge
```
@@ -44,7 +46,7 @@ LangChain provides many modules that can be used to build language model applica
`````{dropdown} LLMs: Get predictions from a language model
## LLMs: Get predictions from a language model
The most basic building block of LangChain is calling an LLM on some input.
Let's walk through a simple example of how to do this.
@@ -75,10 +77,9 @@ Feetful of Fun
```
For more details on how to use LLMs within LangChain, see the [LLM getting started guide](../modules/models/llms/getting_started.ipynb).
`````
`````{dropdown} Prompt Templates: Manage prompts for LLMs
## Prompt Templates: Manage prompts for LLMs
Calling an LLM is a great first step, but it's just the beginning.
Normally when you use an LLM in an application, you are not sending user input directly to the LLM.
@@ -113,11 +114,10 @@ What is a good name for a company that makes colorful socks?
[For more details, check out the getting started guide for prompts.](../modules/prompts/chat_prompt_template.ipynb)
`````
`````{dropdown} Chains: Combine LLMs and prompts in multi-step workflows
## Chains: Combine LLMs and prompts in multi-step workflows
Up until now, we've worked with the PromptTemplate and LLM primitives by themselves. But of course, a real application is not just one primitive, but rather a combination of them.
@@ -157,10 +157,7 @@ This is one of the simpler types of chains, but understanding how it works will
[For more details, check out the getting started guide for chains.](../modules/chains/getting_started.ipynb)
`````
`````{dropdown} Agents: Dynamically Call Chains Based on User Input
## Agents: Dynamically Call Chains Based on User Input
So far the chains we've looked at run in a predetermined order.
@@ -175,9 +172,9 @@ In order to load agents, you should understand the following concepts:
- LLM: The language model powering the agent.
- Agent: The agent to use. This should be a string that references a support agent class. Because this notebook focuses on the simplest, highest level API, this only covers using the standard supported agents. If you want to implement a custom agent, see the documentation for custom agents (coming soon).
**Agents**: For a list of supported agents and their specifications, see [here](../modules/agents/agents.md).
**Agents**: For a list of supported agents and their specifications, see [here](../modules/agents/getting_started.ipynb).
**Tools**: For a list of predefined tools and their specifications, see [here](../modules/agents/tools.md).
**Tools**: For a list of predefined tools and their specifications, see [here](../modules/agents/tools/getting_started.md).
For this example, you will also need to install the SerpAPI Python package.
@@ -232,10 +229,8 @@ Final Answer: The high temperature in SF yesterday in Fahrenheit raised to the .
```
`````
`````{dropdown} Memory: Add State to Chains and Agents
## Memory: Add State to Chains and Agents
So far, all the chains and agents we've gone through have been stateless. But often, you may want a chain or agent to have some concept of "memory" so that it may remember information about its previous interactions. The clearest and simple example of this is when designing a chatbot - you want it to remember previous messages so it can use context from that to have a better conversation. This would be a type of "short-term memory". On the more complex side, you could imagine a chain/agent remembering key pieces of information over time - this would be a form of "long-term memory". For more concrete ideas on the latter, see this [awesome paper](https://memprompt.com/).
@@ -249,7 +244,8 @@ from langchain import OpenAI, ConversationChain
llm = OpenAI(temperature=0)
conversation = ConversationChain(llm=llm, verbose=True)
conversation.predict(input="Hi there!")
output = conversation.predict(input="Hi there!")
print(output)
```
```pycon
@@ -267,7 +263,8 @@ AI:
```
```python
conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
output = conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
print(output)
```
```pycon
@@ -285,7 +282,6 @@ AI:
> Finished chain.
" That's great! What would you like to talk about?"
```
`````
## Building a Language Model Application: Chat Models
@@ -293,8 +289,8 @@ Similarly, you can use chat models instead of LLMs. Chat models are a variation
Chat model APIs are fairly new, so we are still figuring out the correct abstractions.
## Get Message Completions from a Chat Model
`````{dropdown} Get Message Completions from a Chat Model
You can get chat completions by passing one or more messages to the chat model. The response will be a message. The types of messages currently supported in LangChain are `AIMessage`, `HumanMessage`, `SystemMessage`, and `ChatMessage` -- `ChatMessage` takes in an arbitrary role parameter. Most of the time, you'll just be dealing with `HumanMessage`, `AIMessage`, and `SystemMessage`.
```python
@@ -320,7 +316,7 @@ You can also pass in multiple messages for OpenAI's gpt-3.5-turbo and gpt-4 mode
```python
messages = [
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="Translate this sentence from English to French. I love programming.")
HumanMessage(content="I love programming.")
]
chat(messages)
# -> AIMessage(content="J'aime programmer.", additional_kwargs={})
@@ -331,29 +327,29 @@ You can go one step further and generate completions for multiple sets of messag
batch_messages = [
[
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="Translate this sentence from English to French. I love programming.")
HumanMessage(content="I love programming.")
],
[
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="Translate this sentence from English to French. I love artificial intelligence.")
HumanMessage(content="I love artificial intelligence.")
],
]
result = chat.generate(batch_messages)
result
# -> LLMResult(generations=[[ChatGeneration(text="J'aime programmer.", generation_info=None, message=AIMessage(content="J'aime programmer.", additional_kwargs={}))], [ChatGeneration(text="J'aime l'intelligence artificielle.", generation_info=None, message=AIMessage(content="J'aime l'intelligence artificielle.", additional_kwargs={}))]], llm_output={'token_usage': {'prompt_tokens': 71, 'completion_tokens': 18, 'total_tokens': 89}})
# -> LLMResult(generations=[[ChatGeneration(text="J'aime programmer.", generation_info=None, message=AIMessage(content="J'aime programmer.", additional_kwargs={}))], [ChatGeneration(text="J'aime l'intelligence artificielle.", generation_info=None, message=AIMessage(content="J'aime l'intelligence artificielle.", additional_kwargs={}))]], llm_output={'token_usage': {'prompt_tokens': 57, 'completion_tokens': 20, 'total_tokens': 77}})
```
You can recover things like token usage from this LLMResult:
```
result.llm_output['token_usage']
# -> {'prompt_tokens': 71, 'completion_tokens': 18, 'total_tokens': 89}
# -> {'prompt_tokens': 57, 'completion_tokens': 20, 'total_tokens': 77}
```
`````
`````{dropdown} Chat Prompt Templates
## Chat Prompt Templates
Similar to LLMs, you can make use of templating by using a `MessagePromptTemplate`. You can build a `ChatPromptTemplate` from one or more `MessagePromptTemplate`s. You can use `ChatPromptTemplate`'s `format_prompt` -- this returns a `PromptValue`, which you can convert to a string or `Message` object, depending on whether you want to use the formatted value as input to an llm or chat model.
For convience, there is a `from_template` method exposed on the template. If you were to use this template, this is what it would look like:
For convenience, there is a `from_template` method exposed on the template. If you were to use this template, this is what it would look like:
```python
from langchain.chat_models import ChatOpenAI
@@ -365,9 +361,9 @@ from langchain.prompts.chat import (
chat = ChatOpenAI(temperature=0)
template="You are a helpful assistant that translates {input_language} to {output_language}."
template = "You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template="{text}"
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
@@ -376,9 +372,8 @@ chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_mes
chat(chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages())
# -> AIMessage(content="J'aime programmer.", additional_kwargs={})
```
`````
`````{dropdown} Chains with Chat Models
## Chains with Chat Models
The `LLMChain` discussed in the above section can be used with chat models as well:
```python
@@ -392,9 +387,9 @@ from langchain.prompts.chat import (
chat = ChatOpenAI(temperature=0)
template="You are a helpful assistant that translates {input_language} to {output_language}."
template = "You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template="{text}"
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
@@ -402,9 +397,8 @@ chain = LLMChain(llm=chat, prompt=chat_prompt)
chain.run(input_language="English", output_language="French", text="I love programming.")
# -> "J'aime programmer."
```
`````
`````{dropdown} Agents with Chat Models
## Agents with Chat Models
Agents can also be used with chat models, you can initialize one using `AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION` as the agent type.
```python
@@ -463,9 +457,7 @@ Final Answer: 2.169459462491557
> Finished chain.
'2.169459462491557'
```
`````
`````{dropdown} Memory: Add State to Chains and Agents
## Memory: Add State to Chains and Agents
You can use Memory with chains and agents initialized with chat models. The main difference between this and Memory for LLMs is that rather than trying to condense all previous messages into a string, we can keep them as their own unique memory object.
```python
@@ -499,4 +491,4 @@ conversation.predict(input="I'm doing well! Just having a conversation with an A
conversation.predict(input="Tell me about yourself.")
# -> "Sure! I am an AI language model created by OpenAI. I was trained on a large dataset of text from the internet, which allows me to understand and generate human-like language. I can answer questions, provide information, and even have conversations like this one. Is there anything else you'd like to know about me?"
```
`````

View File

@@ -44,6 +44,8 @@ These modules are, in increasing order of complexity:
- `Agents <./modules/agents.html>`_: Agents involve an LLM making decisions about which Actions to take, taking that Action, seeing an Observation, and repeating that until done. LangChain provides a standard interface for agents, a selection of agents to choose from, and examples of end to end agents.
- `Callbacks <./modules/callbacks/getting_started.html>`_: It can be difficult to track all that occurs inside a chain or agent - callbacks help add a level of observability and introspection.
.. toctree::
:maxdepth: 1
@@ -57,12 +59,17 @@ These modules are, in increasing order of complexity:
./modules/memory.md
./modules/chains.md
./modules/agents.md
./modules/callbacks/getting_started.ipynb
Use Cases
----------
The above modules can be used in a variety of ways. LangChain also provides guidance and assistance in this. Below are some of the common use cases LangChain supports.
- `Autonomous Agents <./use_cases/autonomous_agents.html>`_: Autonomous agents are long running agents that take many steps in an attempt to accomplish an objective. Examples include AutoGPT and BabyAGI.
- `Agent Simulations <./use_cases/agent_simulations.html>`_: Putting agents in a sandbox and observing how they interact with each other or to events can be an interesting way to observe their long-term memory abilities.
- `Personal Assistants <./use_cases/personal_assistants.html>`_: The main LangChain use case. Personal assistants need to take actions, remember interactions, and have knowledge about your data.
- `Question Answering <./use_cases/question_answering.html>`_: The second big LangChain use case. Answering questions over specific documents, only utilizing the information in those documents to construct an answer.
@@ -71,6 +78,8 @@ The above modules can be used in a variety of ways. LangChain also provides guid
- `Querying Tabular Data <./use_cases/tabular.html>`_: If you want to understand how to use LLMs to query data that is stored in a tabular format (csvs, SQL, dataframes, etc) you should read this page.
- `Code Understanding <./use_cases/code.html>`_: If you want to understand how to use LLMs to query source code from github, you should read this page.
- `Interacting with APIs <./use_cases/apis.html>`_: Enabling LLMs to interact with APIs is extremely powerful in order to give them more up-to-date information and allow them to take actions.
- `Extraction <./use_cases/extraction.html>`_: Extract structured information from text.
@@ -87,9 +96,12 @@ The above modules can be used in a variety of ways. LangChain also provides guid
:hidden:
./use_cases/personal_assistants.md
./use_cases/autonomous_agents.md
./use_cases/agent_simulations.md
./use_cases/question_answering.md
./use_cases/chatbots.md
./use_cases/tabular.rst
./use_cases/code.md
./use_cases/apis.md
./use_cases/summarization.md
./use_cases/extraction.md
@@ -150,6 +162,8 @@ Additional collection of resources we think may be useful as you develop your ap
- `Discord <https://discord.gg/6adMQxSpJS>`_: Join us on our Discord to discuss all things LangChain!
- `YouTube <./youtube.html>`_: A collection of the LangChain tutorials and videos.
- `Production Support <https://forms.gle/57d8AmXBYp8PP8tZA>`_: As you move your LangChains into production, we'd love to offer more comprehensive support. Please fill out this form and we'll set up a dedicated support Slack channel.
@@ -166,4 +180,5 @@ Additional collection of resources we think may be useful as you develop your ap
./tracing.md
./use_cases/model_laboratory.ipynb
Discord <https://discord.gg/6adMQxSpJS>
./youtube.md
Production Support <https://forms.gle/57d8AmXBYp8PP8tZA>

View File

@@ -10,6 +10,42 @@ but potentially an unknown chain that depends on the user's input.
In these types of chains, there is a “agent” which has access to a suite of tools.
Depending on the user input, the agent can then decide which, if any, of these tools to call.
At the moment, there are two main types of agents:
1. "Action Agents": these agents decide an action to take and take that action one step at a time
2. "Plan-and-Execute Agents": these agents first decide a plan of actions to take, and then execute those actions one at a time.
When should you use each one? Action Agents are more conventional, and good for small tasks.
For more complex or long running tasks, the initial planning step helps to maintain long term objectives and focus. However, that comes at the expense of generally more calls and higher latency.
These two agents are also not mutually exclusive - in fact, it is often best to have an Action Agent be in change of the execution for the Plan and Execute agent.
Action Agents
-------------
High level pseudocode of agents looks something like:
- Some user input is received
- The `agent` decides which `tool` - if any - to use, and what the input to that tool should be
- That `tool` is then called with that `tool input`, and an `observation` is recorded (this is just the output of calling that tool with that tool input)
- That history of `tool`, `tool input`, and `observation` is passed back into the `agent`, and it decides what step to take next
- This is repeated until the `agent` decides it no longer needs to use a `tool`, and then it responds directly to the user.
The different abstractions involved in agents are as follows:
- Agent: this is where the logic of the application lives. Agents expose an interface that takes in user input along with a list of previous steps the agent has taken, and returns either an `AgentAction` or `AgentFinish`
- `AgentAction` corresponds to the tool to use and the input to that tool
- `AgentFinish` means the agent is done, and has information around what to return to the user
- Tools: these are the actions an agent can take. What tools you give an agent highly depend on what you want the agent to do
- Toolkits: these are groups of tools designed for a specific use case. For example, in order for an agent to interact with a SQL database in the best way it may need access to one tool to execute queries and another tool to inspect tables.
- Agent Executor: this wraps an agent and a list of tools. This is responsible for the loop of running the agent iteratively until the stopping criteria is met.
The most important abstraction of the four above to understand is that of the agent.
Although an agent can be defined in whatever way one chooses, the typical way to construct an agent is with:
- PromptTemplate: this is responsible for taking the user input and previous steps and constructing a prompt to send to the language model
- Language Model: this takes the prompt constructed by the PromptTemplate and returns some output
- Output Parser: this takes the output of the Language Model and parses it into an `AgentAction` or `AgentFinish` object.
In this section of documentation, we first start with a Getting Started notebook to cover how to use all things related to agents in an end-to-end manner.
.. toctree::
@@ -23,25 +59,29 @@ We then split the documentation into the following sections:
**Tools**
An overview of the various tools LangChain supports.
In this section we cover the different types of tools LangChain supports natively.
We then cover how to add your own tools.
**Agents**
An overview of the different agent types.
In this section we cover the different types of agents LangChain supports natively.
We then cover how to modify and create your own agents.
**Toolkits**
An overview of toolkits, and examples of the different ones LangChain supports.
In this section we go over the various toolkits that LangChain supports out of the box,
and how to create an agent from them.
**Agent Executor**
An overview of the Agent Executor class and examples of how to use it.
In this section we go over the Agent Executor class, which is responsible for calling
the agent and tools in a loop. We go over different ways to customize this, and options you
can use for more control.
Go Deeper
---------
**Go Deeper**
.. toctree::
:maxdepth: 1
@@ -50,3 +90,23 @@ Go Deeper
./agents/agents.rst
./agents/toolkits.rst
./agents/agent_executors.rst
Plan-and-Execute Agents
-----------------------
High level pseudocode of agents looks something like:
- Some user input is received
- The planner lists out the steps to take
- The executor goes through the list of steps, executing them
The most typical implementation is to have the planner be a language model,
and the executor be an action agent.
**Go Deeper**
.. toctree::
:maxdepth: 1
./agents/plan_and_execute.ipynb

View File

@@ -1,6 +1,7 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"id": "68b24990",
"metadata": {},
@@ -9,7 +10,7 @@
"\n",
"This notebook covers how to combine agents and vectorstores. The use case for this is that you've ingested your data into a vectorstore and want to interact with it in an agentic manner.\n",
"\n",
"The reccomended method for doing so is to create a RetrievalQA and then use that as a tool in the overall agent. Let's take a look at doing this below. You can do this with multiple different vectordbs, and use the agent as a way to route between them. There are two different ways of doing this - you can either let the agent use the vectorstores as normal tools, or you can set `return_direct=True` to really just use the agent as a router."
"The recommended method for doing so is to create a RetrievalQA and then use that as a tool in the overall agent. Let's take a look at doing this below. You can do this with multiple different vectordbs, and use the agent as a way to route between them. There are two different ways of doing this - you can either let the agent use the vectorstores as normal tools, or you can set `return_direct=True` to really just use the agent as a router."
]
},
{

View File

@@ -9,9 +9,9 @@
"\n",
"LangChain provides async support for Agents by leveraging the [asyncio](https://docs.python.org/3/library/asyncio.html) library.\n",
"\n",
"Async methods are currently supported for the following `Tools`: [`SerpAPIWrapper`](https://github.com/hwchase17/langchain/blob/master/langchain/serpapi.py) and [`LLMMathChain`](https://github.com/hwchase17/langchain/blob/master/langchain/chains/llm_math/base.py). Async support for other agent tools are on the roadmap.\n",
"Async methods are currently supported for the following `Tools`: [`GoogleSerperAPIWrapper`](https://github.com/hwchase17/langchain/blob/master/langchain/utilities/google_serper.py), [`SerpAPIWrapper`](https://github.com/hwchase17/langchain/blob/master/langchain/serpapi.py) and [`LLMMathChain`](https://github.com/hwchase17/langchain/blob/master/langchain/chains/llm_math/base.py). Async support for other agent tools are on the roadmap.\n",
"\n",
"For `Tool`s that have a `coroutine` implemented (the two mentioned above), the `AgentExecutor` will `await` them directly. Otherwise, the `AgentExecutor` will call the `Tool`'s `func` via `asyncio.get_event_loop().run_in_executor` to avoid blocking the main runloop.\n",
"For `Tool`s that have a `coroutine` implemented (the three mentioned above), the `AgentExecutor` will `await` them directly. Otherwise, the `AgentExecutor` will call the `Tool`'s `func` via `asyncio.get_event_loop().run_in_executor` to avoid blocking the main runloop.\n",
"\n",
"You can use `arun` to call an `AgentExecutor` asynchronously."
]
@@ -28,10 +28,14 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 5,
"id": "da5df06c-af6f-4572-b9f5-0ab971c16487",
"metadata": {
"tags": []
"tags": [],
"ExecuteTime": {
"end_time": "2023-05-04T01:27:22.755025Z",
"start_time": "2023-05-04T01:27:22.754041Z"
}
},
"outputs": [],
"source": [
@@ -42,7 +46,6 @@
"from langchain.agents import AgentType\n",
"from langchain.llms import OpenAI\n",
"from langchain.callbacks.stdout import StdOutCallbackHandler\n",
"from langchain.callbacks.base import CallbackManager\n",
"from langchain.callbacks.tracers import LangChainTracer\n",
"from aiohttp import ClientSession\n",
"\n",
@@ -57,10 +60,14 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 3,
"id": "fd4c294e-b1d6-44b8-b32e-2765c017e503",
"metadata": {
"tags": []
"tags": [],
"ExecuteTime": {
"end_time": "2023-05-04T01:15:35.466212Z",
"start_time": "2023-05-04T01:14:05.452245Z"
}
},
"outputs": [
{
@@ -69,119 +76,105 @@
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who won the US Open men's final in 2019 and then calculate his age raised to the 0.334 power.\n",
"Action: Search\n",
"Action Input: \"US Open men's final 2019 winner\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mRafael Nadal\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Rafael Nadal's age\n",
"Action: Search\n",
"Action Input: \"Rafael Nadal age\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m36 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate 36 raised to the 0.334 power\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I need to find out who won the US Open men's final in 2019 and then calculate his age raised to the 0.334 power.\n",
"Action: Google Serper\n",
"Action Input: \"Who won the US Open men's final in 2019?\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mRafael Nadal defeated Daniil Medvedev in the final, 75, 63, 57, 46, 64 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ... Draw: 128 (16 Q / 8 WC). Champion: Rafael Nadal. Runner-up: Daniil Medvedev. Score: 75, 63, 57, 46, 64. Bianca Andreescu won the women's singles title, defeating Serena Williams in straight sets in the final, becoming the first Canadian to win a Grand Slam singles ... Rafael Nadal won his 19th career Grand Slam title, and his fourth US Open crown, by surviving an all-time comback effort from Daniil ... Rafael Nadal beats Daniil Medvedev in US Open final to claim 19th major title. World No2 claims 7-5, 6-3, 5-7, 4-6, 6-4 victory over Russian ... Rafael Nadal defeated Daniil Medvedev in the men's singles final of the U.S. Open on Sunday. Rafael Nadal survived. The 33-year-old defeated Daniil Medvedev in the final of the 2019 U.S. Open to earn his 19th Grand Slam title Sunday ... NEW YORK -- Rafael Nadal defeated Daniil Medvedev in an epic five-set match, 7-5, 6-3, 5-7, 4-6, 6-4 to win the men's singles title at the ... Nadal previously won the U.S. Open three times, most recently in 2017. Ahead of the match, Nadal said he was “super happy to be back in the ... Watch the full match between Daniil Medvedev and Rafael ... Duration: 4:47:32. Posted: Mar 20, 2020. US Open 2019: Rafael Nadal beats Daniil Medvedev · Updated: Sep. 08, 2019, 11:11 p.m. |; Published: Sep · Published: Sep. 08, 2019, 10:06 p.m.. 26. US Open ...\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now know that Rafael Nadal won the US Open men's final in 2019 and he is 33 years old.\n",
"Action: Calculator\n",
"Action Input: 36^0.334\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 3.3098250249682484\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Rafael Nadal, aged 36, won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.3098250249682484.\u001b[0m\n",
"Action Input: 33^0.334\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 3.215019829667466\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now know the final answer.\n",
"Final Answer: Rafael Nadal won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.215019829667466.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.\n",
"Action: Search\n",
"Action Input: \"Olivia Wilde boyfriend\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mJason Sudeikis\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Jason Sudeikis' age\n",
"Action: Search\n",
"Action Input: \"Jason Sudeikis age\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m47 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate 47 raised to the 0.23 power\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.\n",
"Action: Google Serper\n",
"Action Input: \"Olivia Wilde boyfriend\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mSudeikis and Wilde's relationship ended in November 2020. Wilde was publicly served with court documents regarding child custody while she was presenting Don't Worry Darling at CinemaCon 2022. In January 2021, Wilde began dating singer Harry Styles after meeting during the filming of Don't Worry Darling.\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to find out Harry Styles' age.\n",
"Action: Google Serper\n",
"Action Input: \"Harry Styles age\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3m29 years\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to calculate 29 raised to the 0.23 power.\n",
"Action: Calculator\n",
"Action Input: 47^0.23\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.4242784855673896\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Jason Sudeikis, Olivia Wilde's boyfriend, is 47 years old and his age raised to the 0.23 power is 2.4242784855673896.\u001b[0m\n",
"Action Input: 29^0.23\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.169459462491557\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now know the final answer.\n",
"Final Answer: Harry Styles is Olivia Wilde's boyfriend and his current age raised to the 0.23 power is 2.169459462491557.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who won the grand prix and then calculate their age raised to the 0.23 power.\n",
"Action: Search\n",
"Action Input: \"Formula 1 Grand Prix Winner\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mMax Verstappen\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Max Verstappen's age\n",
"Action: Search\n",
"Action Input: \"Max Verstappen Age\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m25 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate 25 raised to the 0.23 power\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I need to find out who won the most recent grand prix and then calculate their age raised to the 0.23 power.\n",
"Action: Google Serper\n",
"Action Input: \"who won the most recent formula 1 grand prix\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mMax Verstappen won his first Formula 1 world title on Sunday after the championship was decided by a last-lap overtake of his rival Lewis Hamilton in the Abu Dhabi Grand Prix. Dec 12, 2021\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to find out Max Verstappen's age\n",
"Action: Google Serper\n",
"Action Input: \"Max Verstappen age\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3m25 years\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to calculate 25 raised to the 0.23 power\n",
"Action: Calculator\n",
"Action Input: 25^0.23\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 1.84599359907945\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Max Verstappen, 25 years old, raised to the 0.23 power is 1.84599359907945.\u001b[0m\n",
"Action Input: 25^0.23\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.096651272316035\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now know the final answer\n",
"Final Answer: Max Verstappen, aged 25, won the most recent Formula 1 grand prix and his age raised to the 0.23 power is 2.096651272316035.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who won the US Open women's final in 2019 and then calculate her age raised to the 0.34 power.\n",
"Action: Search\n",
"Action Input: \"US Open women's final 2019 winner\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mBianca Andreescu defeated Serena Williams in the final, 63, 75 to win the women's singles tennis title at the 2019 US Open. It was her first major title, and she became the first Canadian, as well as the first player born in the 2000s, to win a major singles title.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Bianca Andreescu's age.\n",
"Action: Search\n",
"Action Input: \"Bianca Andreescu age\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m22 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the age of Bianca Andreescu and can calculate her age raised to the 0.34 power.\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I need to find out who won the US Open women's final in 2019 and then calculate her age raised to the 0.34 power.\n",
"Action: Google Serper\n",
"Action Input: \"US Open women's final 2019 winner\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mWHAT HAPPENED: #SheTheNorth? She the champion. Nineteen-year-old Canadian Bianca Andreescu sealed her first Grand Slam title on Saturday, downing 23-time major champion Serena Williams in the 2019 US Open women's singles final, 6-3, 7-5. Sep 7, 2019\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now need to calculate her age raised to the 0.34 power.\n",
"Action: Calculator\n",
"Action Input: 22^0.34\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.8603798598506933\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer.\n",
"Final Answer: Bianca Andreescu won the US Open women's final in 2019 and her age raised to the 0.34 power is 2.8603798598506933.\u001b[0m\n",
"Action Input: 19^0.34\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.7212987634680084\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now know the final answer.\n",
"Final Answer: Nineteen-year-old Canadian Bianca Andreescu won the US Open women's final in 2019 and her age raised to the 0.34 power is 2.7212987634680084.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who Beyonce's husband is and then calculate his age raised to the 0.19 power.\n",
"Action: Search\n",
"Action Input: \"Who is Beyonce's husband?\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mJay-Z\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Jay-Z's age\n",
"Action: Search\n",
"Action Input: \"How old is Jay-Z?\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m53 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate 53 raised to the 0.19 power\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I need to find out who Beyonce's husband is and then calculate his age raised to the 0.19 power.\n",
"Action: Google Serper\n",
"Action Input: \"Who is Beyonce's husband?\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mJay-Z\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to find out Jay-Z's age\n",
"Action: Google Serper\n",
"Action Input: \"How old is Jay-Z?\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3m53 years\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to calculate 53 raised to the 0.19 power\n",
"Action: Calculator\n",
"Action Input: 53^0.19\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.12624064206896\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Jay-Z is Beyonce's husband and his age raised to the 0.19 power is 2.12624064206896.\u001b[0m\n",
"Action Input: 53^0.19\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.12624064206896\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now know the final answer\n",
"Final Answer: Jay-Z is Beyonce's husband and his age raised to the 0.19 power is 2.12624064206896.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"Serial executed in 65.11 seconds.\n"
"\u001B[1m> Finished chain.\u001B[0m\n",
"Serial executed in 89.97 seconds.\n"
]
}
],
"source": [
"def generate_serially():\n",
" for q in questions:\n",
" llm = OpenAI(temperature=0)\n",
" tools = load_tools([\"llm-math\", \"serpapi\"], llm=llm)\n",
" agent = initialize_agent(\n",
" tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION verbose=True\n",
" )\n",
" agent.run(q)\n",
"llm = OpenAI(temperature=0)\n",
"tools = load_tools([\"google-serper\", \"llm-math\"], llm=llm)\n",
"agent = initialize_agent(\n",
" tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True\n",
")\n",
"\n",
"s = time.perf_counter()\n",
"generate_serially()\n",
"for q in questions:\n",
" agent.run(q)\n",
"elapsed = time.perf_counter() - s\n",
"print(f\"Serial executed in {elapsed:0.2f} seconds.\")"
]
@@ -191,7 +184,11 @@
"execution_count": 4,
"id": "076d7b85-45ec-465d-8b31-c2ad119c3438",
"metadata": {
"tags": []
"tags": [],
"ExecuteTime": {
"end_time": "2023-05-04T01:26:59.737657Z",
"start_time": "2023-05-04T01:26:42.182078Z"
}
},
"outputs": [
{
@@ -200,192 +197,95 @@
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.\n",
"Action: Search\n",
"Action Input: \"Olivia Wilde boyfriend\"\u001b[0m\u001b[32;1m\u001b[1;3m I need to find out who Beyonce's husband is and then calculate his age raised to the 0.19 power.\n",
"Action: Search\n",
"Action Input: \"Who is Beyonce's husband?\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mJay-Z\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out who won the grand prix and then calculate their age raised to the 0.23 power.\n",
"Action: Search\n",
"Action Input: \"Formula 1 Grand Prix Winner\"\u001b[0m\u001b[32;1m\u001b[1;3m I need to find out who won the US Open women's final in 2019 and then calculate her age raised to the 0.34 power.\n",
"Action: Search\n",
"Action Input: \"US Open women's final 2019 winner\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mJason Sudeikis\u001b[0m\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.\n",
"Action: Google Serper\n",
"Action Input: \"Olivia Wilde boyfriend\"\u001B[0m\u001B[32;1m\u001B[1;3m I need to find out who Beyonce's husband is and then calculate his age raised to the 0.19 power.\n",
"Action: Google Serper\n",
"Action Input: \"Who is Beyonce's husband?\"\u001B[0m\u001B[32;1m\u001B[1;3m I need to find out who won the most recent formula 1 grand prix and then calculate their age raised to the 0.23 power.\n",
"Action: Google Serper\n",
"Action Input: \"most recent formula 1 grand prix winner\"\u001B[0m\u001B[32;1m\u001B[1;3m I need to find out who won the US Open men's final in 2019 and then calculate his age raised to the 0.334 power.\n",
"Action: Google Serper\n",
"Action Input: \"Who won the US Open men's final in 2019?\"\u001B[0m\u001B[32;1m\u001B[1;3m I need to find out who won the US Open women's final in 2019 and then calculate her age raised to the 0.34 power.\n",
"Action: Google Serper\n",
"Action Input: \"US Open women's final 2019 winner\"\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mSudeikis and Wilde's relationship ended in November 2020. Wilde was publicly served with court documents regarding child custody while she was presenting Don't Worry Darling at CinemaCon 2022. In January 2021, Wilde began dating singer Harry Styles after meeting during the filming of Don't Worry Darling.\u001B[0m\n",
"Thought:\n",
"Observation: \u001b[33;1m\u001b[1;3mMax Verstappen\u001b[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mJay-Z\u001B[0m\n",
"Thought:\n",
"Observation: \u001b[33;1m\u001b[1;3mBianca Andreescu defeated Serena Williams in the final, 63, 75 to win the women's singles tennis title at the 2019 US Open. It was her first major title, and she became the first Canadian, as well as the first player born in the 2000s, to win a major singles title.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Jason Sudeikis' age\n",
"Action: Search\n",
"Action Input: \"Jason Sudeikis age\"\u001b[0m\u001b[32;1m\u001b[1;3m I need to find out Jay-Z's age\n",
"Action: Search\n",
"Action Input: \"How old is Jay-Z?\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m53 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out who won the US Open men's final in 2019 and then calculate his age raised to the 0.334 power.\n",
"Action: Search\n",
"Action Input: \"US Open men's final 2019 winner\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mRafael Nadal defeated Daniil Medvedev in the final, 75, 63, 57, 46, 64 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ...\u001b[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mRafael Nadal defeated Daniil Medvedev in the final, 75, 63, 57, 46, 64 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ... Draw: 128 (16 Q / 8 WC). Champion: Rafael Nadal. Runner-up: Daniil Medvedev. Score: 75, 63, 57, 46, 64. Bianca Andreescu won the women's singles title, defeating Serena Williams in straight sets in the final, becoming the first Canadian to win a Grand Slam singles ... Rafael Nadal won his 19th career Grand Slam title, and his fourth US Open crown, by surviving an all-time comback effort from Daniil ... Rafael Nadal beats Daniil Medvedev in US Open final to claim 19th major title. World No2 claims 7-5, 6-3, 5-7, 4-6, 6-4 victory over Russian ... Rafael Nadal defeated Daniil Medvedev in the men's singles final of the U.S. Open on Sunday. Rafael Nadal survived. The 33-year-old defeated Daniil Medvedev in the final of the 2019 U.S. Open to earn his 19th Grand Slam title Sunday ... NEW YORK -- Rafael Nadal defeated Daniil Medvedev in an epic five-set match, 7-5, 6-3, 5-7, 4-6, 6-4 to win the men's singles title at the ... Nadal previously won the U.S. Open three times, most recently in 2017. Ahead of the match, Nadal said he was “super happy to be back in the ... Watch the full match between Daniil Medvedev and Rafael ... Duration: 4:47:32. Posted: Mar 20, 2020. US Open 2019: Rafael Nadal beats Daniil Medvedev · Updated: Sep. 08, 2019, 11:11 p.m. |; Published: Sep · Published: Sep. 08, 2019, 10:06 p.m.. 26. US Open ...\u001B[0m\n",
"Thought:\n",
"Observation: \u001b[33;1m\u001b[1;3m47 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Max Verstappen's age\n",
"Action: Search\n",
"Action Input: \"Max Verstappen Age\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m25 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Bianca Andreescu's age.\n",
"Action: Search\n",
"Action Input: \"Bianca Andreescu age\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m22 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate 53 raised to the 0.19 power\n",
"Action: Calculator\n",
"Action Input: 53^0.19\u001b[0m\u001b[32;1m\u001b[1;3m I need to find out the age of the winner\n",
"Action: Search\n",
"Action Input: \"Rafael Nadal age\"\u001b[0m\u001b[32;1m\u001b[1;3m I need to calculate 47 raised to the 0.23 power\n",
"Action: Calculator\n",
"Action Input: 47^0.23\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m36 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate 25 raised to the 0.23 power\n",
"Action: Calculator\n",
"Action Input: 25^0.23\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.12624064206896\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the age of Bianca Andreescu and can calculate her age raised to the 0.34 power.\n",
"Action: Calculator\n",
"Action Input: 22^0.34\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 1.84599359907945\u001b[0m\n",
"Observation: \u001B[36;1m\u001B[1;3mWHAT HAPPENED: #SheTheNorth? She the champion. Nineteen-year-old Canadian Bianca Andreescu sealed her first Grand Slam title on Saturday, downing 23-time major champion Serena Williams in the 2019 US Open women's singles final, 6-3, 7-5. Sep 7, 2019\u001B[0m\n",
"Thought:\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.4242784855673896\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now need to calculate his age raised to the 0.334 power\n",
"Observation: \u001B[36;1m\u001B[1;3mLewis Hamilton holds the record for the most race wins in Formula One history, with 103 wins to date. Michael Schumacher, the previous record holder, ... Michael Schumacher (top left) and Lewis Hamilton (top right) have each won the championship a record seven times during their careers, while Sebastian Vettel ( ... Grand Prix, Date, Winner, Car, Laps, Time. Bahrain, 05 Mar 2023, Max Verstappen VER, Red Bull Racing Honda RBPT, 57, 1:33:56.736. Saudi Arabia, 19 Mar 2023 ... The Red Bull driver Max Verstappen of the Netherlands celebrated winning his first Formula 1 world title at the Abu Dhabi Grand Prix. Perez wins sprint as Verstappen, Russell clash. Red Bull's Sergio Perez won the first sprint of the 2023 Formula One season after catching and passing Charles ... The most successful driver in the history of F1 is Lewis Hamilton. The man from Stevenage has won 103 Grands Prix throughout his illustrious career and is still ... Lewis Hamilton: 103. Max Verstappen: 37. Michael Schumacher: 91. Fernando Alonso: 32. Max Verstappen and Sergio Perez will race in a very different-looking Red Bull this weekend after the team unveiled a striking special livery for the Miami GP. Lewis Hamilton holds the record of most victories with 103, ahead of Michael Schumacher (91) and Sebastian Vettel (53). Schumacher also holds the record for the ... Lewis Hamilton holds the record for the most race wins in Formula One history, with 103 wins to date. Michael Schumacher, the previous record holder, is second ...\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to find out Harry Styles' age.\n",
"Action: Google Serper\n",
"Action Input: \"Harry Styles age\"\u001B[0m\u001B[32;1m\u001B[1;3m I need to find out Jay-Z's age\n",
"Action: Google Serper\n",
"Action Input: \"How old is Jay-Z?\"\u001B[0m\u001B[32;1m\u001B[1;3m I now know that Rafael Nadal won the US Open men's final in 2019 and he is 33 years old.\n",
"Action: Calculator\n",
"Action Input: 36^0.334\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 2.8603798598506933\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Jay-Z is Beyonce's husband and his age raised to the 0.19 power is 2.12624064206896.\u001b[0m\n",
"Action Input: 33^0.334\u001B[0m\u001B[32;1m\u001B[1;3m I now need to calculate her age raised to the 0.34 power.\n",
"Action: Calculator\n",
"Action Input: 19^0.34\u001B[0m\n",
"Observation: \u001B[36;1m\u001B[1;3m29 years\u001B[0m\n",
"Thought:\n",
"Observation: \u001B[36;1m\u001B[1;3m53 years\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m Max Verstappen won the most recent Formula 1 grand prix.\n",
"Action: Calculator\n",
"Action Input: Max Verstappen's age (23) raised to the 0.23 power\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.7212987634680084\u001B[0m\n",
"Thought:\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 3.215019829667466\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I need to calculate 29 raised to the 0.23 power.\n",
"Action: Calculator\n",
"Action Input: 29^0.23\u001B[0m\u001B[32;1m\u001B[1;3m I need to calculate 53 raised to the 0.19 power\n",
"Action: Calculator\n",
"Action Input: 53^0.19\u001B[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.0568252837687546\u001B[0m\n",
"Thought:\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.169459462491557\u001B[0m\n",
"Thought:\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Max Verstappen, 25 years old, raised to the 0.23 power is 1.84599359907945.\u001b[0m\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"Observation: \u001B[33;1m\u001B[1;3mAnswer: 2.12624064206896\u001B[0m\n",
"Thought:\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 3.3098250249682484\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Jason Sudeikis, Olivia Wilde's boyfriend, is 47 years old and his age raised to the 0.23 power is 2.4242784855673896.\u001b[0m\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I now know the final answer.\n",
"Final Answer: Bianca Andreescu won the US Open women's final in 2019 and her age raised to the 0.34 power is 2.8603798598506933.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Rafael Nadal, aged 36, won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.3098250249682484.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"Concurrent executed in 12.38 seconds.\n"
"\u001B[1m> Finished chain.\u001B[0m\n",
"Concurrent executed in 17.52 seconds.\n"
]
}
],
"source": [
"async def generate_concurrently():\n",
" agents = []\n",
" # To make async requests in Tools more efficient, you can pass in your own aiohttp.ClientSession, \n",
" # but you must manually close the client session at the end of your program/event loop\n",
" aiosession = ClientSession()\n",
" for _ in questions:\n",
" manager = CallbackManager([StdOutCallbackHandler()])\n",
" llm = OpenAI(temperature=0, callback_manager=manager)\n",
" async_tools = load_tools([\"llm-math\", \"serpapi\"], llm=llm, aiosession=aiosession, callback_manager=manager)\n",
" agents.append(\n",
" initialize_agent(async_tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, callback_manager=manager)\n",
" )\n",
" tasks = [async_agent.arun(q) for async_agent, q in zip(agents, questions)]\n",
" await asyncio.gather(*tasks)\n",
" await aiosession.close()\n",
"llm = OpenAI(temperature=0)\n",
"tools = load_tools([\"google-serper\",\"llm-math\"], llm=llm)\n",
"agent = initialize_agent(\n",
" tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True\n",
")\n",
"\n",
"s = time.perf_counter()\n",
"# If running this outside of Jupyter, use asyncio.run(generate_concurrently())\n",
"await generate_concurrently()\n",
"# If running this outside of Jupyter, use asyncio.run or loop.run_until_complete\n",
"tasks = [agent.arun(q) for q in questions]\n",
"await asyncio.gather(*tasks)\n",
"elapsed = time.perf_counter() - s\n",
"print(f\"Concurrent executed in {elapsed:0.2f} seconds.\")"
]
},
{
"cell_type": "markdown",
"id": "97ef285c-4a43-4a4e-9698-cd52a1bc56c9",
"metadata": {},
"source": [
"## Using Tracing with Asynchronous Agents\n",
"\n",
"To use tracing with async agents, you must pass in a custom `CallbackManager` with `LangChainTracer` to each agent running asynchronously. This way, you avoid collisions while the trace is being collected."
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "44bda05a-d33e-4e91-9a71-a0f3f96aae95",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who won the US Open men's final in 2019 and then calculate his age raised to the 0.334 power.\n",
"Action: Search\n",
"Action Input: \"US Open men's final 2019 winner\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mRafael Nadal\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Rafael Nadal's age\n",
"Action: Search\n",
"Action Input: \"Rafael Nadal age\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m36 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate 36 raised to the 0.334 power\n",
"Action: Calculator\n",
"Action Input: 36^0.334\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 3.3098250249682484\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Rafael Nadal, aged 36, won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.3098250249682484.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
}
],
"source": [
"# To make async requests in Tools more efficient, you can pass in your own aiohttp.ClientSession, \n",
"# but you must manually close the client session at the end of your program/event loop\n",
"aiosession = ClientSession()\n",
"tracer = LangChainTracer()\n",
"tracer.load_default_session()\n",
"manager = CallbackManager([StdOutCallbackHandler(), tracer])\n",
"\n",
"# Pass the manager into the llm if you want llm calls traced.\n",
"llm = OpenAI(temperature=0, callback_manager=manager)\n",
"\n",
"async_tools = load_tools([\"llm-math\", \"serpapi\"], llm=llm, aiosession=aiosession)\n",
"async_agent = initialize_agent(async_tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, callback_manager=manager)\n",
"await async_agent.arun(questions[0])\n",
"await aiosession.close()"
]
}
],
"metadata": {
@@ -404,7 +304,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.1"
"version": "3.10.9"
}
},
"nbformat": 4,

View File

@@ -49,7 +49,7 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 3,
"id": "a33e2f7e",
"metadata": {},
"outputs": [],
@@ -77,7 +77,7 @@
" Returns:\n",
" Action specifying what tool to use.\n",
" \"\"\"\n",
" return AgentAction(tool=\"Search\", tool_input=\"foo\", log=\"\")\n",
" return AgentAction(tool=\"Search\", tool_input=kwargs[\"input\"], log=\"\")\n",
"\n",
" async def aplan(\n",
" self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any\n",
@@ -92,12 +92,12 @@
" Returns:\n",
" Action specifying what tool to use.\n",
" \"\"\"\n",
" return AgentAction(tool=\"Search\", tool_input=\"foo\", log=\"\")"
" return AgentAction(tool=\"Search\", tool_input=kwargs[\"input\"], log=\"\")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 4,
"id": "655d72f6",
"metadata": {},
"outputs": [],
@@ -107,7 +107,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 5,
"id": "490604e9",
"metadata": {},
"outputs": [],
@@ -117,7 +117,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 6,
"id": "653b1617",
"metadata": {},
"outputs": [
@@ -128,7 +128,7 @@
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m\u001b[0m\u001b[36;1m\u001b[1;3mFoo Fighters is an American rock band formed in Seattle in 1994. Foo Fighters was initially formed as a one-man project by former Nirvana drummer Dave Grohl. Following the success of the 1995 eponymous debut album, Grohl recruited a band consisting of Nate Mendel, William Goldsmith, and Pat Smear.\u001b[0m\u001b[32;1m\u001b[1;3m\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m\u001b[0m\u001b[36;1m\u001b[1;3mThe current population of Canada is 38,669,152 as of Monday, April 24, 2023, based on Worldometer elaboration of the latest United Nations data.\u001b[0m\u001b[32;1m\u001b[1;3m\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -136,10 +136,10 @@
{
"data": {
"text/plain": [
"'Foo Fighters is an American rock band formed in Seattle in 1994. Foo Fighters was initially formed as a one-man project by former Nirvana drummer Dave Grohl. Following the success of the 1995 eponymous debut album, Grohl recruited a band consisting of Nate Mendel, William Goldsmith, and Pat Smear.'"
"'The current population of Canada is 38,669,152 as of Monday, April 24, 2023, based on Worldometer elaboration of the latest United Nations data.'"
]
},
"execution_count": 7,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}

View File

@@ -315,7 +315,7 @@
" log=llm_output,\n",
" )\n",
" # Parse out the action and action input\n",
" regex = r\"Action: (.*?)[\\n]*Action Input:[\\s]*(.*)\"\n",
" regex = r\"Action\\s*\\d*\\s*:(.*?)\\nAction\\s*\\d*\\s*Input\\s*\\d*\\s*:[\\s]*(.*)\"\n",
" match = re.search(regex, llm_output, re.DOTALL)\n",
" if not match:\n",
" raise ValueError(f\"Could not parse LLM output: `{llm_output}`\")\n",
@@ -373,6 +373,7 @@
"metadata": {},
"outputs": [],
"source": [
"tools = get_tools(\"whats the weather?\")\n",
"tool_names = [tool.name for tool in tools]\n",
"agent = LLMSingleActionAgent(\n",
" llm_chain=llm_chain, \n",

View File

@@ -42,7 +42,7 @@
},
{
"cell_type": "code",
"execution_count": 11,
"execution_count": 1,
"id": "9af9734e",
"metadata": {},
"outputs": [],
@@ -67,7 +67,7 @@
},
{
"cell_type": "code",
"execution_count": 28,
"execution_count": 2,
"id": "becda2a1",
"metadata": {},
"outputs": [],
@@ -99,7 +99,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 3,
"id": "339b1bb8",
"metadata": {},
"outputs": [],
@@ -128,7 +128,7 @@
},
{
"cell_type": "code",
"execution_count": 22,
"execution_count": 4,
"id": "fd969d31",
"metadata": {},
"outputs": [],
@@ -159,7 +159,7 @@
},
{
"cell_type": "code",
"execution_count": 23,
"execution_count": 5,
"id": "798ef9fb",
"metadata": {},
"outputs": [],
@@ -187,7 +187,7 @@
},
{
"cell_type": "code",
"execution_count": 13,
"execution_count": 6,
"id": "7c6fe0d3",
"metadata": {},
"outputs": [],
@@ -204,7 +204,7 @@
" log=llm_output,\n",
" )\n",
" # Parse out the action and action input\n",
" regex = r\"Action: (.*?)[\\n]*Action Input:[\\s]*(.*)\"\n",
" regex = r\"Action\\s*\\d*\\s*:(.*?)\\nAction\\s*\\d*\\s*Input\\s*\\d*\\s*:[\\s]*(.*)\"\n",
" match = re.search(regex, llm_output, re.DOTALL)\n",
" if not match:\n",
" raise ValueError(f\"Could not parse LLM output: `{llm_output}`\")\n",
@@ -216,7 +216,7 @@
},
{
"cell_type": "code",
"execution_count": 14,
"execution_count": 7,
"id": "d278706a",
"metadata": {},
"outputs": [],
@@ -236,7 +236,7 @@
},
{
"cell_type": "code",
"execution_count": 16,
"execution_count": 8,
"id": "f9d4c374",
"metadata": {},
"outputs": [],
@@ -268,7 +268,7 @@
},
{
"cell_type": "code",
"execution_count": 24,
"execution_count": 9,
"id": "9b1cc2a2",
"metadata": {},
"outputs": [],
@@ -279,7 +279,7 @@
},
{
"cell_type": "code",
"execution_count": 25,
"execution_count": 10,
"id": "e4f5092f",
"metadata": {},
"outputs": [],
@@ -305,7 +305,7 @@
},
{
"cell_type": "code",
"execution_count": 26,
"execution_count": 11,
"id": "490604e9",
"metadata": {},
"outputs": [],
@@ -315,7 +315,7 @@
},
{
"cell_type": "code",
"execution_count": 27,
"execution_count": 12,
"id": "653b1617",
"metadata": {},
"outputs": [
@@ -326,11 +326,12 @@
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mAction: Search\n",
"\u001b[32;1m\u001b[1;3mThought: I need to find out the population of Canada in 2023\n",
"Action: Search\n",
"Action Input: Population of Canada in 2023\u001b[0m\n",
"\n",
"Observation:\u001b[36;1m\u001b[1;3m38,648,380\u001b[0m\u001b[32;1m\u001b[1;3m That's a lot of people!\n",
"Final Answer: Arrr, there be 38,648,380 people livin' in Canada come 2023!\u001b[0m\n",
"Observation:\u001b[36;1m\u001b[1;3mThe current population of Canada is 38,658,314 as of Wednesday, April 12, 2023, based on Worldometer elaboration of the latest United Nations data.\u001b[0m\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Arrr, there be 38,658,314 people livin' in Canada as of 2023!\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -338,10 +339,165 @@
{
"data": {
"text/plain": [
"\"Arrr, there be 38,648,380 people livin' in Canada come 2023!\""
"\"Arrr, there be 38,658,314 people livin' in Canada as of 2023!\""
]
},
"execution_count": 27,
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_executor.run(\"How many people live in canada as of 2023?\")"
]
},
{
"cell_type": "markdown",
"id": "d5b4a078",
"metadata": {},
"source": [
"## Adding Memory\n",
"\n",
"If you want to add memory to the agent, you'll need to:\n",
"\n",
"1. Add a place in the custom prompt for the chat_history\n",
"2. Add a memory object to the agent executor."
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "94fffda1",
"metadata": {},
"outputs": [],
"source": [
"# Set up the base template\n",
"template_with_history = \"\"\"Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:\n",
"\n",
"{tools}\n",
"\n",
"Use the following format:\n",
"\n",
"Question: the input question you must answer\n",
"Thought: you should always think about what to do\n",
"Action: the action to take, should be one of [{tool_names}]\n",
"Action Input: the input to the action\n",
"Observation: the result of the action\n",
"... (this Thought/Action/Action Input/Observation can repeat N times)\n",
"Thought: I now know the final answer\n",
"Final Answer: the final answer to the original input question\n",
"\n",
"Begin! Remember to speak as a pirate when giving your final answer. Use lots of \"Arg\"s\n",
"\n",
"Previous conversation history:\n",
"{history}\n",
"\n",
"New question: {input}\n",
"{agent_scratchpad}\"\"\""
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "f58488d7",
"metadata": {},
"outputs": [],
"source": [
"prompt_with_history = CustomPromptTemplate(\n",
" template=template_with_history,\n",
" tools=tools,\n",
" # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically\n",
" # This includes the `intermediate_steps` variable because that is needed\n",
" input_variables=[\"input\", \"intermediate_steps\", \"history\"]\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 31,
"id": "d28d4b5a",
"metadata": {},
"outputs": [],
"source": [
"llm_chain = LLMChain(llm=llm, prompt=prompt_with_history)"
]
},
{
"cell_type": "code",
"execution_count": 32,
"id": "3e37b32a",
"metadata": {},
"outputs": [],
"source": [
"tool_names = [tool.name for tool in tools]\n",
"agent = LLMSingleActionAgent(\n",
" llm_chain=llm_chain, \n",
" output_parser=output_parser,\n",
" stop=[\"\\nObservation:\"], \n",
" allowed_tools=tool_names\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "97ea1bce",
"metadata": {},
"outputs": [],
"source": [
"from langchain.memory import ConversationBufferWindowMemory"
]
},
{
"cell_type": "code",
"execution_count": 42,
"id": "b5ad69ce",
"metadata": {},
"outputs": [],
"source": [
"memory=ConversationBufferWindowMemory(k=2)"
]
},
{
"cell_type": "code",
"execution_count": 43,
"id": "b7b5c9b1",
"metadata": {},
"outputs": [],
"source": [
"agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True, memory=memory)"
]
},
{
"cell_type": "code",
"execution_count": 44,
"id": "5ec4c39b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: I need to find out the population of Canada in 2023\n",
"Action: Search\n",
"Action Input: Population of Canada in 2023\u001b[0m\n",
"\n",
"Observation:\u001b[36;1m\u001b[1;3mThe current population of Canada is 38,658,314 as of Wednesday, April 12, 2023, based on Worldometer elaboration of the latest United Nations data.\u001b[0m\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Arrr, there be 38,658,314 people livin' in Canada as of 2023!\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"\"Arrr, there be 38,658,314 people livin' in Canada as of 2023!\""
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
@@ -350,10 +506,48 @@
"agent_executor.run(\"How many people live in canada as of 2023?\")"
]
},
{
"cell_type": "code",
"execution_count": 45,
"id": "b2ba45bb",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: I need to find out how many people live in Mexico.\n",
"Action: Search\n",
"Action Input: How many people live in Mexico as of 2023?\u001b[0m\n",
"\n",
"Observation:\u001b[36;1m\u001b[1;3mThe current population of Mexico is 132,679,922 as of Tuesday, April 11, 2023, based on Worldometer elaboration of the latest United Nations data. Mexico 2020 ...\u001b[0m\u001b[32;1m\u001b[1;3m I now know the final answer.\n",
"Final Answer: Arrr, there be 132,679,922 people livin' in Mexico as of 2023!\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"\"Arrr, there be 132,679,922 people livin' in Mexico as of 2023!\""
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_executor.run(\"how about in mexico?\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "adefb4c2",
"id": "bd820a7a",
"metadata": {},
"outputs": [],
"source": []

View File

@@ -42,7 +42,7 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 1,
"id": "9af9734e",
"metadata": {},
"outputs": [],
@@ -100,13 +100,13 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 12,
"id": "339b1bb8",
"metadata": {},
"outputs": [],
"source": [
"# Set up the base template\n",
"template = \"\"\"Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:\n",
"template = \"\"\"Complete the objective as best you can. You have access to the following tools:\n",
"\n",
"{tools}\n",
"\n",
@@ -121,7 +121,11 @@
"Thought: I now know the final answer\n",
"Final Answer: the final answer to the original input question\n",
"\n",
"Begin! Remember to speak as a pirate when giving your final answer. Use lots of \"Arg\"s\n",
"These were previous tasks you completed:\n",
"\n",
"\n",
"\n",
"Begin!\n",
"\n",
"Question: {input}\n",
"{agent_scratchpad}\"\"\""
@@ -129,7 +133,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 13,
"id": "fd969d31",
"metadata": {},
"outputs": [],
@@ -161,7 +165,7 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 14,
"id": "798ef9fb",
"metadata": {},
"outputs": [],
@@ -189,7 +193,7 @@
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 15,
"id": "7c6fe0d3",
"metadata": {},
"outputs": [],
@@ -206,7 +210,7 @@
" log=llm_output,\n",
" )\n",
" # Parse out the action and action input\n",
" regex = r\"Action: (.*?)[\\n]*Action Input:[\\s]*(.*)\"\n",
" regex = r\"Action\\s*\\d*\\s*:(.*?)\\nAction\\s*\\d*\\s*Input\\s*\\d*\\s*:[\\s]*(.*)\"\n",
" match = re.search(regex, llm_output, re.DOTALL)\n",
" if not match:\n",
" raise ValueError(f\"Could not parse LLM output: `{llm_output}`\")\n",
@@ -218,7 +222,7 @@
},
{
"cell_type": "code",
"execution_count": 10,
"execution_count": 16,
"id": "d278706a",
"metadata": {},
"outputs": [],
@@ -238,7 +242,7 @@
},
{
"cell_type": "code",
"execution_count": 12,
"execution_count": 17,
"id": "f9d4c374",
"metadata": {},
"outputs": [],
@@ -270,7 +274,7 @@
},
{
"cell_type": "code",
"execution_count": 13,
"execution_count": 18,
"id": "9b1cc2a2",
"metadata": {},
"outputs": [],
@@ -281,7 +285,7 @@
},
{
"cell_type": "code",
"execution_count": 14,
"execution_count": 19,
"id": "e4f5092f",
"metadata": {},
"outputs": [],
@@ -307,7 +311,7 @@
},
{
"cell_type": "code",
"execution_count": 15,
"execution_count": 20,
"id": "490604e9",
"metadata": {},
"outputs": [],
@@ -317,7 +321,7 @@
},
{
"cell_type": "code",
"execution_count": 16,
"execution_count": 21,
"id": "653b1617",
"metadata": {},
"outputs": [
@@ -328,16 +332,13 @@
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: Wot year be it now? That be important to know the answer.\n",
"\u001b[32;1m\u001b[1;3mThought: I should use a reliable search engine to get accurate information.\n",
"Action: Search\n",
"Action Input: \"current population canada 2023\"\u001b[0m\n",
"Action Input: \"Leo DiCaprio girlfriend\"\u001b[0m\n",
"\n",
"Observation:\u001b[36;1m\u001b[1;3m38,649,283\u001b[0m\u001b[32;1m\u001b[1;3mAhoy! That be the correct year, but the answer be in regular numbers. 'Tis time to translate to pirate speak.\n",
"Action: Search\n",
"Action Input: \"38,649,283 in pirate speak\"\u001b[0m\n",
"\n",
"Observation:\u001b[36;1m\u001b[1;3mBrush up on your “Pirate Talk” with these helpful pirate phrases. Aaaarrrrgggghhhh! Pirate catch phrase of grumbling or disgust. Ahoy! Hello! Ahoy, Matey, Hello ...\u001b[0m\u001b[32;1m\u001b[1;3mThat be not helpful, I'll just do the translation meself.\n",
"Final Answer: Arrrr, thar be 38,649,283 scallywags in Canada as of 2023.\u001b[0m\n",
"Observation:\u001b[36;1m\u001b[1;3mHe went on to date Gisele Bündchen, Bar Refaeli, Blake Lively, Toni Garrn and Nina Agdal, among others, before finally settling down with current girlfriend Camila Morrone, who is 23 years his junior.\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mI have found the answer to the question.\n",
"Final Answer: Leo DiCaprio's current girlfriend is Camila Morrone.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -345,16 +346,16 @@
{
"data": {
"text/plain": [
"'Arrrr, thar be 38,649,283 scallywags in Canada as of 2023.'"
"\"Leo DiCaprio's current girlfriend is Camila Morrone.\""
]
},
"execution_count": 16,
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_executor.run(\"How many people live in canada as of 2023?\")"
"agent_executor.run(\"Search for Leo DiCaprio's girlfriend on the internet.\")"
]
},
{

View File

@@ -20,13 +20,14 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "6064f080",
"metadata": {},
"source": [
"### Custom LLMChain\n",
"\n",
"The first way to create a custom agent is to use an existing Agent class, but use a custom LLMChain. This is the simplest way to create a custom Agent. It is highly reccomended that you work with the `ZeroShotAgent`, as at the moment that is by far the most generalizable one. \n",
"The first way to create a custom agent is to use an existing Agent class, but use a custom LLMChain. This is the simplest way to create a custom Agent. It is highly recommended that you work with the `ZeroShotAgent`, as at the moment that is by far the most generalizable one. \n",
"\n",
"Most of the work in creating the custom LLMChain comes down to the prompt. Because we are using an existing agent class to parse the output, it is very important that the prompt say to produce text in that format. Additionally, we currently require an `agent_scratchpad` input variable to put notes on previous actions and observations. This should almost always be the final part of the prompt. However, besides those instructions, you can customize the prompt as you wish.\n",
"\n",
@@ -42,7 +43,7 @@
},
{
"cell_type": "code",
"execution_count": 23,
"execution_count": 1,
"id": "9af9734e",
"metadata": {},
"outputs": [],
@@ -53,7 +54,7 @@
},
{
"cell_type": "code",
"execution_count": 24,
"execution_count": 2,
"id": "becda2a1",
"metadata": {},
"outputs": [],
@@ -70,7 +71,7 @@
},
{
"cell_type": "code",
"execution_count": 25,
"execution_count": 3,
"id": "339b1bb8",
"metadata": {},
"outputs": [],
@@ -99,7 +100,7 @@
},
{
"cell_type": "code",
"execution_count": 26,
"execution_count": 4,
"id": "e21d2098",
"metadata": {},
"outputs": [
@@ -145,7 +146,7 @@
},
{
"cell_type": "code",
"execution_count": 27,
"execution_count": 5,
"id": "9b1cc2a2",
"metadata": {},
"outputs": [],
@@ -155,7 +156,7 @@
},
{
"cell_type": "code",
"execution_count": 28,
"execution_count": 6,
"id": "e4f5092f",
"metadata": {},
"outputs": [],
@@ -166,7 +167,7 @@
},
{
"cell_type": "code",
"execution_count": 29,
"execution_count": 7,
"id": "490604e9",
"metadata": {},
"outputs": [],
@@ -176,7 +177,7 @@
},
{
"cell_type": "code",
"execution_count": 31,
"execution_count": 8,
"id": "653b1617",
"metadata": {},
"outputs": [
@@ -190,9 +191,9 @@
"\u001b[32;1m\u001b[1;3mThought: I need to find out the population of Canada\n",
"Action: Search\n",
"Action Input: Population of Canada 2023\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mThe current population of Canada is 38,610,447 as of Saturday, February 18, 2023, based on Worldometer elaboration of the latest United Nations data. Canada 2020 population is estimated at 37,742,154 people at mid year according to UN data.\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mThe current population of Canada is 38,661,927 as of Sunday, April 16, 2023, based on Worldometer elaboration of the latest United Nations data.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Arrr, Canada be havin' 38,610,447 scallywags livin' there as of 2023!\u001b[0m\n",
"Final Answer: Arrr, Canada be havin' 38,661,927 people livin' there as of 2023!\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -200,10 +201,10 @@
{
"data": {
"text/plain": [
"\"Arrr, Canada be havin' 38,610,447 scallywags livin' there as of 2023!\""
"\"Arrr, Canada be havin' 38,661,927 people livin' there as of 2023!\""
]
},
"execution_count": 31,
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
@@ -223,7 +224,7 @@
},
{
"cell_type": "code",
"execution_count": 32,
"execution_count": 9,
"id": "43dbfa2f",
"metadata": {},
"outputs": [],
@@ -244,7 +245,7 @@
},
{
"cell_type": "code",
"execution_count": 33,
"execution_count": 10,
"id": "0f087313",
"metadata": {},
"outputs": [],
@@ -254,7 +255,7 @@
},
{
"cell_type": "code",
"execution_count": 34,
"execution_count": 11,
"id": "92c75a10",
"metadata": {},
"outputs": [],
@@ -264,7 +265,7 @@
},
{
"cell_type": "code",
"execution_count": 35,
"execution_count": 12,
"id": "ac5b83bf",
"metadata": {},
"outputs": [],
@@ -274,7 +275,7 @@
},
{
"cell_type": "code",
"execution_count": 36,
"execution_count": 13,
"id": "c960e4ff",
"metadata": {},
"outputs": [
@@ -285,12 +286,16 @@
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: I need to find out the population of Canada in 2023.\n",
"\u001b[32;1m\u001b[1;3mThought: I should look for recent population estimates.\n",
"Action: Search\n",
"Action Input: Population of Canada in 2023\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mThe current population of Canada is 38,610,447 as of Saturday, February 18, 2023, based on Worldometer elaboration of the latest United Nations data. Canada 2020 population is estimated at 37,742,154 people at mid year according to UN data.\u001b[0m\n",
"Action Input: Canada population 2023\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m39,566,248\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I should double check this number.\n",
"Action: Search\n",
"Action Input: Canada population estimates 2023\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mCanada's population was estimated at 39,566,248 on January 1, 2023, after a record population growth of 1,050,110 people from January 1, 2022, to January 1, 2023.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer.\n",
"Final Answer: La popolazione del Canada nel 2023 è stimata in 38.610.447 persone.\u001b[0m\n",
"Final Answer: La popolazione del Canada è stata stimata a 39.566.248 il 1° gennaio 2023, dopo un record di crescita demografica di 1.050.110 persone dal 1° gennaio 2022 al 1° gennaio 2023.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -298,10 +303,10 @@
{
"data": {
"text/plain": [
"'La popolazione del Canada nel 2023 è stimata in 38.610.447 persone.'"
"'La popolazione del Canada è stata stimata a 39.566.248 il 1° gennaio 2023, dopo un record di crescita demografica di 1.050.110 persone dal 1° gennaio 2022 al 1° gennaio 2023.'"
]
},
"execution_count": 36,
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}

View File

@@ -31,7 +31,7 @@
},
{
"cell_type": "code",
"execution_count": 21,
"execution_count": 2,
"id": "d7c4ebdc",
"metadata": {},
"outputs": [],
@@ -43,7 +43,7 @@
},
{
"cell_type": "code",
"execution_count": 22,
"execution_count": 3,
"id": "becda2a1",
"metadata": {},
"outputs": [],
@@ -66,7 +66,7 @@
},
{
"cell_type": "code",
"execution_count": 23,
"execution_count": 4,
"id": "a33e2f7e",
"metadata": {},
"outputs": [],
@@ -96,8 +96,8 @@
" \"\"\"\n",
" if len(intermediate_steps) == 0:\n",
" return [\n",
" AgentAction(tool=\"Search\", tool_input=\"foo\", log=\"\"),\n",
" AgentAction(tool=\"RandomWord\", tool_input=\"foo\", log=\"\"),\n",
" AgentAction(tool=\"Search\", tool_input=kwargs[\"input\"], log=\"\"),\n",
" AgentAction(tool=\"RandomWord\", tool_input=kwargs[\"input\"], log=\"\"),\n",
" ]\n",
" else:\n",
" return AgentFinish(return_values={\"output\": \"bar\"}, log=\"\")\n",
@@ -117,8 +117,8 @@
" \"\"\"\n",
" if len(intermediate_steps) == 0:\n",
" return [\n",
" AgentAction(tool=\"Search\", tool_input=\"foo\", log=\"\"),\n",
" AgentAction(tool=\"RandomWord\", tool_input=\"foo\", log=\"\"),\n",
" AgentAction(tool=\"Search\", tool_input=kwargs[\"input\"], log=\"\"),\n",
" AgentAction(tool=\"RandomWord\", tool_input=kwargs[\"input\"], log=\"\"),\n",
" ]\n",
" else:\n",
" return AgentFinish(return_values={\"output\": \"bar\"}, log=\"\")"
@@ -126,7 +126,7 @@
},
{
"cell_type": "code",
"execution_count": 24,
"execution_count": 5,
"id": "655d72f6",
"metadata": {},
"outputs": [],
@@ -136,7 +136,7 @@
},
{
"cell_type": "code",
"execution_count": 25,
"execution_count": 6,
"id": "490604e9",
"metadata": {},
"outputs": [],
@@ -146,7 +146,7 @@
},
{
"cell_type": "code",
"execution_count": 26,
"execution_count": 7,
"id": "653b1617",
"metadata": {},
"outputs": [
@@ -157,7 +157,7 @@
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m\u001b[0m\u001b[36;1m\u001b[1;3mFoo Fighters is an American rock band formed in Seattle in 1994. Foo Fighters was initially formed as a one-man project by former Nirvana drummer Dave Grohl. Following the success of the 1995 eponymous debut album, Grohl recruited a band consisting of Nate Mendel, William Goldsmith, and Pat Smear.\u001b[0m\u001b[32;1m\u001b[1;3m\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m\u001b[0m\u001b[36;1m\u001b[1;3mThe current population of Canada is 38,669,152 as of Monday, April 24, 2023, based on Worldometer elaboration of the latest United Nations data.\u001b[0m\u001b[32;1m\u001b[1;3m\u001b[0m\n",
"Now I'm doing this!\n",
"\u001b[33;1m\u001b[1;3mfoo\u001b[0m\u001b[32;1m\u001b[1;3m\u001b[0m\n",
"\n",
@@ -170,7 +170,7 @@
"'bar'"
]
},
"execution_count": 26,
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}

View File

@@ -28,7 +28,15 @@
"execution_count": 2,
"id": "f65308ab",
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"WARNING:root:Failed to default session, using empty session: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /sessions (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x10a1767c0>: Failed to establish a new connection: [Errno 61] Connection refused'))\n"
]
}
],
"source": [
"from langchain.agents import Tool\n",
"from langchain.memory import ConversationBufferMemory\n",
@@ -88,7 +96,20 @@
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"WARNING:root:Failed to persist run: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /chain-runs (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x13fab40d0>: Failed to establish a new connection: [Errno 61] Connection refused'))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[32;1m\u001b[1;3m{\n",
" \"action\": \"Final Answer\",\n",
" \"action_input\": \"Hello Bob! How can I assist you today?\"\n",
@@ -124,7 +145,20 @@
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"WARNING:root:Failed to persist run: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /chain-runs (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x13fab44f0>: Failed to establish a new connection: [Errno 61] Connection refused'))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[32;1m\u001b[1;3m{\n",
" \"action\": \"Final Answer\",\n",
" \"action_input\": \"Your name is Bob.\"\n",
@@ -167,10 +201,24 @@
" \"action\": \"Current Search\",\n",
" \"action_input\": \"Thai food dinner recipes\"\n",
"}\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m59 easy Thai recipes for any night of the week · Marion Grasby's Thai spicy chilli and basil fried rice · Thai curry noodle soup · Marion Grasby's ...\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m{\n",
"Observation: \u001b[36;1m\u001b[1;3m59 easy Thai recipes for any night of the week · Marion Grasby's Thai spicy chilli and basil fried rice · Thai curry noodle soup · Marion Grasby's Thai Spicy ...\u001b[0m\n",
"Thought:"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"WARNING:root:Failed to persist run: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /chain-runs (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x13fae8be0>: Failed to establish a new connection: [Errno 61] Connection refused'))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[32;1m\u001b[1;3m{\n",
" \"action\": \"Final Answer\",\n",
" \"action_input\": \"Here are some Thai food dinner recipes you can make this week: Thai spicy chilli and basil fried rice, Thai curry noodle soup, and many more. You can find 59 easy Thai recipes for any night of the week on Marion Grasby's website.\"\n",
" \"action_input\": \"Here are some Thai food dinner recipes you can make this week: Thai spicy chilli and basil fried rice, Thai curry noodle soup, and Thai Spicy ... (59 recipes in total).\"\n",
"}\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
@@ -179,7 +227,7 @@
{
"data": {
"text/plain": [
"\"Here are some Thai food dinner recipes you can make this week: Thai spicy chilli and basil fried rice, Thai curry noodle soup, and many more. You can find 59 easy Thai recipes for any night of the week on Marion Grasby's website.\""
"'Here are some Thai food dinner recipes you can make this week: Thai spicy chilli and basil fried rice, Thai curry noodle soup, and Thai Spicy ... (59 recipes in total).'"
]
},
"execution_count": 8,
@@ -210,11 +258,25 @@
" \"action_input\": \"who won the world cup in 1978\"\n",
"}\n",
"```\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mThe Argentina national football team represents Argentina in men's international football and is administered by the Argentine Football Association, the governing body for football in Argentina. Nicknamed La Albiceleste, they are the reigning world champions, having won the most recent World Cup in 2022.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m```json\n",
"Observation: \u001b[36;1m\u001b[1;3mArgentina national football team\u001b[0m\n",
"Thought:"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"WARNING:root:Failed to persist run: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /chain-runs (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x13fae86d0>: Failed to establish a new connection: [Errno 61] Connection refused'))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[32;1m\u001b[1;3m```json\n",
"{\n",
" \"action\": \"Final Answer\",\n",
" \"action_input\": \"The last letter in your name is 'b'. The Argentina national football team won the World Cup in 1978.\"\n",
" \"action_input\": \"The last letter in your name is 'b', and the winner of the 1978 World Cup was the Argentina national football team.\"\n",
"}\n",
"```\u001b[0m\n",
"\n",
@@ -224,7 +286,7 @@
{
"data": {
"text/plain": [
"\"The last letter in your name is 'b'. The Argentina national football team won the World Cup in 1978.\""
"\"The last letter in your name is 'b', and the winner of the 1978 World Cup was the Argentina national football team.\""
]
},
"execution_count": 9,
@@ -253,10 +315,24 @@
" \"action\": \"Current Search\",\n",
" \"action_input\": \"weather in pomfret\"\n",
"}\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mMostly cloudy with gusty winds developing during the afternoon. A few flurries or snow showers possible. High near 40F. Winds NNW at 20 to 30 mph.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m{\n",
"Observation: \u001b[36;1m\u001b[1;3m10 Day Weather-Pomfret, CT ; Sun 16. 64° · 50°. 24% · NE 7 mph ; Mon 17. 58° · 45°. 70% · ESE 8 mph ; Tue 18. 57° · 37°. 8% · WSW 15 mph.\u001b[0m\n",
"Thought:"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"WARNING:root:Failed to persist run: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /chain-runs (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x13fa9d7f0>: Failed to establish a new connection: [Errno 61] Connection refused'))\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[32;1m\u001b[1;3m{\n",
" \"action\": \"Final Answer\",\n",
" \"action_input\": \"The weather in Pomfret is mostly cloudy with gusty winds developing during the afternoon. A few flurries or snow showers are possible. High near 40F. Winds NNW at 20 to 30 mph.\"\n",
" \"action_input\": \"The weather in Pomfret, CT for the next 10 days is as follows: Sun 16. 64° · 50°. 24% · NE 7 mph ; Mon 17. 58° · 45°. 70% · ESE 8 mph ; Tue 18. 57° · 37°. 8% · WSW 15 mph.\"\n",
"}\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
@@ -265,7 +341,7 @@
{
"data": {
"text/plain": [
"'The weather in Pomfret is mostly cloudy with gusty winds developing during the afternoon. A few flurries or snow showers are possible. High near 40F. Winds NNW at 20 to 30 mph.'"
"'The weather in Pomfret, CT for the next 10 days is as follows: Sun 16. 64° · 50°. 24% · NE 7 mph ; Mon 17. 58° · 45°. 70% · ESE 8 mph ; Tue 18. 57° · 37°. 8% · WSW 15 mph.'"
]
},
"execution_count": 10,

View File

@@ -23,7 +23,7 @@
"from langchain.agents import AgentType\n",
"from langchain.memory import ConversationBufferMemory\n",
"from langchain import OpenAI\n",
"from langchain.utilities import GoogleSearchAPIWrapper\n",
"from langchain.utilities import SerpAPIWrapper\n",
"from langchain.agents import initialize_agent"
]
},
@@ -34,7 +34,7 @@
"metadata": {},
"outputs": [],
"source": [
"search = GoogleSearchAPIWrapper()\n",
"search = SerpAPIWrapper()\n",
"tools = [\n",
" Tool(\n",
" name = \"Current Search\",\n",
@@ -149,8 +149,12 @@
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m\n",
"Thought: Do I need to use a tool? No\n",
"AI: If you like Thai food, some great dinner options this week could include Thai green curry, Pad Thai, or a Thai-style stir-fry. You could also try making a Thai-style soup or salad. Enjoy!\u001b[0m\n",
"Thought: Do I need to use a tool? Yes\n",
"Action: Current Search\n",
"Action Input: Thai food dinner recipes\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m59 easy Thai recipes for any night of the week · Marion Grasby's Thai spicy chilli and basil fried rice · Thai curry noodle soup · Marion Grasby's Thai Spicy ...\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m Do I need to use a tool? No\n",
"AI: Here are some great Thai dinner recipes you can try this week: Marion Grasby's Thai Spicy Chilli and Basil Fried Rice, Thai Curry Noodle Soup, Thai Green Curry with Coconut Rice, Thai Red Curry with Vegetables, and Thai Coconut Soup. I hope you enjoy them!\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -158,7 +162,7 @@
{
"data": {
"text/plain": [
"'If you like Thai food, some great dinner options this week could include Thai green curry, Pad Thai, or a Thai-style stir-fry. You could also try making a Thai-style soup or salad. Enjoy!'"
"\"Here are some great Thai dinner recipes you can try this week: Marion Grasby's Thai Spicy Chilli and Basil Fried Rice, Thai Curry Noodle Soup, Thai Green Curry with Coconut Rice, Thai Red Curry with Vegetables, and Thai Coconut Soup. I hope you enjoy them!\""
]
},
"execution_count": 7,
@@ -187,9 +191,9 @@
"Thought: Do I need to use a tool? Yes\n",
"Action: Current Search\n",
"Action Input: Who won the World Cup in 1978\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mThe Cup was won by the host nation, Argentina, who defeated the Netherlands 31 in the final, after extra time. The final was held at River Plate's home stadium ... Amid Argentina's celebrations, there was sympathy for the Netherlands, runners-up for the second tournament running, following a 3-1 final defeat at the Estadio ... The match was won by the Argentine squad in extra time by a score of 31. Mario Kempes, who finished as the tournament's top scorer, was named the man of the ... May 21, 2022 ... Argentina won the World Cup for the first time in their history, beating Netherlands 3-1 in the final. This edition of the World Cup was full of ... The adidas Golden Ball is presented to the best player at each FIFA World Cup finals. Those who finish as runners-up in the vote receive the adidas Silver ... Holders West Germany failed to beat Holland and Italy and were eliminated when Berti Vogts' own goal gave Austria a 3-2 victory. Holland thrashed the Austrians ... Jun 14, 2018 ... On a clear afternoon on 1 June 1978 at the revamped El Monumental stadium in Buenos Aires' Belgrano barrio, several hundred children in white ... Dec 15, 2022 ... The tournament couldn't have gone better for the ruling junta. Argentina went on to win the championship, defeating the Netherlands, 3-1, in the ... Nov 9, 2022 ... Host: Argentina Teams: 16. Format: Group stage, second round, third-place playoff, final. Matches: 38. Goals: 102. Winner: Argentina Feb 19, 2009 ... Argentina sealed their first World Cup win on home soil when they defeated the Netherlands in an exciting final that went to extra-time. For the ...\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mArgentina national football team\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m Do I need to use a tool? No\n",
"AI: The last letter in your name is 'b'. Argentina won the World Cup in 1978.\u001b[0m\n",
"AI: The last letter in your name is \"b\" and the winner of the 1978 World Cup was the Argentina national football team.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -197,7 +201,7 @@
{
"data": {
"text/plain": [
"\"The last letter in your name is 'b'. Argentina won the World Cup in 1978.\""
"'The last letter in your name is \"b\" and the winner of the 1978 World Cup was the Argentina national football team.'"
]
},
"execution_count": 8,
@@ -226,9 +230,9 @@
"Thought: Do I need to use a tool? Yes\n",
"Action: Current Search\n",
"Action Input: Current temperature in Pomfret\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mA mixture of rain and snow showers. High 39F. Winds NNW at 5 to 10 mph. Chance of precip 50%. Snow accumulations less than one inch. Pomfret, CT Weather Forecast, with current conditions, wind, air quality, and what to expect for the next 3 days. Pomfret Center Weather Forecasts. ... Pomfret Center, CT Weather Conditionsstar_ratehome ... Tomorrow's temperature is forecast to be COOLER than today. It is 46 degrees fahrenheit, or 8 degrees celsius and feels like 46 degrees fahrenheit. The barometric pressure is 29.78 - measured by inch of mercury units - ... Pomfret Weather Forecasts. ... Pomfret, MD Weather Conditionsstar_ratehome ... Tomorrow's temperature is forecast to be MUCH COOLER than today. Additional Headlines. En Español · Share |. Current conditions at ... Pomfret CT. Tonight ... Past Weather Information · Interactive Forecast Map. Pomfret MD detailed current weather report for 20675 in Charles county, Maryland. ... Pomfret, MD weather condition is Mostly Cloudy and 43°F. Mostly Cloudy. Hazardous Weather Conditions. Hazardous Weather Outlook · En Español · Share |. Current conditions at ... South Pomfret VT. Tonight. Pomfret Center, CT Weather. Current Report for Thu Jan 5 2023. As of 2:00 PM EST. 5-Day Forecast | Road Conditions. 45°F 7°c. Feels Like 44°F. Pomfret Center CT. Today. Today: Areas of fog before 9am. Otherwise, cloudy, with a ... Otherwise, cloudy, with a temperature falling to around 33 by 5pm.\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mPartly cloudy skies. High around 70F. Winds W at 5 to 10 mph. Humidity41%.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m Do I need to use a tool? No\n",
"AI: The current temperature in Pomfret is 45°F (7°C) and it feels like 44°F.\u001b[0m\n",
"AI: The current temperature in Pomfret is around 70F with partly cloudy skies and winds W at 5 to 10 mph. The humidity is 41%.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -236,7 +240,7 @@
{
"data": {
"text/plain": [
"'The current temperature in Pomfret is 45°F (7°C) and it feels like 44°F.'"
"'The current temperature in Pomfret is around 70F with partly cloudy skies and winds W at 5 to 10 mph. The humidity is 41%.'"
]
},
"execution_count": 9,

View File

@@ -33,7 +33,7 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 3,
"id": "07e96d99",
"metadata": {},
"outputs": [],
@@ -41,7 +41,7 @@
"llm = OpenAI(temperature=0)\n",
"search = SerpAPIWrapper()\n",
"llm_math_chain = LLMMathChain(llm=llm, verbose=True)\n",
"db = SQLDatabase.from_uri(\"sqlite:///../../../../notebooks/Chinook.db\")\n",
"db = SQLDatabase.from_uri(\"sqlite:///../../../../../notebooks/Chinook.db\")\n",
"db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True)\n",
"tools = [\n",
" Tool(\n",
@@ -64,7 +64,7 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 4,
"id": "a069c4b6",
"metadata": {},
"outputs": [],
@@ -74,7 +74,7 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 5,
"id": "e603cd7d",
"metadata": {},
"outputs": [
@@ -88,30 +88,24 @@
"\u001b[32;1m\u001b[1;3m I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.\n",
"Action: Search\n",
"Action Input: \"Who is Leo DiCaprio's girlfriend?\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mCamila Morrone\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Camila Morrone's age\n",
"Action: Search\n",
"Action Input: \"How old is Camila Morrone?\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m25 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate 25 raised to the 0.43 power\n",
"Observation: \u001b[36;1m\u001b[1;3mDiCaprio met actor Camila Morrone in December 2017, when she was 20 and he was 43. They were spotted at Coachella and went on multiple vacations together. Some reports suggested that DiCaprio was ready to ask Morrone to marry him. The couple made their red carpet debut at the 2020 Academy Awards.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate Camila Morrone's age raised to the 0.43 power.\n",
"Action: Calculator\n",
"Action Input: 25^0.43\u001b[0m\n",
"Action Input: 21^0.43\u001b[0m\n",
"\n",
"\u001b[1m> Entering new LLMMathChain chain...\u001b[0m\n",
"25^0.43\u001b[32;1m\u001b[1;3m\n",
"```python\n",
"import math\n",
"print(math.pow(25, 0.43))\n",
"21^0.43\u001b[32;1m\u001b[1;3m\n",
"```text\n",
"21**0.43\n",
"```\n",
"...numexpr.evaluate(\"21**0.43\")...\n",
"\u001b[0m\n",
"Answer: \u001b[33;1m\u001b[1;3m3.991298452658078\n",
"\u001b[0m\n",
"Answer: \u001b[33;1m\u001b[1;3m3.7030049853137306\u001b[0m\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\n",
"Observation: \u001b[33;1m\u001b[1;3mAnswer: 3.991298452658078\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Camila Morrone is 25 years old and her age raised to the 0.43 power is 3.991298452658078.\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mAnswer: 3.7030049853137306\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer.\n",
"Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.7030049853137306.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -119,10 +113,10 @@
{
"data": {
"text/plain": [
"'Camila Morrone is 25 years old and her age raised to the 0.43 power is 3.991298452658078.'"
"\"Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.7030049853137306.\""
]
},
"execution_count": 4,
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
@@ -133,7 +127,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 6,
"id": "a5c07010",
"metadata": {},
"outputs": [
@@ -147,21 +141,36 @@
"\u001b[32;1m\u001b[1;3m I need to find out the artist's full name and then search the FooBar database for their albums.\n",
"Action: Search\n",
"Action Input: \"The Storm Before the Calm\" artist\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mThe Storm Before the Calm (stylized in all lowercase) is the tenth (and eighth international) studio album by Canadian-American singer-songwriter Alanis ...\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now need to search the FooBar database for Alanis Morissette's albums\n",
"Observation: \u001b[36;1m\u001b[1;3mThe Storm Before the Calm (stylized in all lowercase) is the tenth (and eighth international) studio album by Canadian-American singer-songwriter Alanis Morissette, released June 17, 2022, via Epiphany Music and Thirty Tigers, as well as by RCA Records in Europe.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now need to search the FooBar database for Alanis Morissette's albums.\n",
"Action: FooBar DB\n",
"Action Input: What albums by Alanis Morissette are in the FooBar database?\u001b[0m\n",
"\n",
"\u001b[1m> Entering new SQLDatabaseChain chain...\u001b[0m\n",
"What albums by Alanis Morissette are in the FooBar database? \n",
"SQLQuery:\u001b[32;1m\u001b[1;3m SELECT Title FROM Album INNER JOIN Artist ON Album.ArtistId = Artist.ArtistId WHERE Artist.Name = 'Alanis Morissette' LIMIT 5;\u001b[0m\n",
"What albums by Alanis Morissette are in the FooBar database?\n",
"SQLQuery:"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/harrisonchase/workplace/langchain/langchain/sql_database.py:191: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n",
" sample_rows = connection.execute(command)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[32;1m\u001b[1;3m SELECT \"Title\" FROM \"Album\" INNER JOIN \"Artist\" ON \"Album\".\"ArtistId\" = \"Artist\".\"ArtistId\" WHERE \"Name\" = 'Alanis Morissette' LIMIT 5;\u001b[0m\n",
"SQLResult: \u001b[33;1m\u001b[1;3m[('Jagged Little Pill',)]\u001b[0m\n",
"Answer:\u001b[32;1m\u001b[1;3m The albums by Alanis Morissette in the FooBar database are Jagged Little Pill.\u001b[0m\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\n",
"Observation: \u001b[38;5;200m\u001b[1;3m The albums by Alanis Morissette in the FooBar database are Jagged Little Pill.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: The artist who released the album The Storm Before the Calm is Alanis Morissette and the albums of theirs in the FooBar database are Jagged Little Pill.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer.\n",
"Final Answer: The artist who released the album 'The Storm Before the Calm' is Alanis Morissette and the albums of hers in the FooBar database are Jagged Little Pill.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -169,10 +178,10 @@
{
"data": {
"text/plain": [
"'The artist who released the album The Storm Before the Calm is Alanis Morissette and the albums of theirs in the FooBar database are Jagged Little Pill.'"
"\"The artist who released the album 'The Storm Before the Calm' is Alanis Morissette and the albums of hers in the FooBar database are Jagged Little Pill.\""
]
},
"execution_count": 5,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}

View File

@@ -21,7 +21,7 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 8,
"id": "ac561cc4",
"metadata": {},
"outputs": [],
@@ -34,7 +34,7 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 10,
"id": "07e96d99",
"metadata": {},
"outputs": [],
@@ -43,7 +43,7 @@
"llm1 = OpenAI(temperature=0)\n",
"search = SerpAPIWrapper()\n",
"llm_math_chain = LLMMathChain(llm=llm1, verbose=True)\n",
"db = SQLDatabase.from_uri(\"sqlite:///../../../../notebooks/Chinook.db\")\n",
"db = SQLDatabase.from_uri(\"sqlite:///../../../../../notebooks/Chinook.db\")\n",
"db_chain = SQLDatabaseChain(llm=llm1, database=db, verbose=True)\n",
"tools = [\n",
" Tool(\n",
@@ -66,7 +66,7 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 11,
"id": "a069c4b6",
"metadata": {},
"outputs": [],
@@ -76,7 +76,7 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 12,
"id": "e603cd7d",
"metadata": {},
"outputs": [
@@ -92,37 +92,34 @@
"```\n",
"{\n",
" \"action\": \"Search\",\n",
" \"action_input\": \"Who is Leo DiCaprio's girlfriend?\"\n",
" \"action_input\": \"Leo DiCaprio girlfriend\"\n",
"}\n",
"```\n",
"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mCamila Morrone\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mFor the second question, I need to use the calculator tool to raise her current age to the 0.43 power.\n",
"Observation: \u001b[36;1m\u001b[1;3mGigi Hadid: 2022 Leo and Gigi were first linked back in September 2022, when a source told Us Weekly that Leo had his “sights set\" on her (alarming way to put it, but okay).\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mFor the second question, I need to calculate the age raised to the 0.43 power. I will use the calculator tool.\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"Calculator\",\n",
" \"action_input\": \"22.0^(0.43)\"\n",
" \"action_input\": \"((2022-1995)^0.43)\"\n",
"}\n",
"```\n",
"\n",
"\u001b[0m\n",
"\n",
"\u001b[1m> Entering new LLMMathChain chain...\u001b[0m\n",
"22.0^(0.43)\u001b[32;1m\u001b[1;3m\n",
"```python\n",
"import math\n",
"print(math.pow(22.0, 0.43))\n",
"((2022-1995)^0.43)\u001b[32;1m\u001b[1;3m\n",
"```text\n",
"(2022-1995)**0.43\n",
"```\n",
"...numexpr.evaluate(\"(2022-1995)**0.43\")...\n",
"\u001b[0m\n",
"Answer: \u001b[33;1m\u001b[1;3m3.777824273683966\n",
"\u001b[0m\n",
"Answer: \u001b[33;1m\u001b[1;3m4.125593352125936\u001b[0m\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\n",
"Observation: \u001b[33;1m\u001b[1;3mAnswer: 3.777824273683966\n",
"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mAnswer: 4.125593352125936\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI now know the final answer.\n",
"Final Answer: Camila Morrone, 3.777824273683966.\u001b[0m\n",
"Final Answer: Gigi Hadid is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is approximately 4.13.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -130,10 +127,10 @@
{
"data": {
"text/plain": [
"'Camila Morrone, 3.777824273683966.'"
"\"Gigi Hadid is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is approximately 4.13.\""
]
},
"execution_count": 4,
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
@@ -144,7 +141,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 13,
"id": "a5c07010",
"metadata": {},
"outputs": [
@@ -156,7 +153,7 @@
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mQuestion: What is the full name of the artist who recently released an album called 'The Storm Before the Calm' and are they in the FooBar database? If so, what albums of theirs are in the FooBar database?\n",
"Thought: I should use the Search tool to find the answer to the first part of the question and then use the FooBar DB tool to find the answer to the second part of the question.\n",
"Thought: I should use the Search tool to find the answer to the first part of the question and then use the FooBar DB tool to find the answer to the second part.\n",
"Action:\n",
"```\n",
"{\n",
@@ -166,7 +163,7 @@
"```\n",
"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAlanis Morissette\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mNow that I have the name of the artist, I can use the FooBar DB tool to find their albums in the database.\n",
"Thought:\u001b[32;1m\u001b[1;3mNow that I know the artist's name, I can use the FooBar DB tool to find out if they are in the database and what albums of theirs are in it.\n",
"Action:\n",
"```\n",
"{\n",
@@ -178,7 +175,7 @@
"\u001b[0m\n",
"\n",
"\u001b[1m> Entering new SQLDatabaseChain chain...\u001b[0m\n",
"What albums does Alanis Morissette have in the database? \n",
"What albums does Alanis Morissette have in the database?\n",
"SQLQuery:"
]
},
@@ -186,7 +183,7 @@
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/harrisonchase/workplace/langchain/langchain/sql_database.py:141: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n",
"/Users/harrisonchase/workplace/langchain/langchain/sql_database.py:191: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n",
" sample_rows = connection.execute(command)\n"
]
},
@@ -194,14 +191,14 @@
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[32;1m\u001b[1;3m SELECT Title FROM Album WHERE ArtistId IN (SELECT ArtistId FROM Artist WHERE Name = 'Alanis Morissette') LIMIT 5;\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m SELECT \"Title\" FROM \"Album\" WHERE \"ArtistId\" IN (SELECT \"ArtistId\" FROM \"Artist\" WHERE \"Name\" = 'Alanis Morissette') LIMIT 5;\u001b[0m\n",
"SQLResult: \u001b[33;1m\u001b[1;3m[('Jagged Little Pill',)]\u001b[0m\n",
"Answer:\u001b[32;1m\u001b[1;3m Alanis Morissette has the album 'Jagged Little Pill' in the database.\u001b[0m\n",
"Answer:\u001b[32;1m\u001b[1;3m Alanis Morissette has the album Jagged Little Pill in the database.\u001b[0m\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\n",
"Observation: \u001b[38;5;200m\u001b[1;3m Alanis Morissette has the album 'Jagged Little Pill' in the database.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI have found the answer to both parts of the question.\n",
"Final Answer: The artist who recently released an album called 'The Storm Before the Calm' is Alanis Morissette. The album 'Jagged Little Pill' is in the FooBar database.\u001b[0m\n",
"Observation: \u001b[38;5;200m\u001b[1;3m Alanis Morissette has the album Jagged Little Pill in the database.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mThe artist Alanis Morissette is in the FooBar database and has the album Jagged Little Pill in it.\n",
"Final Answer: Alanis Morissette is in the FooBar database and has the album Jagged Little Pill in it.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -209,10 +206,10 @@
{
"data": {
"text/plain": [
"\"The artist who recently released an album called 'The Storm Before the Calm' is Alanis Morissette. The album 'Jagged Little Pill' is in the FooBar database.\""
"'Alanis Morissette is in the FooBar database and has the album Jagged Little Pill in it.'"
]
},
"execution_count": 5,
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}

View File

@@ -12,7 +12,7 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 1,
"id": "7e3b513e",
"metadata": {},
"outputs": [
@@ -25,11 +25,12 @@
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m Yes.\n",
"Follow up: Who is the reigning men's U.S. Open champion?\u001b[0m\n",
"Intermediate answer: \u001b[36;1m\u001b[1;3mCarlos Alcaraz won the 2022 Men's single title while Poland's Iga Swiatek won the Women's single title defeating Tunisian's Ons Jabeur.\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mFollow up: Where is Carlos Alcaraz from?\u001b[0m\n",
"Intermediate answer: \u001b[36;1m\u001b[1;3mCarlos Alcaraz Garfia\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mFollow up: Where is Carlos Alcaraz Garfia from?\u001b[0m\n",
"Intermediate answer: \u001b[36;1m\u001b[1;3mEl Palmar, Spain\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mSo the final answer is: El Palmar, Spain\u001b[0m\n",
"\u001b[1m> Finished AgentExecutor chain.\u001b[0m\n"
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
@@ -38,7 +39,7 @@
"'El Palmar, Spain'"
]
},
"execution_count": 2,
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
@@ -61,6 +62,14 @@
"self_ask_with_search = initialize_agent(tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True)\n",
"self_ask_with_search.run(\"What is the hometown of the reigning men's U.S. Open champion?\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b2e4d6bc",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
@@ -79,7 +88,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.9"
"version": "3.9.1"
},
"vscode": {
"interpreter": {

View File

@@ -0,0 +1,424 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "4658d71a",
"metadata": {},
"source": [
"# Structured Tool Chat Agent\n",
"\n",
"This notebook walks through using a chat agent capable of using multi-input tools.\n",
"\n",
"Older agents are configured to specify an action input as a single string, but this agent can use the provided tools' `args_schema` to populate the action input.\n",
"\n",
"This functionality is natively available in the (`structured-chat-zero-shot-react-description` or `AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION`)."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "ccc8ff98",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"os.environ[\"LANGCHAIN_TRACING\"] = \"true\" # If you want to trace the execution of the program, set to \"true\""
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "f65308ab",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain.agents import AgentType\n",
"from langchain.chat_models import ChatOpenAI\n",
"from langchain.agents import initialize_agent"
]
},
{
"cell_type": "markdown",
"id": "30aaf540-9e8e-436e-af8b-89e610e34120",
"metadata": {},
"source": [
"### Initialize Tools\n",
"\n",
"We will test the agent using a web browser."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "71027ff2-5d09-49cd-92a1-24b2c454a7ae",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain.agents.agent_toolkits import PlayWrightBrowserToolkit\n",
"from langchain.tools.playwright.utils import (\n",
" create_async_playwright_browser,\n",
" create_sync_playwright_browser, # A synchronous browser is available, though it isn't compatible with jupyter.\n",
")\n",
"\n",
"# This import is required only for jupyter notebooks, since they have their own eventloop\n",
"import nest_asyncio\n",
"nest_asyncio.apply()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "5fb14d6d",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"async_browser = create_async_playwright_browser()\n",
"browser_toolkit = PlayWrightBrowserToolkit.from_browser(async_browser=async_browser)\n",
"tools = browser_toolkit.get_tools()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "cafe9bc1",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"llm = ChatOpenAI(temperature=0) # Also works well with Anthropic models\n",
"agent_chain = initialize_agent(tools, llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "4f4aa234-9746-47d8-bec7-d76081ac3ef6",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mAction:\n",
"```\n",
"{\n",
" \"action\": \"Final Answer\",\n",
" \"action_input\": \"Hello Erica, how can I assist you today?\"\n",
"}\n",
"```\n",
"\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"Hello Erica, how can I assist you today?\n"
]
}
],
"source": [
"response = await agent_chain.arun(input=\"Hi I'm Erica.\")\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "23e7dc33-50a5-4685-8e9b-4ac49e12877f",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"I'm here to chat! How's your day going?\n"
]
}
],
"source": [
"response = await agent_chain.arun(input=\"Don't need help really just chatting.\")\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "dc70b454",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mAction:\n",
"```\n",
"{\n",
" \"action\": \"navigate_browser\",\n",
" \"action_input\": {\n",
" \"url\": \"https://blog.langchain.dev/\"\n",
" }\n",
"}\n",
"```\n",
"\n",
"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mNavigating to https://blog.langchain.dev/ returned status code 200\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI need to extract the text from the webpage to summarize it.\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"extract_text\",\n",
" \"action_input\": {}\n",
"}\n",
"```\n",
"\u001b[0m\n",
"Observation: \u001b[31;1m\u001b[1;3mLangChain LangChain Home About GitHub Docs LangChain The official LangChain blog. Auto-Evaluator Opportunities Editor's Note: this is a guest blog post by Lance Martin.\n",
"\n",
"\n",
"TL;DR\n",
"\n",
"We recently open-sourced an auto-evaluator tool for grading LLM question-answer chains. We are now releasing an open source, free to use hosted app and API to expand usability. Below we discuss a few opportunities to further improve May 1, 2023 5 min read Callbacks Improvements TL;DR: We're announcing improvements to our callbacks system, which powers logging, tracing, streaming output, and some awesome third-party integrations. This will better support concurrent runs with independent callbacks, tracing of deeply nested trees of LangChain components, and callback handlers scoped to a single request (which is super useful for May 1, 2023 3 min read Unleashing the power of AI Collaboration with Parallelized LLM Agent Actor Trees Editor's note: the following is a guest blog post from Cyrus at Shaman AI. We use guest blog posts to highlight interesting and novel applciations, and this is certainly that. There's been a lot of talk about agents recently, but most have been discussions around a single agent. If multiple Apr 28, 2023 4 min read Gradio & LLM Agents Editor's note: this is a guest blog post from Freddy Boulton, a software engineer at Gradio. We're excited to share this post because it brings a large number of exciting new tools into the ecosystem. Agents are largely defined by the tools they have, so to be able to equip Apr 23, 2023 4 min read RecAlign - The smart content filter for social media feed [Editor's Note] This is a guest post by Tian Jin. We are highlighting this application as we think it is a novel use case. Specifically, we think recommendation systems are incredibly impactful in our everyday lives and there has not been a ton of discourse on how LLMs will impact Apr 22, 2023 3 min read Improving Document Retrieval with Contextual Compression Note: This post assumes some familiarity with LangChain and is moderately technical.\n",
"\n",
"💡 TL;DR: Weve introduced a new abstraction and a new document Retriever to facilitate the post-processing of retrieved documents. Specifically, the new abstraction makes it easy to take a set of retrieved documents and extract from them Apr 20, 2023 3 min read Autonomous Agents & Agent Simulations Over the past two weeks, there has been a massive increase in using LLMs in an agentic manner. Specifically, projects like AutoGPT, BabyAGI, CAMEL, and Generative Agents have popped up. The LangChain community has now implemented some parts of all of those projects in the LangChain framework. While researching and Apr 18, 2023 7 min read AI-Powered Medical Knowledge: Revolutionizing Care for Rare Conditions [Editor's Note]: This is a guest post by Jack Simon, who recently participated in a hackathon at Williams College. He built a LangChain-powered chatbot focused on appendiceal cancer, aiming to make specialized knowledge more accessible to those in need. If you are interested in building a chatbot for another rare Apr 17, 2023 3 min read Auto-Eval of Question-Answering Tasks By Lance Martin\n",
"\n",
"Context\n",
"\n",
"LLM ops platforms, such as LangChain, make it easy to assemble LLM components (e.g., models, document retrievers, data loaders) into chains. Question-Answering is one of the most popular applications of these chains. But it is often not always obvious to determine what parameters (e.g. Apr 15, 2023 3 min read Announcing LangChainJS Support for Multiple JS Environments TLDR: We're announcing support for running LangChain.js in browsers, Cloudflare Workers, Vercel/Next.js, Deno, Supabase Edge Functions, alongside existing support for Node.js ESM and CJS. See install/upgrade docs and breaking changes list.\n",
"\n",
"\n",
"Context\n",
"\n",
"Originally we designed LangChain.js to run in Node.js, which is the Apr 11, 2023 3 min read LangChain x Supabase Supabase is holding an AI Hackathon this week. Here at LangChain we are big fans of both Supabase and hackathons, so we thought this would be a perfect time to highlight the multiple ways you can use LangChain and Supabase together.\n",
"\n",
"The reason we like Supabase so much is that Apr 8, 2023 2 min read Announcing our $10M seed round led by Benchmark It was only six months ago that we released the first version of LangChain, but it seems like several years. When we launched, generative AI was starting to go mainstream: stable diffusion had just been released and was captivating peoples imagination and fueling an explosion in developer activity, Jasper Apr 4, 2023 4 min read Custom Agents One of the most common requests we've heard is better functionality and documentation for creating custom agents. This has always been a bit tricky - because in our mind it's actually still very unclear what an \"agent\" actually is, and therefor what the \"right\" abstractions for them may be. Recently, Apr 3, 2023 3 min read Retrieval TL;DR: We are adjusting our abstractions to make it easy for other retrieval methods besides the LangChain VectorDB object to be used in LangChain. This is done with the goals of (1) allowing retrievers constructed elsewhere to be used more easily in LangChain, (2) encouraging more experimentation with alternative Mar 23, 2023 4 min read LangChain + Zapier Natural Language Actions (NLA) We are super excited to team up with Zapier and integrate their new Zapier NLA API into LangChain, which you can now use with your agents and chains. With this integration, you have access to the 5k+ apps and 20k+ actions on Zapier's platform through a natural language API interface. Mar 16, 2023 2 min read Evaluation Evaluation of language models, and by extension applications built on top of language models, is hard. With recent model releases (OpenAI, Anthropic, Google) evaluation is becoming a bigger and bigger issue. People are starting to try to tackle this, with OpenAI releasing OpenAI/evals - focused on evaluating OpenAI models. Mar 14, 2023 3 min read LLMs and SQL Francisco Ingham and Jon Luo are two of the community members leading the change on the SQL integrations. Were really excited to write this blog post with them going over all the tips and tricks theyve learned doing so. Were even more excited to announce that we Mar 13, 2023 8 min read Origin Web Browser [Editor's Note]: This is the second of hopefully many guest posts. We intend to highlight novel applications building on top of LangChain. If you are interested in working with us on such a post, please reach out to harrison@langchain.dev.\n",
"\n",
"Authors: Parth Asawa (pgasawa@), Ayushi Batwara (ayushi.batwara@), Jason Mar 8, 2023 4 min read Prompt Selectors One common complaint we've heard is that the default prompt templates do not work equally well for all models. This became especially pronounced this past week when OpenAI released a ChatGPT API. This new API had a completely new interface (which required new abstractions) and as a result many users Mar 8, 2023 2 min read Chat Models Last week OpenAI released a ChatGPT endpoint. It came marketed with several big improvements, most notably being 10x cheaper and a lot faster. But it also came with a completely new API endpoint. We were able to quickly write a wrapper for this endpoint to let users use it like Mar 6, 2023 6 min read Using the ChatGPT API to evaluate the ChatGPT API OpenAI released a new ChatGPT API yesterday. Lots of people were excited to try it. But how does it actually compare to the existing API? It will take some time before there is a definitive answer, but here are some initial thoughts. Because I'm lazy, I also enrolled the help Mar 2, 2023 5 min read Agent Toolkits Today, we're announcing agent toolkits, a new abstraction that allows developers to create agents designed for a particular use-case (for example, interacting with a relational database or interacting with an OpenAPI spec). We hope to continue developing different toolkits that can enable agents to do amazing feats. Toolkits are supported Mar 1, 2023 3 min read TypeScript Support It's finally here... TypeScript support for LangChain.\n",
"\n",
"What does this mean? It means that all your favorite prompts, chains, and agents are all recreatable in TypeScript natively. Both the Python version and TypeScript version utilize the same serializable format, meaning that artifacts can seamlessly be shared between languages. As an Feb 17, 2023 2 min read Streaming Support in LangChain Were excited to announce streaming support in LangChain. There's been a lot of talk about the best UX for LLM applications, and we believe streaming is at its core. Weve also updated the chat-langchain repo to include streaming and async execution. We hope that this repo can serve Feb 14, 2023 2 min read LangChain + Chroma Today were announcing LangChain's integration with Chroma, the first step on the path to the Modern A.I Stack.\n",
"\n",
"\n",
"LangChain - The A.I-native developer toolkit\n",
"\n",
"We started LangChain with the intent to build a modular and flexible framework for developing A.I-native applications. Some of the use cases Feb 13, 2023 2 min read Page 1 of 2 Older Posts → LangChain © 2023 Sign up Powered by Ghost\u001b[0m\n",
"Thought:\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"The LangChain blog has recently released an open-source auto-evaluator tool for grading LLM question-answer chains and is now releasing an open-source, free-to-use hosted app and API to expand usability. The blog also discusses various opportunities to further improve the LangChain platform.\n"
]
}
],
"source": [
"response = await agent_chain.arun(input=\"Browse to blog.langchain.dev and summarize the text, please.\")\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "0084efd6",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: I can navigate to the xkcd website and extract the latest comic title and alt text to answer the question.\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"navigate_browser\",\n",
" \"action_input\": {\n",
" \"url\": \"https://xkcd.com/\"\n",
" }\n",
"}\n",
"```\n",
"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mNavigating to https://xkcd.com/ returned status code 200\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI can extract the latest comic title and alt text using CSS selectors.\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"get_elements\",\n",
" \"action_input\": {\n",
" \"selector\": \"#ctitle, #comic img\",\n",
" \"attributes\": [\"alt\", \"src\"]\n",
" }\n",
"}\n",
"``` \n",
"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m[{\"alt\": \"Tapetum Lucidum\", \"src\": \"//imgs.xkcd.com/comics/tapetum_lucidum.png\"}]\u001b[0m\n",
"Thought:\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"The latest xkcd comic is titled \"Tapetum Lucidum\" and the image can be found at https://xkcd.com/2565/.\n"
]
}
],
"source": [
"response = await agent_chain.arun(input=\"What's the latest xkcd comic about?\")\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "42473442",
"metadata": {},
"source": [
"## Adding in memory\n",
"\n",
"Here is how you add in memory to this agent"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "b5a0dd2a",
"metadata": {},
"outputs": [],
"source": [
"from langchain.prompts import MessagesPlaceholder\n",
"from langchain.memory import ConversationBufferMemory"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "91b9288f",
"metadata": {},
"outputs": [],
"source": [
"chat_history = MessagesPlaceholder(variable_name=\"chat_history\")\n",
"memory = ConversationBufferMemory(memory_key=\"chat_history\", return_messages=True)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "dba9e0d9",
"metadata": {},
"outputs": [],
"source": [
"agent_chain = initialize_agent(\n",
" tools, \n",
" llm, \n",
" agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, \n",
" verbose=True, \n",
" memory=memory, \n",
" agent_kwargs = {\n",
" \"memory_prompts\": [chat_history],\n",
" \"input_variables\": [\"input\", \"agent_scratchpad\", \"chat_history\"]\n",
" }\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "a9509461",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mAction:\n",
"```\n",
"{\n",
" \"action\": \"Final Answer\",\n",
" \"action_input\": \"Hi Erica! How can I assist you today?\"\n",
"}\n",
"```\n",
"\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"Hi Erica! How can I assist you today?\n"
]
}
],
"source": [
"response = await agent_chain.arun(input=\"Hi I'm Erica.\")\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "412cedd2",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mYour name is Erica.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"Your name is Erica.\n"
]
}
],
"source": [
"response = await agent_chain.arun(input=\"whats my name?\")\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9af1a713",
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -0,0 +1,362 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "406483c4",
"metadata": {},
"source": [
"## Plan and Execute\n",
"\n",
"Plan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by [BabyAGI](https://github.com/yoheinakajima/babyagi) and then the [\"Plan-and-Solve\" paper](https://arxiv.org/abs/2305.04091).\n",
"\n",
"The planning is almost always done by an LLM.\n",
"\n",
"The execution is usually done by a separate agent (equipped with tools)."
]
},
{
"cell_type": "markdown",
"id": "91192118",
"metadata": {},
"source": [
"## Imports"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "6ccd1dc5",
"metadata": {},
"outputs": [],
"source": [
"from langchain.chat_models import ChatOpenAI\n",
"from langchain.experimental.plan_and_execute import PlanAndExecute, load_agent_executor, load_chat_planner\n",
"from langchain.llms import OpenAI\n",
"from langchain import SerpAPIWrapper\n",
"from langchain.agents.tools import Tool\n",
"from langchain import LLMMathChain"
]
},
{
"cell_type": "markdown",
"id": "0b10d200",
"metadata": {},
"source": [
"## Tools"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "3c00f724",
"metadata": {},
"outputs": [],
"source": [
"search = SerpAPIWrapper()\n",
"llm = OpenAI(temperature=0)\n",
"llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True)\n",
"tools = [\n",
" Tool(\n",
" name = \"Search\",\n",
" func=search.run,\n",
" description=\"useful for when you need to answer questions about current events\"\n",
" ),\n",
" Tool(\n",
" name=\"Calculator\",\n",
" func=llm_math_chain.run,\n",
" description=\"useful for when you need to answer questions about math\"\n",
" ),\n",
"]"
]
},
{
"cell_type": "markdown",
"id": "ce38ae84",
"metadata": {},
"source": [
"## Planner, Executor, and Agent"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "0ab2cadd",
"metadata": {},
"outputs": [],
"source": [
"model = ChatOpenAI(temperature=0)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "7b2419f2",
"metadata": {},
"outputs": [],
"source": [
"planner = load_chat_planner(model)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "ed9f518b",
"metadata": {},
"outputs": [],
"source": [
"executor = load_agent_executor(model, tools, verbose=True)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "36943178",
"metadata": {},
"outputs": [],
"source": [
"agent = PlanAndExecute(planner=planner, executer=executor, verbose=True)"
]
},
{
"cell_type": "markdown",
"id": "8be9f1bd",
"metadata": {},
"source": [
"## Run Example"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "4891062e",
"metadata": {
"scrolled": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new PlanAndExecute chain...\u001b[0m\n",
"steps=[Step(value=\"Search for Leo DiCaprio's girlfriend on the internet.\"), Step(value='Find her current age.'), Step(value='Raise her current age to the 0.43 power using a calculator or programming language.'), Step(value='Output the result.'), Step(value=\"Given the above steps taken, respond to the user's original question.\\n\\n\")]\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mAction:\n",
"```\n",
"{\n",
" \"action\": \"Search\",\n",
" \"action_input\": \"Who is Leo DiCaprio's girlfriend?\"\n",
"}\n",
"``` \n",
"\n",
"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mDiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years. He's since been linked to another famous supermodel Gigi Hadid. The power couple were first supposedly an item in September after being spotted getting cozy during a party at New York Fashion Week.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mBased on the previous observation, I can provide the answer to the current objective. \n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"Final Answer\",\n",
" \"action_input\": \"Leo DiCaprio is currently linked to Gigi Hadid.\"\n",
"}\n",
"```\n",
"\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"*****\n",
"\n",
"Step: Search for Leo DiCaprio's girlfriend on the internet.\n",
"\n",
"Response: Leo DiCaprio is currently linked to Gigi Hadid.\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mAction:\n",
"```\n",
"{\n",
" \"action\": \"Search\",\n",
" \"action_input\": \"What is Gigi Hadid's current age?\"\n",
"}\n",
"```\n",
"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m28 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mPrevious steps: steps=[(Step(value=\"Search for Leo DiCaprio's girlfriend on the internet.\"), StepResponse(response='Leo DiCaprio is currently linked to Gigi Hadid.'))]\n",
"\n",
"Current objective: value='Find her current age.'\n",
"\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"Search\",\n",
" \"action_input\": \"What is Gigi Hadid's current age?\"\n",
"}\n",
"```\n",
"\n",
"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m28 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mBased on my search, Gigi Hadid's current age is 26 years old. \n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"Final Answer\",\n",
" \"action_input\": \"Gigi Hadid's current age is 26 years old.\"\n",
"}\n",
"```\n",
"\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"*****\n",
"\n",
"Step: Find her current age.\n",
"\n",
"Response: Gigi Hadid's current age is 26 years old.\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mAction:\n",
"```\n",
"{\n",
" \"action\": \"Calculator\",\n",
" \"action_input\": \"26 ** 0.43\"\n",
"}\n",
"```\n",
"\n",
"\u001b[0m\n",
"\n",
"\u001b[1m> Entering new LLMMathChain chain...\u001b[0m\n",
"26 ** 0.43\u001b[32;1m\u001b[1;3m\n",
"```text\n",
"26 ** 0.43\n",
"```\n",
"...numexpr.evaluate(\"26 ** 0.43\")...\n",
"\u001b[0m\n",
"Answer: \u001b[33;1m\u001b[1;3m4.059182145592686\u001b[0m\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\n",
"Observation: \u001b[33;1m\u001b[1;3mAnswer: 4.059182145592686\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mThe current objective is to raise Gigi Hadid's age to the 0.43 power. \n",
"\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"Calculator\",\n",
" \"action_input\": \"26 ** 0.43\"\n",
"}\n",
"```\n",
"\n",
"\u001b[0m\n",
"\n",
"\u001b[1m> Entering new LLMMathChain chain...\u001b[0m\n",
"26 ** 0.43\u001b[32;1m\u001b[1;3m\n",
"```text\n",
"26 ** 0.43\n",
"```\n",
"...numexpr.evaluate(\"26 ** 0.43\")...\n",
"\u001b[0m\n",
"Answer: \u001b[33;1m\u001b[1;3m4.059182145592686\u001b[0m\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\n",
"Observation: \u001b[33;1m\u001b[1;3mAnswer: 4.059182145592686\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mThe answer to the current objective is 4.059182145592686.\n",
"\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"Final Answer\",\n",
" \"action_input\": \"Gigi Hadid's age raised to the 0.43 power is approximately 4.059 years.\"\n",
"}\n",
"```\n",
"\n",
"\n",
"\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"*****\n",
"\n",
"Step: Raise her current age to the 0.43 power using a calculator or programming language.\n",
"\n",
"Response: Gigi Hadid's age raised to the 0.43 power is approximately 4.059 years.\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mAction:\n",
"```\n",
"{\n",
" \"action\": \"Final Answer\",\n",
" \"action_input\": \"Gigi Hadid's age raised to the 0.43 power is approximately 4.059 years.\"\n",
"}\n",
"```\n",
"\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"*****\n",
"\n",
"Step: Output the result.\n",
"\n",
"Response: Gigi Hadid's age raised to the 0.43 power is approximately 4.059 years.\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mAction:\n",
"```\n",
"{\n",
" \"action\": \"Final Answer\",\n",
" \"action_input\": \"Gigi Hadid's age raised to the 0.43 power is approximately 4.059 years.\"\n",
"}\n",
"```\n",
"\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"*****\n",
"\n",
"Step: Given the above steps taken, respond to the user's original question.\n",
"\n",
"\n",
"\n",
"Response: Gigi Hadid's age raised to the 0.43 power is approximately 4.059 years.\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"\"Gigi Hadid's age raised to the 0.43 power is approximately 4.059 years.\""
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent.run(\"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "aa3ec998",
"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.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -35,7 +35,7 @@
},
{
"cell_type": "code",
"execution_count": 11,
"execution_count": 3,
"id": "16c4dc59",
"metadata": {},
"outputs": [],
@@ -45,7 +45,7 @@
},
{
"cell_type": "code",
"execution_count": 12,
"execution_count": 4,
"id": "46b9489d",
"metadata": {},
"outputs": [
@@ -72,7 +72,7 @@
"'There are 891 rows in the dataframe.'"
]
},
"execution_count": 12,
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
@@ -83,7 +83,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 5,
"id": "a96309be",
"metadata": {},
"outputs": [
@@ -110,18 +110,18 @@
"'30 people have more than 3 siblings.'"
]
},
"execution_count": 6,
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent.run(\"how many people have more than 3 sibligngs\")"
"agent.run(\"how many people have more than 3 siblings\")"
]
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 6,
"id": "964a09f7",
"metadata": {},
"outputs": [
@@ -143,7 +143,7 @@
"Thought:\u001b[32;1m\u001b[1;3m I need to import the math library\n",
"Action: python_repl_ast\n",
"Action Input: import math\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mNone\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I can now calculate the square root\n",
"Action: python_repl_ast\n",
"Action Input: math.sqrt(df['Age'].mean())\u001b[0m\n",
@@ -160,7 +160,7 @@
"'5.449689683556195'"
]
},
"execution_count": 7,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}

View File

@@ -0,0 +1,232 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Gmail Toolkit\n",
"\n",
"This notebook walks through connecting a LangChain email to the Gmail API.\n",
"\n",
"To use this toolkit, you will need to set up your credentials explained in the [Gmail API docs](https://developers.google.com/gmail/api/quickstart/python#authorize_credentials_for_a_desktop_application). Once you've downloaded the `credentials.json` file, you can start using the Gmail API. Once this is done, we'll install the required libraries."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"!pip install --upgrade google-api-python-client > /dev/null\n",
"!pip install --upgrade google-auth-oauthlib > /dev/null\n",
"!pip install --upgrade google-auth-httplib2 > /dev/null\n",
"!pip install beautifulsoup4 > /dev/null # This is optional but is useful for parsing HTML messages"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create the Toolkit\n",
"\n",
"By default the toolkit reads the local `credentials.json` file. You can also manually provide a `Credentials` object."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain.agents.agent_toolkits import GmailToolkit\n",
"\n",
"toolkit = GmailToolkit() "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Customizing Authentication\n",
"\n",
"Behind the scenes, a `googleapi` resource is created using the following methods. \n",
"you can manually build a `googleapi` resource for more auth control. "
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain.tools.gmail.utils import build_resource_service, get_gmail_credentials\n",
"\n",
"# Can review scopes here https://developers.google.com/gmail/api/auth/scopes\n",
"# For instance, readonly scope is 'https://www.googleapis.com/auth/gmail.readonly'\n",
"credentials = get_gmail_credentials(\n",
" token_file='token.json',\n",
" scopes=[\"https://mail.google.com/\"],\n",
" client_secrets_file=\"credentials.json\",\n",
")\n",
"api_resource = build_resource_service(credentials=credentials)\n",
"toolkit = GmailToolkit(api_resource=api_resource)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"[GmailCreateDraft(name='create_gmail_draft', description='Use this tool to create a draft email with the provided message fields.', args_schema=<class 'langchain.tools.gmail.create_draft.CreateDraftSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>),\n",
" GmailSendMessage(name='send_gmail_message', description='Use this tool to send email messages. The input is the message, recipents', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>),\n",
" GmailSearch(name='search_gmail', description=('Use this tool to search for email messages or threads. The input must be a valid Gmail query. The output is a JSON list of the requested resource.',), args_schema=<class 'langchain.tools.gmail.search.SearchArgsSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>),\n",
" GmailGetMessage(name='get_gmail_message', description='Use this tool to fetch an email by message ID. Returns the thread ID, snipet, body, subject, and sender.', args_schema=<class 'langchain.tools.gmail.get_message.SearchArgsSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>),\n",
" GmailGetThread(name='get_gmail_thread', description=('Use this tool to search for email messages. The input must be a valid Gmail query. The output is a JSON list of messages.',), args_schema=<class 'langchain.tools.gmail.get_thread.GetThreadSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>)]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tools = toolkit.get_tools()\n",
"tools"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use within an Agent"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain import OpenAI\n",
"from langchain.agents import initialize_agent, AgentType"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"llm = OpenAI(temperature=0)\n",
"agent = initialize_agent(\n",
" tools=toolkit.get_tools(),\n",
" llm=llm,\n",
" agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"WARNING:root:Failed to load default session, using empty session: 0\n",
"WARNING:root:Failed to persist run: {\"detail\":\"Not Found\"}\n"
]
},
{
"data": {
"text/plain": [
"'I have created a draft email for you to edit. The draft Id is r5681294731961864018.'"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent.run(\"Create a gmail draft for me to edit of a letter from the perspective of a sentient parrot\"\n",
" \" who is looking to collaborate on some research with her\"\n",
" \" estranged friend, a cat. Under no circumstances may you send the message, however.\")"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"WARNING:root:Failed to load default session, using empty session: 0\n",
"WARNING:root:Failed to persist run: {\"detail\":\"Not Found\"}\n"
]
},
{
"data": {
"text/plain": [
"\"The latest email in your drafts is from hopefulparrot@gmail.com with the subject 'Collaboration Opportunity'. The body of the email reads: 'Dear [Friend], I hope this letter finds you well. I am writing to you in the hopes of rekindling our friendship and to discuss the possibility of collaborating on some research together. I know that we have had our differences in the past, but I believe that we can put them aside and work together for the greater good. I look forward to hearing from you. Sincerely, [Parrot]'\""
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent.run(\"Could you search in my drafts for the latest email?\")"
]
},
{
"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.11.2"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

View File

@@ -0,0 +1,167 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"id": "245a954a",
"metadata": {},
"source": [
"# Jira\n",
"\n",
"This notebook goes over how to use the Jira tool.\n",
"The Jira tool allows agents to interact with a given Jira instance, performing actions such as searching for issues and creating issues, the tool wraps the atlassian-python-api library, for more see: https://atlassian-python-api.readthedocs.io/jira.html\n",
"\n",
"To use this tool, you must first set as environment variables:\n",
" JIRA_API_TOKEN\n",
" JIRA_USERNAME\n",
" JIRA_INSTANCE_URL"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "961b3689",
"metadata": {
"vscode": {
"languageId": "shellscript"
},
"ExecuteTime": {
"start_time": "2023-04-17T10:21:18.698672Z",
"end_time": "2023-04-17T10:21:20.168639Z"
}
},
"outputs": [],
"source": [
"%pip install atlassian-python-api"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "34bb5968",
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-17T10:21:22.911233Z",
"end_time": "2023-04-17T10:21:23.730922Z"
}
},
"outputs": [],
"source": [
"import os\n",
"from langchain.agents import AgentType\n",
"from langchain.agents import initialize_agent\n",
"from langchain.agents.agent_toolkits.jira.toolkit import JiraToolkit\n",
"from langchain.llms import OpenAI\n",
"from langchain.utilities.jira import JiraAPIWrapper"
]
},
{
"cell_type": "code",
"execution_count": 4,
"outputs": [],
"source": [
"os.environ[\"JIRA_API_TOKEN\"] = \"abc\"\n",
"os.environ[\"JIRA_USERNAME\"] = \"123\"\n",
"os.environ[\"JIRA_INSTANCE_URL\"] = \"https://jira.atlassian.com\"\n",
"os.environ[\"OPENAI_API_KEY\"] = \"xyz\""
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"start_time": "2023-04-17T10:22:42.499447Z",
"end_time": "2023-04-17T10:22:42.505412Z"
}
}
},
{
"cell_type": "code",
"execution_count": 5,
"id": "ac4910f8",
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-17T10:22:44.664481Z",
"end_time": "2023-04-17T10:22:44.720538Z"
}
},
"outputs": [],
"source": [
"llm = OpenAI(temperature=0)\n",
"jira = JiraAPIWrapper()\n",
"toolkit = JiraToolkit.from_jira_api_wrapper(jira)\n",
"agent = initialize_agent(\n",
" toolkit.get_tools(),\n",
" llm,\n",
" agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n",
" verbose=True\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 9,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I need to create an issue in project PW\n",
"Action: Create Issue\n",
"Action Input: {\"summary\": \"Make more fried rice\", \"description\": \"Reminder to make more fried rice\", \"issuetype\": {\"name\": \"Task\"}, \"priority\": {\"name\": \"Low\"}, \"project\": {\"key\": \"PW\"}}\u001B[0m\n",
"Observation: \u001B[38;5;200m\u001B[1;3mNone\u001B[0m\n",
"Thought:\u001B[32;1m\u001B[1;3m I now know the final answer\n",
"Final Answer: A new issue has been created in project PW with the summary \"Make more fried rice\" and description \"Reminder to make more fried rice\".\u001B[0m\n",
"\n",
"\u001B[1m> Finished chain.\u001B[0m\n"
]
},
{
"data": {
"text/plain": "'A new issue has been created in project PW with the summary \"Make more fried rice\" and description \"Reminder to make more fried rice\".'"
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent.run(\"make a new issue in project PW to remind me to make more fried rice\")"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"start_time": "2023-04-17T10:23:33.662454Z",
"end_time": "2023-04-17T10:23:38.121883Z"
}
}
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.7"
},
"vscode": {
"interpreter": {
"hash": "53f3bc57609c7a84333bb558594977aa5b4026b1d6070b93987956689e367341"
}
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -15,7 +15,7 @@
"id": "a389367b",
"metadata": {},
"source": [
"# 1st example: hierarchical planning agent\n",
"## 1st example: hierarchical planning agent\n",
"\n",
"In this example, we'll consider an approach called hierarchical planning, common in robotics and appearing in recent works for LLMs X robotics. We'll see it's a viable approach to start working with a massive API spec AND to assist with user queries that require multiple steps against the API.\n",
"\n",
@@ -31,7 +31,7 @@
"id": "4b6ecf6e",
"metadata": {},
"source": [
"## To start, let's collect some OpenAPI specs."
"### To start, let's collect some OpenAPI specs."
]
},
{
@@ -169,7 +169,7 @@
"id": "76349780",
"metadata": {},
"source": [
"## How big is this spec?"
"### How big is this spec?"
]
},
{
@@ -229,7 +229,7 @@
"id": "cbc4964e",
"metadata": {},
"source": [
"## Let's see some examples!\n",
"### Let's see some examples!\n",
"\n",
"Starting with GPT-4. (Some robustness iterations under way for GPT-3 family.)"
]
@@ -759,7 +759,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.0"
"version": "3.9.1"
}
},
"nbformat": 4,

View File

@@ -0,0 +1,409 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "c7ad998d",
"metadata": {},
"source": [
"# Natural Language APIs\n",
"\n",
"Natural Language API Toolkits (NLAToolkits) permit LangChain Agents to efficiently plan and combine calls across endpoints. This notebook demonstrates a sample composition of the Speak, Klarna, and Spoonacluar APIs.\n",
"\n",
"For a detailed walkthrough of the OpenAPI chains wrapped within the NLAToolkit, see the [OpenAPI Operation Chain](openapi.ipynb) notebook.\n",
"\n",
"### First, import dependencies and load the LLM"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "6593f793",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from typing import List, Optional\n",
"from langchain.chains import LLMChain\n",
"from langchain.llms import OpenAI\n",
"from langchain.prompts import PromptTemplate\n",
"from langchain.requests import Requests\n",
"from langchain.tools import APIOperation, OpenAPISpec\n",
"from langchain.agents import AgentType, Tool, initialize_agent\n",
"from langchain.agents.agent_toolkits import NLAToolkit"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "dd720860",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Select the LLM to use. Here, we use text-davinci-003\n",
"llm = OpenAI(temperature=0, max_tokens=700) # You can swap between different core LLM's here."
]
},
{
"cell_type": "markdown",
"id": "4cadac9d",
"metadata": {
"tags": []
},
"source": [
"### Next, load the Natural Language API Toolkits"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "6b208ab0",
"metadata": {
"scrolled": true,
"tags": []
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.\n",
"Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.\n",
"Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.\n"
]
}
],
"source": [
"speak_toolkit = NLAToolkit.from_llm_and_url(llm, \"https://api.speak.com/openapi.yaml\")\n",
"klarna_toolkit = NLAToolkit.from_llm_and_url(llm, \"https://www.klarna.com/us/shopping/public/openai/v0/api-docs/\")"
]
},
{
"cell_type": "markdown",
"id": "16c7336f",
"metadata": {},
"source": [
"### Create the Agent"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "730a0dc2-b4d0-46d5-a1e9-583803220973",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Slightly tweak the instructions from the default agent\n",
"openapi_format_instructions = \"\"\"Use the following format:\n",
"\n",
"Question: the input question you must answer\n",
"Thought: you should always think about what to do\n",
"Action: the action to take, should be one of [{tool_names}]\n",
"Action Input: what to instruct the AI Action representative.\n",
"Observation: The Agent's response\n",
"... (this Thought/Action/Action Input/Observation can repeat N times)\n",
"Thought: I now know the final answer. User can't see any of my observations, API responses, links, or tools.\n",
"Final Answer: the final answer to the original input question with the right amount of detail\n",
"\n",
"When responding with your Final Answer, remember that the person you are responding to CANNOT see any of your Thought/Action/Action Input/Observations, so if there is any relevant information there you need to include it explicitly in your response.\"\"\""
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "40a979c3",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"natural_language_tools = speak_toolkit.get_tools() + klarna_toolkit.get_tools()\n",
"mrkl = initialize_agent(natural_language_tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, \n",
" verbose=True, agent_kwargs={\"format_instructions\":openapi_format_instructions})"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "794380ba",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out what kind of Italian clothes are available\n",
"Action: Open_AI_Klarna_product_Api.productsUsingGET\n",
"Action Input: Italian clothes\u001b[0m\n",
"Observation: \u001b[31;1m\u001b[1;3mThe API response contains two products from the Alé brand in Italian Blue. The first is the Alé Colour Block Short Sleeve Jersey Men - Italian Blue, which costs $86.49, and the second is the Alé Dolid Flash Jersey Men - Italian Blue, which costs $40.00.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know what kind of Italian clothes are available and how much they cost.\n",
"Final Answer: You can buy two products from the Alé brand in Italian Blue for your end of year party. The Alé Colour Block Short Sleeve Jersey Men - Italian Blue costs $86.49, and the Alé Dolid Flash Jersey Men - Italian Blue costs $40.00.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"'You can buy two products from the Alé brand in Italian Blue for your end of year party. The Alé Colour Block Short Sleeve Jersey Men - Italian Blue costs $86.49, and the Alé Dolid Flash Jersey Men - Italian Blue costs $40.00.'"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"mrkl.run(\"I have an end of year party for my Italian class and have to buy some Italian clothes for it\")"
]
},
{
"cell_type": "markdown",
"id": "c61d92a8",
"metadata": {},
"source": [
"### Using Auth + Adding more Endpoints\n",
"\n",
"Some endpoints may require user authentication via things like access tokens. Here we show how to pass in the authentication information via the `Requests` wrapper object.\n",
"\n",
"Since each NLATool exposes a concisee natural language interface to its wrapped API, the top level conversational agent has an easier job incorporating each endpoint to satisfy a user's request."
]
},
{
"cell_type": "markdown",
"id": "f0d132cc",
"metadata": {},
"source": [
"**Adding the Spoonacular endpoints.**\n",
"\n",
"1. Go to the [Spoonacular API Console](https://spoonacular.com/food-api/console#Profile) and make a free account.\n",
"2. Click on `Profile` and copy your API key below."
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "c2368b9c",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"spoonacular_api_key = \"\" # Copy from the API Console"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "fbd97c28-fef6-41b5-9600-a9611a32bfb3",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Attempting to load an OpenAPI 3.0.0 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.\n",
"Unsupported APIPropertyLocation \"header\" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter\n",
"Unsupported APIPropertyLocation \"header\" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter\n"
]
}
],
"source": [
"requests = Requests(headers={\"x-api-key\": spoonacular_api_key})\n",
"spoonacular_toolkit = NLAToolkit.from_llm_and_url(\n",
" llm, \n",
" \"https://spoonacular.com/application/frontend/downloads/spoonacular-openapi-3.json\",\n",
" requests=requests,\n",
" max_text_length=1800, # If you want to truncate the response text\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "81a6edac",
"metadata": {
"scrolled": true,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"34 tools loaded.\n"
]
}
],
"source": [
"natural_language_api_tools = (speak_toolkit.get_tools() \n",
" + klarna_toolkit.get_tools() \n",
" + spoonacular_toolkit.get_tools()[:30]\n",
" )\n",
"print(f\"{len(natural_language_api_tools)} tools loaded.\")"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "831f772d-5cd1-4467-b494-a3172af2ff48",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Create an agent with the new tools\n",
"mrkl = initialize_agent(natural_language_api_tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, \n",
" verbose=True, agent_kwargs={\"format_instructions\":openapi_format_instructions})"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "0385e04b",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Make the query more complex!\n",
"user_input = (\n",
" \"I'm learning Italian, and my language class is having an end of year party... \"\n",
" \" Could you help me find an Italian outfit to wear and\"\n",
" \" an appropriate recipe to prepare so I can present for the class in Italian?\"\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "6ebd3f55",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find a recipe and an outfit that is Italian-themed.\n",
"Action: spoonacular_API.searchRecipes\n",
"Action Input: Italian\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mThe API response contains 10 Italian recipes, including Turkey Tomato Cheese Pizza, Broccolini Quinoa Pilaf, Bruschetta Style Pork & Pasta, Salmon Quinoa Risotto, Italian Tuna Pasta, Roasted Brussels Sprouts With Garlic, Asparagus Lemon Risotto, Italian Steamed Artichokes, Crispy Italian Cauliflower Poppers Appetizer, and Pappa Al Pomodoro.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find an Italian-themed outfit.\n",
"Action: Open_AI_Klarna_product_Api.productsUsingGET\n",
"Action Input: Italian\u001b[0m\n",
"Observation: \u001b[31;1m\u001b[1;3mI found 10 products related to 'Italian' in the API response. These products include Italian Gold Sparkle Perfectina Necklace - Gold, Italian Design Miami Cuban Link Chain Necklace - Gold, Italian Gold Miami Cuban Link Chain Necklace - Gold, Italian Gold Herringbone Necklace - Gold, Italian Gold Claddagh Ring - Gold, Italian Gold Herringbone Chain Necklace - Gold, Garmin QuickFit 22mm Italian Vacchetta Leather Band, Macy's Italian Horn Charm - Gold, Dolce & Gabbana Light Blue Italian Love Pour Homme EdT 1.7 fl oz.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer.\n",
"Final Answer: To present for your Italian language class, you could wear an Italian Gold Sparkle Perfectina Necklace - Gold, an Italian Design Miami Cuban Link Chain Necklace - Gold, or an Italian Gold Miami Cuban Link Chain Necklace - Gold. For a recipe, you could make Turkey Tomato Cheese Pizza, Broccolini Quinoa Pilaf, Bruschetta Style Pork & Pasta, Salmon Quinoa Risotto, Italian Tuna Pasta, Roasted Brussels Sprouts With Garlic, Asparagus Lemon Risotto, Italian Steamed Artichokes, Crispy Italian Cauliflower Poppers Appetizer, or Pappa Al Pomodoro.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"'To present for your Italian language class, you could wear an Italian Gold Sparkle Perfectina Necklace - Gold, an Italian Design Miami Cuban Link Chain Necklace - Gold, or an Italian Gold Miami Cuban Link Chain Necklace - Gold. For a recipe, you could make Turkey Tomato Cheese Pizza, Broccolini Quinoa Pilaf, Bruschetta Style Pork & Pasta, Salmon Quinoa Risotto, Italian Tuna Pasta, Roasted Brussels Sprouts With Garlic, Asparagus Lemon Risotto, Italian Steamed Artichokes, Crispy Italian Cauliflower Poppers Appetizer, or Pappa Al Pomodoro.'"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"mrkl.run(user_input)"
]
},
{
"cell_type": "markdown",
"id": "a2959462",
"metadata": {},
"source": [
"## Thank you!"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "6fcda5f0",
"metadata": {
"scrolled": true
},
"outputs": [
{
"data": {
"text/plain": [
"\"In Italian, you can say 'Buon appetito' to someone to wish them to enjoy their meal. This phrase is commonly used in Italy when someone is about to eat, often at the beginning of a meal. It's similar to saying 'Bon appétit' in French or 'Guten Appetit' in German.\""
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"natural_language_api_tools[1].run(\"Tell the LangChain audience to 'enjoy the meal' in Italian, please!\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ab366dc0",
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -118,7 +118,7 @@
}
],
"source": [
"agent.run(\"how many people have more than 3 sibligngs\")"
"agent.run(\"how many people have more than 3 siblings\")"
]
},
{

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,219 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"id": "0e499e90-7a6d-4fab-8aab-31a4df417601",
"metadata": {},
"source": [
"# PowerBI Dataset Agent\n",
"\n",
"This notebook showcases an agent designed to interact with a Power BI Dataset. The agent is designed to answer more general questions about a dataset, as well as recover from errors.\n",
"\n",
"Note that, as this agent is in active development, all answers might not be correct. It runs against the [executequery endpoint](https://learn.microsoft.com/en-us/rest/api/power-bi/datasets/execute-queries), which does not allow deletes.\n",
"\n",
"### Some notes\n",
"- It relies on authentication with the azure.identity package, which can be installed with `pip install azure-identity`. Alternatively you can create the powerbi dataset with a token as a string without supplying the credentials.\n",
"- You can also supply a username to impersonate for use with datasets that have RLS enabled. \n",
"- The toolkit uses a LLM to create the query from the question, the agent uses the LLM for the overall execution.\n",
"- Testing was done mostly with a `text-davinci-003` model, codex models did not seem to perform ver well."
]
},
{
"cell_type": "markdown",
"id": "ec927ac6-9b2a-4e8a-9a6e-3e429191875c",
"metadata": {
"tags": []
},
"source": [
"## Initialization"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "53422913-967b-4f2a-8022-00269c1be1b1",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain.agents.agent_toolkits import create_pbi_agent\n",
"from langchain.agents.agent_toolkits import PowerBIToolkit\n",
"from langchain.utilities.powerbi import PowerBIDataset\n",
"from langchain.llms.openai import AzureOpenAI\n",
"from langchain.agents import AgentExecutor\n",
"from azure.identity import DefaultAzureCredential"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "090f3699-79c6-4ce1-ab96-a94f0121fd64",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"fast_llm = AzureOpenAI(temperature=0.5, max_tokens=1000, deployment_name=\"gpt-35-turbo\", verbose=True)\n",
"smart_llm = AzureOpenAI(temperature=0, max_tokens=100, deployment_name=\"gpt-4\", verbose=True)\n",
"\n",
"toolkit = PowerBIToolkit(\n",
" powerbi=PowerBIDataset(dataset_id=\"<dataset_id>\", table_names=['table1', 'table2'], credential=DefaultAzureCredential()), \n",
" llm=smart_llm\n",
")\n",
"\n",
"agent_executor = create_pbi_agent(\n",
" llm=fast_llm,\n",
" toolkit=toolkit,\n",
" verbose=True,\n",
")"
]
},
{
"cell_type": "markdown",
"id": "36ae48c7-cb08-4fef-977e-c7d4b96a464b",
"metadata": {},
"source": [
"## Example: describing a table"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ff70e83d-5ad0-4fc7-bb96-27d82ac166d7",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"agent_executor.run(\"Describe table1\")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "9abcfe8e-1868-42a4-8345-ad2d9b44c681",
"metadata": {},
"source": [
"## Example: simple query on a table\n",
"In this example, the agent actually figures out the correct query to get a row count of the table."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bea76658-a65b-47e2-b294-6d52c5556246",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"agent_executor.run(\"How many records are in table1?\")"
]
},
{
"cell_type": "markdown",
"id": "6fbc26af-97e4-4a21-82aa-48bdc992da26",
"metadata": {},
"source": [
"## Example: running queries"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "17bea710-4a23-4de0-b48e-21d57be48293",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"agent_executor.run(\"How many records are there by dimension1 in table2?\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "474dddda-c067-4eeb-98b1-e763ee78b18c",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"agent_executor.run(\"What unique values are there for dimensions2 in table2\")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "6fd950e4",
"metadata": {},
"source": [
"## Example: add your own few-shot prompts"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "87d677f9",
"metadata": {},
"outputs": [],
"source": [
"#fictional example\n",
"few_shots = \"\"\"\n",
"Question: How many rows are in the table revenue?\n",
"DAX: EVALUATE ROW(\"Number of rows\", COUNTROWS(revenue_details))\n",
"----\n",
"Question: How many rows are in the table revenue where year is not empty?\n",
"DAX: EVALUATE ROW(\"Number of rows\", COUNTROWS(FILTER(revenue_details, revenue_details[year] <> \"\")))\n",
"----\n",
"Question: What was the average of value in revenue in dollars?\n",
"DAX: EVALUATE ROW(\"Average\", AVERAGE(revenue_details[dollar_value]))\n",
"----\n",
"\"\"\"\n",
"toolkit = PowerBIToolkit(\n",
" powerbi=PowerBIDataset(dataset_id=\"<dataset_id>\", table_names=['table1', 'table2'], credential=DefaultAzureCredential()), \n",
" llm=smart_llm,\n",
" examples=few_shots,\n",
")\n",
"agent_executor = create_pbi_agent(\n",
" llm=fast_llm,\n",
" toolkit=toolkit,\n",
" verbose=True,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "33f4bb43",
"metadata": {},
"outputs": [],
"source": [
"agent_executor.run(\"What was the maximum of value in revenue in dollars in 2022?\")"
]
}
],
"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.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -12,7 +12,7 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 4,
"id": "f98e9c90-5c37-4fb9-af3e-d09693af8543",
"metadata": {
"tags": []
@@ -27,7 +27,7 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 5,
"id": "cc422f53-c51c-4694-a834-72ecd1e68363",
"metadata": {
"tags": []
@@ -206,9 +206,9 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "LangChain",
"language": "python",
"name": "python3"
"name": "langchain"
},
"language_info": {
"codemirror_mode": {
@@ -220,7 +220,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.1"
"version": "3.9.16"
}
},
"nbformat": 4,

View File

@@ -0,0 +1,398 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Spark Dataframe Agent\n",
"\n",
"This notebook shows how to use agents to interact with a Spark dataframe and Spark Connect. It is mostly optimized for question answering.\n",
"\n",
"**NOTE: this agent calls the Python agent under the hood, which executes LLM generated Python code - this can be bad if the LLM generated Python code is harmful. Use cautiously.**"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import create_spark_dataframe_agent\n",
"import os\n",
"\n",
"os.environ[\"OPENAI_API_KEY\"] = \"...input your openai api key here...\""
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"+-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+\n",
"|PassengerId|Survived|Pclass| Name| Sex| Age|SibSp|Parch| Ticket| Fare|Cabin|Embarked|\n",
"+-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+\n",
"| 1| 0| 3|Braund, Mr. Owen ...| male|22.0| 1| 0| A/5 21171| 7.25| null| S|\n",
"| 2| 1| 1|Cumings, Mrs. Joh...|female|38.0| 1| 0| PC 17599|71.2833| C85| C|\n",
"| 3| 1| 3|Heikkinen, Miss. ...|female|26.0| 0| 0|STON/O2. 3101282| 7.925| null| S|\n",
"| 4| 1| 1|Futrelle, Mrs. Ja...|female|35.0| 1| 0| 113803| 53.1| C123| S|\n",
"| 5| 0| 3|Allen, Mr. Willia...| male|35.0| 0| 0| 373450| 8.05| null| S|\n",
"| 6| 0| 3| Moran, Mr. James| male|null| 0| 0| 330877| 8.4583| null| Q|\n",
"| 7| 0| 1|McCarthy, Mr. Tim...| male|54.0| 0| 0| 17463|51.8625| E46| S|\n",
"| 8| 0| 3|Palsson, Master. ...| male| 2.0| 3| 1| 349909| 21.075| null| S|\n",
"| 9| 1| 3|Johnson, Mrs. Osc...|female|27.0| 0| 2| 347742|11.1333| null| S|\n",
"| 10| 1| 2|Nasser, Mrs. Nich...|female|14.0| 1| 0| 237736|30.0708| null| C|\n",
"| 11| 1| 3|Sandstrom, Miss. ...|female| 4.0| 1| 1| PP 9549| 16.7| G6| S|\n",
"| 12| 1| 1|Bonnell, Miss. El...|female|58.0| 0| 0| 113783| 26.55| C103| S|\n",
"| 13| 0| 3|Saundercock, Mr. ...| male|20.0| 0| 0| A/5. 2151| 8.05| null| S|\n",
"| 14| 0| 3|Andersson, Mr. An...| male|39.0| 1| 5| 347082| 31.275| null| S|\n",
"| 15| 0| 3|Vestrom, Miss. Hu...|female|14.0| 0| 0| 350406| 7.8542| null| S|\n",
"| 16| 1| 2|Hewlett, Mrs. (Ma...|female|55.0| 0| 0| 248706| 16.0| null| S|\n",
"| 17| 0| 3|Rice, Master. Eugene| male| 2.0| 4| 1| 382652| 29.125| null| Q|\n",
"| 18| 1| 2|Williams, Mr. Cha...| male|null| 0| 0| 244373| 13.0| null| S|\n",
"| 19| 0| 3|Vander Planke, Mr...|female|31.0| 1| 0| 345763| 18.0| null| S|\n",
"| 20| 1| 3|Masselmani, Mrs. ...|female|null| 0| 0| 2649| 7.225| null| C|\n",
"+-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+\n",
"only showing top 20 rows\n",
"\n"
]
}
],
"source": [
"from langchain.llms import OpenAI\n",
"from pyspark.sql import SparkSession\n",
"\n",
"spark = SparkSession.builder.getOrCreate()\n",
"csv_file_path = \"titanic.csv\"\n",
"df = spark.read.csv(csv_file_path, header=True, inferSchema=True)\n",
"df.show()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"agent = create_spark_dataframe_agent(llm=OpenAI(temperature=0), df=df, verbose=True)\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: I need to find out the size of the dataframe\n",
"Action: python_repl_ast\n",
"Action Input: df.count()\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m891\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: There are 891 rows in the dataframe.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"'There are 891 rows in the dataframe.'"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent.run(\"how many rows are there?\")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: I need to find out how many people have more than 3 siblings\n",
"Action: python_repl_ast\n",
"Action Input: df.filter(df.SibSp > 3).count()\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m30\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: 30 people have more than 3 siblings.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"'30 people have more than 3 siblings.'"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent.run(\"how many people have more than 3 siblings\")"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: I need to get the average age first\n",
"Action: python_repl_ast\n",
"Action Input: df.agg({\"Age\": \"mean\"}).collect()[0][0]\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m29.69911764705882\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now have the average age, I need to get the square root\n",
"Action: python_repl_ast\n",
"Action Input: math.sqrt(29.69911764705882)\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mname 'math' is not defined\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to import math first\n",
"Action: python_repl_ast\n",
"Action Input: import math\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now have the math library imported, I can get the square root\n",
"Action: python_repl_ast\n",
"Action Input: math.sqrt(29.69911764705882)\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m5.449689683556195\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: 5.449689683556195\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"'5.449689683556195'"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent.run(\"whats the square root of the average age?\")"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"spark.stop()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Spark Connect Example"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# in apache-spark root directory. (tested here with \"spark-3.4.0-bin-hadoop3 and later\")\n",
"# To launch Spark with support for Spark Connect sessions, run the start-connect-server.sh script.\n",
"!./sbin/start-connect-server.sh --packages org.apache.spark:spark-connect_2.12:3.4.0"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"23/05/08 10:06:09 WARN Utils: Service 'SparkUI' could not bind on port 4040. Attempting port 4041.\n"
]
}
],
"source": [
"from pyspark.sql import SparkSession\n",
"\n",
"# Now that the Spark server is running, we can connect to it remotely using Spark Connect. We do this by \n",
"# creating a remote Spark session on the client where our application runs. Before we can do that, we need \n",
"# to make sure to stop the existing regular Spark session because it cannot coexist with the remote \n",
"# Spark Connect session we are about to create.\n",
"SparkSession.builder.master(\"local[*]\").getOrCreate().stop()"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"# The command we used above to launch the server configured Spark to run as localhost:15002. \n",
"# So now we can create a remote Spark session on the client using the following command.\n",
"spark = SparkSession.builder.remote(\"sc://localhost:15002\").getOrCreate()"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"+-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+\n",
"|PassengerId|Survived|Pclass| Name| Sex| Age|SibSp|Parch| Ticket| Fare|Cabin|Embarked|\n",
"+-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+\n",
"| 1| 0| 3|Braund, Mr. Owen ...| male|22.0| 1| 0| A/5 21171| 7.25| null| S|\n",
"| 2| 1| 1|Cumings, Mrs. Joh...|female|38.0| 1| 0| PC 17599|71.2833| C85| C|\n",
"| 3| 1| 3|Heikkinen, Miss. ...|female|26.0| 0| 0|STON/O2. 3101282| 7.925| null| S|\n",
"| 4| 1| 1|Futrelle, Mrs. Ja...|female|35.0| 1| 0| 113803| 53.1| C123| S|\n",
"| 5| 0| 3|Allen, Mr. Willia...| male|35.0| 0| 0| 373450| 8.05| null| S|\n",
"| 6| 0| 3| Moran, Mr. James| male|null| 0| 0| 330877| 8.4583| null| Q|\n",
"| 7| 0| 1|McCarthy, Mr. Tim...| male|54.0| 0| 0| 17463|51.8625| E46| S|\n",
"| 8| 0| 3|Palsson, Master. ...| male| 2.0| 3| 1| 349909| 21.075| null| S|\n",
"| 9| 1| 3|Johnson, Mrs. Osc...|female|27.0| 0| 2| 347742|11.1333| null| S|\n",
"| 10| 1| 2|Nasser, Mrs. Nich...|female|14.0| 1| 0| 237736|30.0708| null| C|\n",
"| 11| 1| 3|Sandstrom, Miss. ...|female| 4.0| 1| 1| PP 9549| 16.7| G6| S|\n",
"| 12| 1| 1|Bonnell, Miss. El...|female|58.0| 0| 0| 113783| 26.55| C103| S|\n",
"| 13| 0| 3|Saundercock, Mr. ...| male|20.0| 0| 0| A/5. 2151| 8.05| null| S|\n",
"| 14| 0| 3|Andersson, Mr. An...| male|39.0| 1| 5| 347082| 31.275| null| S|\n",
"| 15| 0| 3|Vestrom, Miss. Hu...|female|14.0| 0| 0| 350406| 7.8542| null| S|\n",
"| 16| 1| 2|Hewlett, Mrs. (Ma...|female|55.0| 0| 0| 248706| 16.0| null| S|\n",
"| 17| 0| 3|Rice, Master. Eugene| male| 2.0| 4| 1| 382652| 29.125| null| Q|\n",
"| 18| 1| 2|Williams, Mr. Cha...| male|null| 0| 0| 244373| 13.0| null| S|\n",
"| 19| 0| 3|Vander Planke, Mr...|female|31.0| 1| 0| 345763| 18.0| null| S|\n",
"| 20| 1| 3|Masselmani, Mrs. ...|female|null| 0| 0| 2649| 7.225| null| C|\n",
"+-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+\n",
"only showing top 20 rows\n",
"\n"
]
}
],
"source": [
"csv_file_path = \"titanic.csv\"\n",
"df = spark.read.csv(csv_file_path, header=True, inferSchema=True)\n",
"df.show()"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import create_spark_dataframe_agent\n",
"from langchain.llms import OpenAI\n",
"import os\n",
"\n",
"os.environ[\"OPENAI_API_KEY\"] = \"...input your openai api key here...\"\n",
"\n",
"agent = create_spark_dataframe_agent(llm=OpenAI(temperature=0), df=df, verbose=True)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m\n",
"Thought: I need to find the row with the highest fare\n",
"Action: python_repl_ast\n",
"Action Input: df.sort(df.Fare.desc()).first()\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mRow(PassengerId=259, Survived=1, Pclass=1, Name='Ward, Miss. Anna', Sex='female', Age=35.0, SibSp=0, Parch=0, Ticket='PC 17755', Fare=512.3292, Cabin=None, Embarked='C')\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the name of the person who bought the most expensive ticket\n",
"Final Answer: Miss. Anna Ward\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"'Miss. Anna Ward'"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent.run(\"\"\"\n",
"who bought the most expensive ticket?\n",
"You can find all supported function types in https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/dataframe.html\n",
"\"\"\")"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"spark.stop()"
]
}
],
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -24,6 +24,7 @@ Next, we have some examples of customizing and generically working with tools
./tools/custom_tools.ipynb
./tools/multi_input_tool.ipynb
./tools/tool_input_validation.ipynb
In this documentation we cover generic tooling functionality (eg how to create your own)

View File

@@ -1,6 +1,7 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"id": "5436020b",
"metadata": {},
@@ -9,28 +10,29 @@
"\n",
"When constructing your own agent, you will need to provide it with a list of Tools that it can use. Besides the actual function that is called, the Tool consists of several components:\n",
"\n",
"- name (str), is required\n",
"- description (str), is optional\n",
"- name (str), is required and must be unique within a set of tools provided to an agent\n",
"- description (str), is optional but recommended, as it is used by an agent to determine tool use\n",
"- return_direct (bool), defaults to False\n",
"- args_schema (Pydantic BaseModel), is optional but recommended, can be used to provide more information (e.g., few-shot examples) or validation for expected parameters.\n",
"\n",
"The function that should be called when the tool is selected should take as input a single string and return a single string.\n",
"\n",
"There are two ways to define a tool, we will cover both in the example below."
"There are two main ways to define a tool, we will cover both in the example below."
]
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 1,
"id": "1aaba18c",
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Import things that are needed generically\n",
"from langchain.agents import initialize_agent, Tool\n",
"from langchain.agents import AgentType\n",
"from langchain.tools import BaseTool\n",
"from langchain.llms import OpenAI\n",
"from langchain import LLMMathChain, SerpAPIWrapper"
"from langchain import LLMMathChain, SerpAPIWrapper\n",
"from langchain.agents import AgentType, initialize_agent\n",
"from langchain.chat_models import ChatOpenAI\n",
"from langchain.tools import BaseTool, StructuredTool, Tool, tool"
]
},
{
@@ -43,63 +45,112 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 2,
"id": "36ed392e",
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"llm = OpenAI(temperature=0)"
"llm = ChatOpenAI(temperature=0)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "f8bc72c2",
"metadata": {},
"source": [
"## Completely New Tools \n",
"First, we show how to create completely new tools from scratch.\n",
"## Completely New Tools - String Input and Output\n",
"\n",
"The simplest tools accept a single query string and return a string output. If your tool function requires multiple arguments, you might want to skip down to the `StructuredTool` section below.\n",
"\n",
"There are two ways to do this: either by using the Tool dataclass, or by subclassing the BaseTool class."
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "b63fcc3b",
"metadata": {},
"source": [
"### Tool dataclass"
"### Tool dataclass\n",
"\n",
"The 'Tool' dataclass wraps functions that accept a single string input and returns a string output."
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "56ff7670",
"metadata": {},
"outputs": [],
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/wfh/code/lc/lckg/langchain/chains/llm_math/base.py:50: UserWarning: Directly instantiating an LLMMathChain with an llm is deprecated. Please instantiate with llm_chain argument or using the from_llm class method.\n",
" warnings.warn(\n"
]
}
],
"source": [
"# Load the tool configs that are needed.\n",
"search = SerpAPIWrapper()\n",
"llm_math_chain = LLMMathChain(llm=llm, verbose=True)\n",
"tools = [\n",
" Tool(\n",
" name = \"Search\",\n",
" Tool.from_function(\n",
" func=search.run,\n",
" name = \"Search\",\n",
" description=\"useful for when you need to answer questions about current events\"\n",
" # coroutine= ... <- you can specify an async method if desired as well\n",
" ),\n",
" Tool(\n",
" name=\"Calculator\",\n",
" func=llm_math_chain.run,\n",
" description=\"useful for when you need to answer questions about math\"\n",
" )\n",
"]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "e9b560f7",
"metadata": {},
"source": [
"You can also define a custom `args_schema`` to provide more information about inputs."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "5b93047d",
"id": "631361e7",
"metadata": {},
"outputs": [],
"source": [
"from pydantic import BaseModel, Field\n",
"\n",
"class CalculatorInput(BaseModel):\n",
" question: str = Field()\n",
" \n",
"\n",
"tools.append(\n",
" Tool.from_function(\n",
" func=llm_math_chain.run,\n",
" name=\"Calculator\",\n",
" description=\"useful for when you need to answer questions about math\",\n",
" args_schema=CalculatorInput\n",
" # coroutine= ... <- you can specify an async method if desired as well\n",
" )\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "5b93047d",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Construct the agent. We will use the default agent type here.\n",
"# See documentation for a full list of options.\n",
@@ -108,9 +159,11 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 6,
"id": "6f96a891",
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
@@ -119,29 +172,34 @@
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.\n",
"\u001b[32;1m\u001b[1;3mI need to find out Leo DiCaprio's girlfriend's name and her age\n",
"Action: Search\n",
"Action Input: \"Leo DiCaprio girlfriend\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mCamila Morrone\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now need to calculate her age raised to the 0.43 power\n",
"Observation: \u001b[36;1m\u001b[1;3mAfter rumours of a romance with Gigi Hadid, the Oscar winner has seemingly moved on. First being linked to the television personality in September 2022, it appears as if his \"age bracket\" has moved up. This follows his rumoured relationship with mere 19-year-old Eden Polani.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI still need to find out his current girlfriend's name and age\n",
"Action: Search\n",
"Action Input: \"Leo DiCaprio current girlfriend\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mJust Jared on Instagram: “Leonardo DiCaprio & girlfriend Camila Morrone couple up for a lunch date!\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mNow that I know his girlfriend's name is Camila Morrone, I need to find her current age\n",
"Action: Search\n",
"Action Input: \"Camila Morrone age\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m25 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mNow that I have her age, I need to calculate her age raised to the 0.43 power\n",
"Action: Calculator\n",
"Action Input: 22^0.43\u001b[0m\n",
"Action Input: 25^(0.43)\u001b[0m\n",
"\n",
"\u001b[1m> Entering new LLMMathChain chain...\u001b[0m\n",
"22^0.43\u001b[32;1m\u001b[1;3m\n",
"```python\n",
"import math\n",
"print(math.pow(22, 0.43))\n",
"25^(0.43)\u001b[32;1m\u001b[1;3m```text\n",
"25**(0.43)\n",
"```\n",
"...numexpr.evaluate(\"25**(0.43)\")...\n",
"\u001b[0m\n",
"Answer: \u001b[33;1m\u001b[1;3m3.777824273683966\n",
"\u001b[0m\n",
"Answer: \u001b[33;1m\u001b[1;3m3.991298452658078\u001b[0m\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\n",
"Observation: \u001b[33;1m\u001b[1;3mAnswer: 3.777824273683966\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Camila Morrone's age raised to the 0.43 power is 3.777824273683966.\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mAnswer: 3.991298452658078\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI now know the final answer\n",
"Final Answer: Camila Morrone's current age raised to the 0.43 power is approximately 3.99.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -149,10 +207,10 @@
{
"data": {
"text/plain": [
"\"Camila Morrone's age raised to the 0.43 power is 3.777824273683966.\""
"\"Camila Morrone's current age raised to the 0.43 power is approximately 3.99.\""
]
},
"execution_count": 5,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
@@ -162,70 +220,75 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "6f12eaf0",
"metadata": {},
"source": [
"### Subclassing the BaseTool class"
"### Subclassing the BaseTool class\n",
"\n",
"You can also directly subclass `BaseTool`. This is useful if you want more control over the instance variables or if you want to propagate callbacks to nested chains or other tools."
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "c58a7c40",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from typing import Optional, Type\n",
"\n",
"from langchain.callbacks.manager import AsyncCallbackManagerForToolRun, CallbackManagerForToolRun\n",
"\n",
"class CustomSearchTool(BaseTool):\n",
" name = \"custom_search\"\n",
" description = \"useful for when you need to answer questions about current events\"\n",
"\n",
" def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None) -> str:\n",
" \"\"\"Use the tool.\"\"\"\n",
" return search.run(query)\n",
" \n",
" async def _arun(self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str:\n",
" \"\"\"Use the tool asynchronously.\"\"\"\n",
" raise NotImplementedError(\"custom_search does not support async\")\n",
" \n",
"class CustomCalculatorTool(BaseTool):\n",
" name = \"Calculator\"\n",
" description = \"useful for when you need to answer questions about math\"\n",
" args_schema: Type[BaseModel] = CalculatorInput\n",
"\n",
" def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None) -> str:\n",
" \"\"\"Use the tool.\"\"\"\n",
" return llm_math_chain.run(query)\n",
" \n",
" async def _arun(self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str:\n",
" \"\"\"Use the tool asynchronously.\"\"\"\n",
" raise NotImplementedError(\"Calculator does not support async\")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "c58a7c40",
"metadata": {},
"outputs": [],
"source": [
"class CustomSearchTool(BaseTool):\n",
" name = \"Search\"\n",
" description = \"useful for when you need to answer questions about current events\"\n",
"\n",
" def _run(self, query: str) -> str:\n",
" \"\"\"Use the tool.\"\"\"\n",
" return search.run(query)\n",
" \n",
" async def _arun(self, query: str) -> str:\n",
" \"\"\"Use the tool asynchronously.\"\"\"\n",
" raise NotImplementedError(\"BingSearchRun does not support async\")\n",
" \n",
"class CustomCalculatorTool(BaseTool):\n",
" name = \"Calculator\"\n",
" description = \"useful for when you need to answer questions about math\"\n",
"\n",
" def _run(self, query: str) -> str:\n",
" \"\"\"Use the tool.\"\"\"\n",
" return llm_math_chain.run(query)\n",
" \n",
" async def _arun(self, query: str) -> str:\n",
" \"\"\"Use the tool asynchronously.\"\"\"\n",
" raise NotImplementedError(\"BingSearchRun does not support async\")"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "3318a46f",
"metadata": {},
"outputs": [],
"source": [
"tools = [CustomSearchTool(), CustomCalculatorTool()]"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "ee2d0f3a",
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"tools = [CustomSearchTool(), CustomCalculatorTool()]\n",
"agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"execution_count": 9,
"id": "6a2cebbf",
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
@@ -234,29 +297,30 @@
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.\n",
"Action: Search\n",
"\u001b[32;1m\u001b[1;3mI need to use custom_search to find out who Leo DiCaprio's girlfriend is, and then use the Calculator to raise her age to the 0.43 power.\n",
"Action: custom_search\n",
"Action Input: \"Leo DiCaprio girlfriend\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mCamila Morrone\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now need to calculate her age raised to the 0.43 power\n",
"Observation: \u001b[36;1m\u001b[1;3mAfter rumours of a romance with Gigi Hadid, the Oscar winner has seemingly moved on. First being linked to the television personality in September 2022, it appears as if his \"age bracket\" has moved up. This follows his rumoured relationship with mere 19-year-old Eden Polani.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI need to find out the current age of Eden Polani.\n",
"Action: custom_search\n",
"Action Input: \"Eden Polani age\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m19 years old\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mNow I can use the Calculator to raise her age to the 0.43 power.\n",
"Action: Calculator\n",
"Action Input: 22^0.43\u001b[0m\n",
"Action Input: 19 ^ 0.43\u001b[0m\n",
"\n",
"\u001b[1m> Entering new LLMMathChain chain...\u001b[0m\n",
"22^0.43\u001b[32;1m\u001b[1;3m\n",
"```python\n",
"import math\n",
"print(math.pow(22, 0.43))\n",
"19 ^ 0.43\u001b[32;1m\u001b[1;3m```text\n",
"19 ** 0.43\n",
"```\n",
"...numexpr.evaluate(\"19 ** 0.43\")...\n",
"\u001b[0m\n",
"Answer: \u001b[33;1m\u001b[1;3m3.777824273683966\n",
"\u001b[0m\n",
"Answer: \u001b[33;1m\u001b[1;3m3.547023357958959\u001b[0m\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\n",
"Observation: \u001b[33;1m\u001b[1;3mAnswer: 3.777824273683966\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Camila Morrone's age raised to the 0.43 power is 3.777824273683966.\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mAnswer: 3.547023357958959\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI now know the final answer.\n",
"Final Answer: 3.547023357958959\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -264,10 +328,10 @@
{
"data": {
"text/plain": [
"\"Camila Morrone's age raised to the 0.43 power is 3.777824273683966.\""
"'3.547023357958959'"
]
},
"execution_count": 11,
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
@@ -288,37 +352,20 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 10,
"id": "8f15307d",
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain.agents import tool\n",
"from langchain.tools import tool\n",
"\n",
"@tool\n",
"def search_api(query: str) -> str:\n",
" \"\"\"Searches the API for the query.\"\"\"\n",
" return \"Results\""
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "0a23b91b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Tool(name='search_api', description='search_api(query: str) -> str - Searches the API for the query.', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1184e0cd0>, func=<function search_api at 0x1635f8700>, coroutine=None)"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
" return f\"Results for query {query}\"\n",
"\n",
"search_api"
]
},
@@ -332,9 +379,11 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 12,
"id": "28cdf04d",
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"@tool(\"search\", return_direct=True)\n",
@@ -345,17 +394,17 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 13,
"id": "1085a4bd",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Tool(name='search', description='search(query: str) -> str - Searches the API for the query.', return_direct=True, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1184e0cd0>, func=<function search_api at 0x1635f8670>, coroutine=None)"
"Tool(name='search', description='search(query: str) -> str - Searches the API for the query.', args_schema=<class 'pydantic.main.SearchApi'>, return_direct=True, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x12748c4c0>, func=<function search_api at 0x16bd66310>, coroutine=None)"
]
},
"execution_count": 7,
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
@@ -365,18 +414,194 @@
]
},
{
"cell_type": "markdown",
"id": "de34a6a3",
"metadata": {},
"source": [
"You can also provide `args_schema` to provide more information about the argument"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "f3a5c106",
"metadata": {},
"outputs": [],
"source": [
"class SearchInput(BaseModel):\n",
" query: str = Field(description=\"should be a search query\")\n",
" \n",
"@tool(\"search\", return_direct=True, args_schema=SearchInput)\n",
"def search_api(query: str) -> str:\n",
" \"\"\"Searches the API for the query.\"\"\"\n",
" return \"Results\""
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "7914ba6b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Tool(name='search', description='search(query: str) -> str - Searches the API for the query.', args_schema=<class '__main__.SearchInput'>, return_direct=True, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x12748c4c0>, func=<function search_api at 0x16bcf0ee0>, coroutine=None)"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"search_api"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "61d2e80b",
"metadata": {},
"source": [
"## Custom Structured Tools\n",
"\n",
"If your functions require more structured arguments, you can use the `StructuredTool` class directly, or still subclass the `BaseTool` class."
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "5be41722",
"metadata": {},
"source": [
"### StructuredTool dataclass\n",
"\n",
"To dynamically generate a structured tool from a given function, the fastest way to get started is with `StructuredTool.from_function()`."
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "3c070216",
"metadata": {},
"outputs": [],
"source": [
"import requests\n",
"from langchain.tools import StructuredTool\n",
"\n",
"def post_message(url: str, body: dict, parameters: Optional[dict] = None) -> str:\n",
" \"\"\"Sends a POST request to the given url with the given body and parameters.\"\"\"\n",
" result = requests.post(url, json=body, params=parameters)\n",
" return f\"Status: {result.status_code} - {result.text}\"\n",
"\n",
"tool = StructuredTool.from_function(post_message)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "fb0a38eb",
"metadata": {},
"source": [
"## Subclassing the BaseTool\n",
"\n",
"The BaseTool automatically infers the schema from the _run method's signature."
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "7505c9c5",
"metadata": {},
"outputs": [],
"source": [
"from typing import Optional, Type\n",
"\n",
"from langchain.callbacks.manager import AsyncCallbackManagerForToolRun, CallbackManagerForToolRun\n",
" \n",
"class CustomSearchTool(BaseTool):\n",
" name = \"custom_search\"\n",
" description = \"useful for when you need to answer questions about current events\"\n",
"\n",
" def _run(self, query: str, engine: str = \"google\", gl: str = \"us\", hl: str = \"en\", run_manager: Optional[CallbackManagerForToolRun] = None) -> str:\n",
" \"\"\"Use the tool.\"\"\"\n",
" search_wrapper = SerpAPIWrapper(params={\"engine\": engine, \"gl\": gl, \"hl\": hl})\n",
" return search_wrapper.run(query)\n",
" \n",
" async def _arun(self, query: str, engine: str = \"google\", gl: str = \"us\", hl: str = \"en\", run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str:\n",
" \"\"\"Use the tool asynchronously.\"\"\"\n",
" raise NotImplementedError(\"custom_search does not support async\")\n",
"\n",
"\n",
"\n",
"# You can provide a custom args schema to add descriptions or custom validation\n",
"\n",
"class SearchSchema(BaseModel):\n",
" query: str = Field(description=\"should be a search query\")\n",
" engine: str = Field(description=\"should be a search engine\")\n",
" gl: str = Field(description=\"should be a country code\")\n",
" hl: str = Field(description=\"should be a language code\")\n",
"\n",
"class CustomSearchTool(BaseTool):\n",
" name = \"custom_search\"\n",
" description = \"useful for when you need to answer questions about current events\"\n",
" args_schema: Type[SearchSchema] = SearchSchema\n",
"\n",
" def _run(self, query: str, engine: str = \"google\", gl: str = \"us\", hl: str = \"en\", run_manager: Optional[CallbackManagerForToolRun] = None) -> str:\n",
" \"\"\"Use the tool.\"\"\"\n",
" search_wrapper = SerpAPIWrapper(params={\"engine\": engine, \"gl\": gl, \"hl\": hl})\n",
" return search_wrapper.run(query)\n",
" \n",
" async def _arun(self, query: str, engine: str = \"google\", gl: str = \"us\", hl: str = \"en\", run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str:\n",
" \"\"\"Use the tool asynchronously.\"\"\"\n",
" raise NotImplementedError(\"custom_search does not support async\")\n",
" \n",
" "
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "7d68b0ac",
"metadata": {},
"source": [
"## Using the decorator\n",
"\n",
"The `tool` decorator creates a structured tool automatically if the signature has multiple arguments."
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "38d11416",
"metadata": {},
"outputs": [],
"source": [
"import requests\n",
"from langchain.tools import tool\n",
"\n",
"@tool\n",
"def post_message(url: str, body: dict, parameters: Optional[dict] = None) -> str:\n",
" \"\"\"Sends a POST request to the given url with the given body and parameters.\"\"\"\n",
" result = requests.post(url, json=body, params=parameters)\n",
" return f\"Status: {result.status_code} - {result.text}\""
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "1d0430d6",
"metadata": {},
"source": [
"## Modify existing tools\n",
"\n",
"Now, we show how to load existing tools and just modify them. In the example below, we do something really simple and change the Search tool to have the name `Google Search`."
"Now, we show how to load existing tools and modify them directly. In the example below, we do something really simple and change the Search tool to have the name `Google Search`."
]
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 13,
"id": "79213f40",
"metadata": {},
"outputs": [],
@@ -386,7 +611,7 @@
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 14,
"id": "e1067dcb",
"metadata": {},
"outputs": [],
@@ -396,7 +621,7 @@
},
{
"cell_type": "code",
"execution_count": 10,
"execution_count": 15,
"id": "6c66ffe8",
"metadata": {},
"outputs": [],
@@ -406,7 +631,7 @@
},
{
"cell_type": "code",
"execution_count": 11,
"execution_count": 16,
"id": "f45b5bc3",
"metadata": {},
"outputs": [],
@@ -416,7 +641,7 @@
},
{
"cell_type": "code",
"execution_count": 12,
"execution_count": 17,
"id": "565e2b9b",
"metadata": {},
"outputs": [
@@ -427,21 +652,20 @@
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.\n",
"\u001b[32;1m\u001b[1;3mI need to find out Leo DiCaprio's girlfriend's name and her age.\n",
"Action: Google Search\n",
"Action Input: \"Leo DiCaprio girlfriend\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mCamila Morrone\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to find out Camila Morrone's age\n",
"Observation: \u001b[36;1m\u001b[1;3mAfter rumours of a romance with Gigi Hadid, the Oscar winner has seemingly moved on. First being linked to the television personality in September 2022, it appears as if his \"age bracket\" has moved up. This follows his rumoured relationship with mere 19-year-old Eden Polani.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI still need to find out his current girlfriend's name and her age.\n",
"Action: Google Search\n",
"Action Input: \"Camila Morrone age\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m25 years\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I need to calculate 25 raised to the 0.43 power\n",
"Action Input: \"Leo DiCaprio current girlfriend age\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mLeonardo DiCaprio has been linked with 19-year-old model Eden Polani, continuing the rumour that he doesn't date any women over the age of ...\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI need to find out the age of Eden Polani.\n",
"Action: Calculator\n",
"Action Input: 25^0.43\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mAnswer: 3.991298452658078\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078.\u001b[0m\n",
"Action Input: 19^(0.43)\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mAnswer: 3.547023357958959\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI now know the final answer.\n",
"Final Answer: The age of Leo DiCaprio's girlfriend raised to the 0.43 power is approximately 3.55.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -449,10 +673,10 @@
{
"data": {
"text/plain": [
"\"Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078.\""
"\"The age of Leo DiCaprio's girlfriend raised to the 0.43 power is approximately 3.55.\""
]
},
"execution_count": 12,
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
@@ -478,7 +702,7 @@
},
{
"cell_type": "code",
"execution_count": 13,
"execution_count": 18,
"id": "3450512e",
"metadata": {},
"outputs": [],
@@ -507,7 +731,7 @@
},
{
"cell_type": "code",
"execution_count": 14,
"execution_count": 20,
"id": "4b9a7849",
"metadata": {},
"outputs": [
@@ -520,9 +744,7 @@
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I should use a music search engine to find the answer\n",
"Action: Music Search\n",
"Action Input: most famous song of christmas\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3m'All I Want For Christmas Is You' by Mariah Carey.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Action Input: most famous song of christmas\u001b[0m\u001b[33;1m\u001b[1;3m'All I Want For Christmas Is You' by Mariah Carey.\u001b[0m\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: 'All I Want For Christmas Is You' by Mariah Carey.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
@@ -534,7 +756,7 @@
"\"'All I Want For Christmas Is You' by Mariah Carey.\""
]
},
"execution_count": 14,
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
@@ -554,7 +776,7 @@
},
{
"cell_type": "code",
"execution_count": 15,
"execution_count": 21,
"id": "3bb6185f",
"metadata": {},
"outputs": [],
@@ -572,7 +794,7 @@
},
{
"cell_type": "code",
"execution_count": 16,
"execution_count": 22,
"id": "113ddb84",
"metadata": {},
"outputs": [],
@@ -583,9 +805,11 @@
},
{
"cell_type": "code",
"execution_count": 17,
"execution_count": 23,
"id": "582439a6",
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
@@ -596,9 +820,7 @@
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m I need to calculate this\n",
"Action: Calculator\n",
"Action Input: 2**.12\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 1.2599210498948732\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m\u001b[0m\n",
"Action Input: 2**.12\u001b[0m\u001b[36;1m\u001b[1;3mAnswer: 1.086734862526058\u001b[0m\u001b[32;1m\u001b[1;3m\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -606,10 +828,10 @@
{
"data": {
"text/plain": [
"'Answer: 1.2599210498948732'"
"'Answer: 1.086734862526058'"
]
},
"execution_count": 17,
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
@@ -617,14 +839,6 @@
"source": [
"agent.run(\"whats 2**.12\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "537bc628",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
@@ -643,7 +857,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.1"
"version": "3.11.2"
},
"vscode": {
"interpreter": {

View File

@@ -1,7 +1,6 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
@@ -20,7 +19,15 @@
]
},
{
"attachments": {},
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#!pip install apify-client"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
@@ -39,7 +46,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
@@ -60,7 +66,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
@@ -85,7 +90,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
@@ -102,7 +106,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
@@ -156,9 +159,9 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
"version": "3.10.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
"nbformat_minor": 4
}

View File

@@ -0,0 +1,259 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "245a954a",
"metadata": {},
"source": [
"# ArXiv API Tool\n",
"\n",
"This notebook goes over how to use the `arxiv` component. \n",
"\n",
"First, you need to install `arxiv` python package."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d5a7209e",
"metadata": {
"tags": [],
"vscode": {
"languageId": "shellscript"
}
},
"outputs": [],
"source": [
"!pip install arxiv"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "ce1a4827-ce89-4f31-a041-3246743e513a",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain.chat_models import ChatOpenAI\n",
"from langchain.agents import load_tools, initialize_agent, AgentType\n",
"\n",
"llm = ChatOpenAI(temperature=0.0)\n",
"tools = load_tools(\n",
" [\"arxiv\"], \n",
")\n",
"\n",
"agent_chain = initialize_agent(\n",
" tools,\n",
" llm,\n",
" agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n",
" verbose=True,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "ad7dd945-5ae3-49e5-b667-6d86b15050b6",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mI need to use Arxiv to search for the paper.\n",
"Action: Arxiv\n",
"Action Input: \"1605.08386\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mPublished: 2016-05-26\n",
"Title: Heat-bath random walks with Markov bases\n",
"Authors: Caprice Stanley, Tobias Windisch\n",
"Summary: Graphs on lattice points are studied whose edges come from a finite set of\n",
"allowed moves of arbitrary length. We show that the diameter of these graphs on\n",
"fibers of a fixed integer matrix can be bounded from above by a constant. We\n",
"then study the mixing behaviour of heat-bath random walks on these graphs. We\n",
"also state explicit conditions on the set of moves so that the heat-bath random\n",
"walk, a generalization of the Glauber dynamics, is an expander in fixed\n",
"dimension.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mThe paper is about heat-bath random walks with Markov bases on graphs of lattice points.\n",
"Final Answer: The paper 1605.08386 is about heat-bath random walks with Markov bases on graphs of lattice points.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"'The paper 1605.08386 is about heat-bath random walks with Markov bases on graphs of lattice points.'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_chain.run(\n",
" \"What's the paper 1605.08386 about?\",\n",
")"
]
},
{
"cell_type": "markdown",
"id": "b4183343-d69a-4be0-9b2c-cc98464a6825",
"metadata": {},
"source": [
"## The ArXiv API Wrapper\n",
"\n",
"The tool wraps the API Wrapper. Below, we can explore some of the features it provides."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "8d32b39a",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain.utilities import ArxivAPIWrapper"
]
},
{
"cell_type": "markdown",
"id": "c89c110c-96ac-4fe1-ba3e-6056543d1a59",
"metadata": {},
"source": [
"Run a query to get information about some `scientific article`/articles. The query text is limited to 300 characters.\n",
"\n",
"It returns these article fields:\n",
"- Publishing date\n",
"- Title\n",
"- Authors\n",
"- Summary\n",
"\n",
"Next query returns information about one article with arxiv Id equal \"1605.08386\". "
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "34bb5968",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"'Published: 2016-05-26\\nTitle: Heat-bath random walks with Markov bases\\nAuthors: Caprice Stanley, Tobias Windisch\\nSummary: Graphs on lattice points are studied whose edges come from a finite set of\\nallowed moves of arbitrary length. We show that the diameter of these graphs on\\nfibers of a fixed integer matrix can be bounded from above by a constant. We\\nthen study the mixing behaviour of heat-bath random walks on these graphs. We\\nalso state explicit conditions on the set of moves so that the heat-bath random\\nwalk, a generalization of the Glauber dynamics, is an expander in fixed\\ndimension.'"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"\n",
"arxiv = ArxivAPIWrapper()\n",
"docs = arxiv.run(\"1605.08386\")\n",
"docs"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "840f70c9-8f80-4680-bb38-46198e931bcf",
"metadata": {},
"source": [
"Now, we want to get information about one author, `Caprice Stanley`.\n",
"\n",
"This query returns information about three articles. By default, the query returns information only about three top articles."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "b0867fda-e119-4b19-9ec6-e354fa821db3",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"'Published: 2017-10-10\\nTitle: On Mixing Behavior of a Family of Random Walks Determined by a Linear Recurrence\\nAuthors: Caprice Stanley, Seth Sullivant\\nSummary: We study random walks on the integers mod $G_n$ that are determined by an\\ninteger sequence $\\\\{ G_n \\\\}_{n \\\\geq 1}$ generated by a linear recurrence\\nrelation. Fourier analysis provides explicit formulas to compute the\\neigenvalues of the transition matrices and we use this to bound the mixing time\\nof the random walks.\\n\\nPublished: 2016-05-26\\nTitle: Heat-bath random walks with Markov bases\\nAuthors: Caprice Stanley, Tobias Windisch\\nSummary: Graphs on lattice points are studied whose edges come from a finite set of\\nallowed moves of arbitrary length. We show that the diameter of these graphs on\\nfibers of a fixed integer matrix can be bounded from above by a constant. We\\nthen study the mixing behaviour of heat-bath random walks on these graphs. We\\nalso state explicit conditions on the set of moves so that the heat-bath random\\nwalk, a generalization of the Glauber dynamics, is an expander in fixed\\ndimension.\\n\\nPublished: 2003-03-18\\nTitle: Calculation of fluxes of charged particles and neutrinos from atmospheric showers\\nAuthors: V. Plyaskin\\nSummary: The results on the fluxes of charged particles and neutrinos from a\\n3-dimensional (3D) simulation of atmospheric showers are presented. An\\nagreement of calculated fluxes with data on charged particles from the AMS and\\nCAPRICE detectors is demonstrated. Predictions on neutrino fluxes at different\\nexperimental sites are compared with results from other calculations.'"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"docs = arxiv.run(\"Caprice Stanley\")\n",
"docs"
]
},
{
"cell_type": "markdown",
"id": "2d9b6292-a47d-4f99-9827-8e9f244bf887",
"metadata": {},
"source": [
"Now, we are trying to find information about non-existing article. In this case, the response is \"No good Arxiv Result was found\""
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "3580aeeb-086f-45ba-bcdc-b46f5134b3dd",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"'No good Arxiv Result was found'"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"docs = arxiv.run(\"1605.08386WWW\")\n",
"docs"
]
}
],
"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.4"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -0,0 +1,119 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## AWS Lambda API"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook goes over how to use the AWS Lambda Tool component.\n",
"\n",
"AWS Lambda is a serverless computing service provided by Amazon Web Services (AWS), designed to allow developers to build and run applications and services without the need for provisioning or managing servers. This serverless architecture enables you to focus on writing and deploying code, while AWS automatically takes care of scaling, patching, and managing the infrastructure required to run your applications.\n",
"\n",
"By including a `awslambda` in the list of tools provided to an Agent, you can grant your Agent the ability to invoke code running in your AWS Cloud for whatever purposes you need.\n",
"\n",
"When an Agent uses the awslambda tool, it will provide an argument of type string which will in turn be passed into the Lambda function via the event parameter.\n",
"\n",
"First, you need to install `boto3` python package."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"vscode": {
"languageId": "shellscript"
}
},
"outputs": [],
"source": [
"!pip install boto3 > /dev/null"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"In order for an agent to use the tool, you must provide it with the name and description that match the functionality of you lambda function's logic. \n",
"\n",
"You must also provide the name of your function. "
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that because this tool is effectively just a wrapper around the boto3 library, you will need to run `aws configure` in order to make use of the tool. For more detail, see [here](https://docs.aws.amazon.com/cli/index.html)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"vscode": {
"languageId": "shellscript"
}
},
"outputs": [],
"source": [
"from langchain import OpenAI\n",
"from langchain.agents import load_tools, AgentType\n",
"\n",
"llm = OpenAI(temperature=0)\n",
"\n",
"tools = load_tools(\n",
" [\"awslambda\"],\n",
" awslambda_tool_name=\"email-sender\",\n",
" awslambda_tool_description=\"sends an email with the specified content to test@testing123.com\",\n",
" function_name=\"testFunction1\"\n",
")\n",
"\n",
"agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n",
"\n",
"agent.run(\"Send an email to test@testing123.com saying hello world.\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"vscode": {
"languageId": "shellscript"
}
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.2"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -5,57 +5,158 @@
"id": "8f210ec3",
"metadata": {},
"source": [
"# Bash\n",
"It can often be useful to have an LLM generate bash commands, and then run them. A common use case for this is letting the LLM interact with your local file system. We provide an easy util to execute bash commands."
"# Shell Tool\n",
"\n",
"Giving agents access to the shell is powerful (though risky outside a sandboxed environment).\n",
"\n",
"The LLM can use it to execute any shell commands. A common use case for this is letting the LLM interact with your local file system."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "f7b3767b",
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain.utilities import BashProcess"
"from langchain.tools import ShellTool\n",
"\n",
"shell_tool = ShellTool()"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "cf1c92f0",
"metadata": {},
"outputs": [],
"source": [
"bash = BashProcess()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "2fa952fc",
"metadata": {},
"id": "c92ac832-556b-4f66-baa4-b78f965dfba0",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"bash.ipynb\n",
"google_search.ipynb\n",
"python.ipynb\n",
"requests.ipynb\n",
"serpapi.ipynb\n",
"Hello World!\n",
"\n",
"real\t0m0.000s\n",
"user\t0m0.000s\n",
"sys\t0m0.000s\n",
"\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/wfh/code/lc/lckg/langchain/tools/shell/tool.py:34: UserWarning: The shell tool has no safeguards by default. Use at your own risk.\n",
" warnings.warn(\n"
]
}
],
"source": [
"print(bash.run(\"ls\"))"
"print(shell_tool.run({\"commands\": [\"echo 'Hello World!'\", \"time\"]}))"
]
},
{
"cell_type": "markdown",
"id": "2fa952fc",
"metadata": {},
"source": [
"### Use with Agents\n",
"\n",
"As with all tools, these can be given to an agent to accomplish more complex tasks. Let's have the agent fetch some links from a web page."
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "851fee9f",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mQuestion: What is the task?\n",
"Thought: We need to download the langchain.com webpage and extract all the URLs from it. Then we need to sort the URLs and return them.\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"shell\",\n",
" \"action_input\": {\n",
" \"commands\": [\n",
" \"curl -s https://langchain.com | grep -o 'http[s]*://[^\\\" ]*' | sort\"\n",
" ]\n",
" }\n",
"}\n",
"```\n",
"\u001b[0m"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/wfh/code/lc/lckg/langchain/tools/shell/tool.py:34: UserWarning: The shell tool has no safeguards by default. Use at your own risk.\n",
" warnings.warn(\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Observation: \u001b[36;1m\u001b[1;3mhttps://blog.langchain.dev/\n",
"https://discord.gg/6adMQxSpJS\n",
"https://docs.langchain.com/docs/\n",
"https://github.com/hwchase17/chat-langchain\n",
"https://github.com/hwchase17/langchain\n",
"https://github.com/hwchase17/langchainjs\n",
"https://github.com/sullivan-sean/chat-langchainjs\n",
"https://js.langchain.com/docs/\n",
"https://python.langchain.com/en/latest/\n",
"https://twitter.com/langchainai\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mThe URLs have been successfully extracted and sorted. We can return the list of URLs as the final answer.\n",
"Final Answer: [\"https://blog.langchain.dev/\", \"https://discord.gg/6adMQxSpJS\", \"https://docs.langchain.com/docs/\", \"https://github.com/hwchase17/chat-langchain\", \"https://github.com/hwchase17/langchain\", \"https://github.com/hwchase17/langchainjs\", \"https://github.com/sullivan-sean/chat-langchainjs\", \"https://js.langchain.com/docs/\", \"https://python.langchain.com/en/latest/\", \"https://twitter.com/langchainai\"]\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"'[\"https://blog.langchain.dev/\", \"https://discord.gg/6adMQxSpJS\", \"https://docs.langchain.com/docs/\", \"https://github.com/hwchase17/chat-langchain\", \"https://github.com/hwchase17/langchain\", \"https://github.com/hwchase17/langchainjs\", \"https://github.com/sullivan-sean/chat-langchainjs\", \"https://js.langchain.com/docs/\", \"https://python.langchain.com/en/latest/\", \"https://twitter.com/langchainai\"]'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from langchain.chat_models import ChatOpenAI\n",
"from langchain.agents import initialize_agent\n",
"from langchain.agents import AgentType\n",
"\n",
"llm = ChatOpenAI(temperature=0)\n",
"\n",
"shell_tool.description = shell_tool.description + f\"args {shell_tool.args}\".replace(\"{\", \"{{\").replace(\"}\", \"}}\")\n",
"self_ask_with_search = initialize_agent([shell_tool], llm, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n",
"self_ask_with_search.run(\"Download the langchain.com webpage and grep for all urls. Return only a sorted list of them. Be sure to use double quotes.\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "851fee9f",
"id": "8d0ea3ac-0890-4e39-9cec-74bd80b4b8b8",
"metadata": {},
"outputs": [],
"source": []
@@ -77,7 +178,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.9"
"version": "3.8.16"
}
},
"nbformat": 4,

View File

@@ -80,11 +80,11 @@
}
],
"source": [
"llm = ChatOpenAI(temperature=0,)\n",
"tools = load_tools([\"requests\"] )\n",
"llm = ChatOpenAI(temperature=0)\n",
"tools = load_tools([\"requests_all\"] )\n",
"tools += [tool]\n",
"\n",
"agent_chain = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION verbose=True)\n",
"agent_chain = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n",
"agent_chain.run(\"what t shirts are available in klarna?\")"
]
},

View File

@@ -0,0 +1,91 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "245a954a",
"metadata": {},
"source": [
"# DuckDuckGo Search\n",
"\n",
"This notebook goes over how to use the duck-duck-go search component."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "21e46d4d",
"metadata": {},
"outputs": [],
"source": [
"# !pip install duckduckgo-search"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "ac4910f8",
"metadata": {},
"outputs": [],
"source": [
"from langchain.tools import DuckDuckGoSearchRun"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "84b8f773",
"metadata": {},
"outputs": [],
"source": [
"search = DuckDuckGoSearchRun()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "068991a6",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Barack Obama, in full Barack Hussein Obama II, (born August 4, 1961, Honolulu, Hawaii, U.S.), 44th president of the United States (2009-17) and the first African American to hold the office. Before winning the presidency, Obama represented Illinois in the U.S. Senate (2005-08). Barack Hussein Obama II (/ b ə ˈ r ɑː k h uː ˈ s eɪ n oʊ ˈ b ɑː m ə / bə-RAHK hoo-SAYN oh-BAH-mə; born August 4, 1961) is an American former politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, he was the first African-American president of the United States. Obama previously served as a U.S. senator representing ... Barack Obama was the first African American president of the United States (2009-17). He oversaw the recovery of the U.S. economy (from the Great Recession of 2008-09) and the enactment of landmark health care reform (the Patient Protection and Affordable Care Act ). In 2009 he was awarded the Nobel Peace Prize. His birth certificate lists his first name as Barack: That\\'s how Obama has spelled his name throughout his life. His name derives from a Hebrew name which means \"lightning.\". The Hebrew word has been transliterated into English in various spellings, including Barak, Buraq, Burack, and Barack. Most common names of U.S. presidents 1789-2021. Published by. Aaron O\\'Neill , Jun 21, 2022. The most common first name for a U.S. president is James, followed by John and then William. Six U.S ...'"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"search.run(\"Obama's first name?\")"
]
}
],
"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.1"
},
"vscode": {
"interpreter": {
"hash": "a0a0263b650d907a3bfe41c0f8d6a63a071b884df3cfdc1579f00cdc1aed6b03"
}
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -0,0 +1,190 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# File System Tools\n",
"\n",
"LangChain provides tools for interacting with a local file system out of the box. This notebook walks through some of them.\n",
"\n",
"Note: these tools are not recommended for use outside a sandboxed environment! "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First, we'll import the tools."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain.tools.file_management import (\n",
" ReadFileTool,\n",
" CopyFileTool,\n",
" DeleteFileTool,\n",
" MoveFileTool,\n",
" WriteFileTool,\n",
" ListDirectoryTool,\n",
")\n",
"from langchain.agents.agent_toolkits import FileManagementToolkit\n",
"from tempfile import TemporaryDirectory\n",
"\n",
"# We'll make a temporary directory to avoid clutter\n",
"working_directory = TemporaryDirectory()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The FileManagementToolkit\n",
"\n",
"If you want to provide all the file tooling to your agent, it's easy to do so with the toolkit. We'll pass the temporary directory in as a root directory as a workspace for the LLM.\n",
"\n",
"It's recommended to always pass in a root directory, since without one, it's easy for the LLM to pollute the working directory, and without one, there isn't any validation against\n",
"straightforward prompt injection."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"[CopyFileTool(name='copy_file', description='Create a copy of a file in a specified location', args_schema=<class 'langchain.tools.file_management.copy.FileCopyInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),\n",
" DeleteFileTool(name='file_delete', description='Delete a file', args_schema=<class 'langchain.tools.file_management.delete.FileDeleteInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),\n",
" FileSearchTool(name='file_search', description='Recursively search for files in a subdirectory that match the regex pattern', args_schema=<class 'langchain.tools.file_management.file_search.FileSearchInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),\n",
" MoveFileTool(name='move_file', description='Move or rename a file from one location to another', args_schema=<class 'langchain.tools.file_management.move.FileMoveInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),\n",
" ReadFileTool(name='read_file', description='Read file from disk', args_schema=<class 'langchain.tools.file_management.read.ReadFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),\n",
" WriteFileTool(name='write_file', description='Write file to disk', args_schema=<class 'langchain.tools.file_management.write.WriteFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),\n",
" ListDirectoryTool(name='list_directory', description='List files and directories in a specified folder', args_schema=<class 'langchain.tools.file_management.list_dir.DirectoryListingInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug')]"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"toolkit = FileManagementToolkit(root_dir=str(working_directory.name)) # If you don't provide a root_dir, operations will default to the current working directory\n",
"toolkit.get_tools()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Selecting File System Tools\n",
"\n",
"If you only want to select certain tools, you can pass them in as arguments when initializing the toolkit, or you can individually initialize the desired tools."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"[ReadFileTool(name='read_file', description='Read file from disk', args_schema=<class 'langchain.tools.file_management.read.ReadFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),\n",
" WriteFileTool(name='write_file', description='Write file to disk', args_schema=<class 'langchain.tools.file_management.write.WriteFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),\n",
" ListDirectoryTool(name='list_directory', description='List files and directories in a specified folder', args_schema=<class 'langchain.tools.file_management.list_dir.DirectoryListingInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug')]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tools = FileManagementToolkit(root_dir=str(working_directory.name), selected_tools=[\"read_file\", \"write_file\", \"list_directory\"]).get_tools()\n",
"tools"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'File written successfully to example.txt.'"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"read_tool, write_tool, list_tool = tools\n",
"write_tool.run({\"file_path\": \"example.txt\", \"text\": \"Hello World!\"})"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'example.txt'"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# List files in the working directory\n",
"list_tool.run({})"
]
},
{
"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.11.2"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

View File

@@ -0,0 +1,105 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "487607cd",
"metadata": {},
"source": [
"# Google Places\n",
"\n",
"This notebook goes through how to use Google Places API"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "8690845f",
"metadata": {},
"outputs": [],
"source": [
"#!pip install googlemaps"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "fae31ef4",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"os.environ[\"GPLACES_API_KEY\"] = \"\""
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "abb502b3",
"metadata": {},
"outputs": [],
"source": [
"from langchain.tools import GooglePlacesTool"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "a83a02ac",
"metadata": {},
"outputs": [],
"source": [
"places = GooglePlacesTool()"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "2b65a285",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"1. Delfina Restaurant\\nAddress: 3621 18th St, San Francisco, CA 94110, USA\\nPhone: (415) 552-4055\\nWebsite: https://www.delfinasf.com/\\n\\n\\n2. Piccolo Forno\\nAddress: 725 Columbus Ave, San Francisco, CA 94133, USA\\nPhone: (415) 757-0087\\nWebsite: https://piccolo-forno-sf.com/\\n\\n\\n3. L'Osteria del Forno\\nAddress: 519 Columbus Ave, San Francisco, CA 94133, USA\\nPhone: (415) 982-1124\\nWebsite: Unknown\\n\\n\\n4. Il Fornaio\\nAddress: 1265 Battery St, San Francisco, CA 94111, USA\\nPhone: (415) 986-0100\\nWebsite: https://www.ilfornaio.com/\\n\\n\""
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"places.run(\"al fornos\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "66d3da8a",
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -9,7 +9,7 @@
"\n",
"This notebook goes over how to use the google search component.\n",
"\n",
"First, you need to set up the proper API keys and environment variables. To set it up, follow the instructions found [here](https://stackoverflow.com/questions/37083058/programmatically-searching-google-in-python-using-custom-search).\n",
"First, you need to set up the proper API keys and environment variables. To set it up, create the GOOGLE_API_KEY in the Google Cloud credential console (https://console.cloud.google.com/apis/credentials) and a GOOGLE_CSE_ID using the Programmable Search Enginge (https://programmablesearchengine.google.com/controlpanel/create). Next, it is good to follow the instructions found [here](https://stackoverflow.com/questions/37083058/programmatically-searching-google-in-python-using-custom-search).\n",
"\n",
"Then we will need to set some environment variables."
]
@@ -33,7 +33,16 @@
"metadata": {},
"outputs": [],
"source": [
"from langchain.utilities import GoogleSearchAPIWrapper"
"from langchain.tools import Tool\n",
"from langchain.utilities import GoogleSearchAPIWrapper\n",
"\n",
"search = GoogleSearchAPIWrapper()\n",
"\n",
"tool = Tool(\n",
" name = \"Google Search\",\n",
" description=\"Search Google for recent results.\",\n",
" func=search.run\n",
")"
]
},
{
@@ -41,30 +50,20 @@
"execution_count": 3,
"id": "84b8f773",
"metadata": {},
"outputs": [],
"source": [
"search = GoogleSearchAPIWrapper()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "068991a6",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'1 Child\\'s First Name. 2. 6. 7d. Street Address. 71. (Type or print). BARACK. Sex. 3. This Birth. 4. If Twin or Triplet,. Was Child Born. Barack Hussein Obama II is an American retired politician who served as the 44th president of the United States from 2009 to 2017. His full name is Barack Hussein Obama II. Since the “II” is simply because he was named for his father, his last name is Obama. Feb 9, 2015 ... Michael Jordan misspelled Barack Obama\\'s first name on 50th-birthday gift ... Knowing Obama is a Chicagoan and huge basketball fan,\\xa0... Aug 18, 2017 ... It took him several seconds and multiple clues to remember former President Barack Obama\\'s first name. Miller knew that every answer had to end\\xa0... First Lady Michelle LaVaughn Robinson Obama is a lawyer, writer, and the wife of the 44th President, Barack Obama. She is the first African-American First\\xa0... Barack Obama, in full Barack Hussein Obama II, (born August 4, 1961, Honolulu, Hawaii, U.S.), 44th president of the United States (200917) and the first\\xa0... When Barack Obama was elected president in 2008, he became the first African American to hold ... The Middle East remained a key foreign policy challenge. Feb 27, 2020 ... President Barack Obama was born Barack Hussein Obama, II, as shown here on his birth certificate here . As reported by Reuters here , his\\xa0... Jan 16, 2007 ... 4, 1961, in Honolulu. His first name means \"one who is blessed\" in Swahili. While Obama\\'s father, Barack Hussein Obama Sr., was from Kenya, his\\xa0...'"
"\"STATE OF HAWAII. 1 Child's First Name. (Type or print). 2. Sex. BARACK. 3. This Birth. CERTIFICATE OF LIVE BIRTH. FILE. NUMBER 151 le. lb. Middle Name. Barack Hussein Obama II is an American former politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic\\xa0... When Barack Obama was elected president in 2008, he became the first African American to hold ... The Middle East remained a key foreign policy challenge. Jan 19, 2017 ... Jordan Barack Treasure, New York City, born in 2008 ... Jordan Barack Treasure made national news when he was the focus of a New York newspaper\\xa0... Portrait of George Washington, the 1st President of the United States ... Portrait of Barack Obama, the 44th President of the United States\\xa0... His full name is Barack Hussein Obama II. Since the “II” is simply because he was named for his father, his last name is Obama. Mar 22, 2008 ... Barry Obama decided that he didn't like his nickname. A few of his friends at Occidental College had already begun to call him Barack (his\\xa0... Aug 18, 2017 ... It took him several seconds and multiple clues to remember former President Barack Obama's first name. Miller knew that every answer had to\\xa0... Feb 9, 2015 ... Michael Jordan misspelled Barack Obama's first name on 50th-birthday gift ... Knowing Obama is a Chicagoan and huge basketball fan,\\xa0... 4 days ago ... Barack Obama, in full Barack Hussein Obama II, (born August 4, 1961, Honolulu, Hawaii, U.S.), 44th president of the United States (200917) and\\xa0...\""
]
},
"execution_count": 4,
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"search.run(\"Obama's first name?\")"
"tool.run(\"Obama's first name?\")"
]
},
{
@@ -78,17 +77,23 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 4,
"id": "5083fbdd",
"metadata": {},
"outputs": [],
"source": [
"search = GoogleSearchAPIWrapper(k=1)"
"search = GoogleSearchAPIWrapper(k=1)\n",
"\n",
"tool = Tool(\n",
" name = \"I'm Feeling Lucky\",\n",
" description=\"Search Google and return the first result.\",\n",
" func=search.run\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 5,
"id": "77aaa857",
"metadata": {},
"outputs": [
@@ -98,13 +103,13 @@
"'The official home of the Python Programming Language.'"
]
},
"execution_count": 6,
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"search.run(\"python\")"
"tool.run(\"python\")"
]
},
{
@@ -137,48 +142,30 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 6,
"id": "028f4cba",
"metadata": {},
"outputs": [],
"source": [
"search = GoogleSearchAPIWrapper()"
"search = GoogleSearchAPIWrapper()\n",
"\n",
"def top5_results(query):\n",
" return search.results(query, 5)\n",
"\n",
"tool = Tool(\n",
" name = \"Google Search Snippets\",\n",
" description=\"Search Google for recent results.\",\n",
" func=top5_results\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "4d8f734f",
"execution_count": null,
"id": "4d7f92e1",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'snippet': 'Discover the innovative world of Apple and shop everything iPhone, iPad, Apple Watch, Mac, and Apple TV, plus explore accessories, entertainment,\\xa0...',\n",
" 'title': 'Apple',\n",
" 'link': 'https://www.apple.com/'},\n",
" {'snippet': \"Jul 10, 2022 ... Whether or not you're up on your apple trivia, no doubt you know how delicious this popular fruit is, and how nutritious. Apples are rich in\\xa0...\",\n",
" 'title': '25 Types of Apples and What to Make With Them - Parade ...',\n",
" 'link': 'https://parade.com/1330308/bethlipton/types-of-apples/'},\n",
" {'snippet': 'An apple is an edible fruit produced by an apple tree (Malus domestica). Apple trees are cultivated worldwide and are the most widely grown species in the\\xa0...',\n",
" 'title': 'Apple - Wikipedia',\n",
" 'link': 'https://en.wikipedia.org/wiki/Apple'},\n",
" {'snippet': 'Apples are a popular fruit. They contain antioxidants, vitamins, dietary fiber, and a range of other nutrients. Due to their varied nutrient content,\\xa0...',\n",
" 'title': 'Apples: Benefits, nutrition, and tips',\n",
" 'link': 'https://www.medicalnewstoday.com/articles/267290'},\n",
" {'snippet': \"An apple is a crunchy, bright-colored fruit, one of the most popular in the United States. You've probably heard the age-old saying, “An apple a day keeps\\xa0...\",\n",
" 'title': 'Apples: Nutrition & Health Benefits',\n",
" 'link': 'https://www.webmd.com/food-recipes/benefits-apples'}]"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"search.results(\"apples\", 5)"
]
"outputs": [],
"source": []
}
],
"metadata": {
@@ -197,7 +184,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.9"
"version": "3.11.2"
},
"vscode": {
"interpreter": {

View File

@@ -12,21 +12,34 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 11,
"outputs": [],
"source": [
"import os\n",
"import pprint\n",
"os.environ[\"SERPER_API_KEY\"] = \"\""
],
"metadata": {
"collapsed": false
"collapsed": false,
"pycharm": {
"is_executing": true
},
"ExecuteTime": {
"end_time": "2023-05-04T00:56:29.336521Z",
"start_time": "2023-05-04T00:56:29.334173Z"
}
}
},
{
"cell_type": "code",
"execution_count": 2,
"id": "54bf5afd",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-04T00:54:07.676293Z",
"start_time": "2023-05-04T00:54:06.665742Z"
}
},
"outputs": [],
"source": [
"from langchain.utilities import GoogleSerperAPIWrapper"
@@ -36,7 +49,12 @@
"cell_type": "code",
"execution_count": 3,
"id": "31f8f382",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-04T00:54:08.324245Z",
"start_time": "2023-05-04T00:54:08.321577Z"
}
},
"outputs": [],
"source": [
"search = GoogleSerperAPIWrapper()"
@@ -46,7 +64,12 @@
"cell_type": "code",
"execution_count": 4,
"id": "25ce0225",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2023-05-04T00:54:11.399847Z",
"start_time": "2023-05-04T00:54:09.335597Z"
}
},
"outputs": [
{
"data": {
@@ -72,13 +95,17 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 5,
"outputs": [],
"source": [
"os.environ['OPENAI_API_KEY'] = \"\""
],
"metadata": {
"collapsed": false
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-05-04T00:54:14.311773Z",
"start_time": "2023-05-04T00:54:14.304389Z"
}
}
},
{
@@ -133,6 +160,693 @@
"metadata": {
"collapsed": false
}
},
{
"cell_type": "markdown",
"source": [
"## Obtaining results with metadata\n",
"If you would also like to obtain the results in a structured way including metadata. For this we will be using the `results` method of the wrapper."
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": 6,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'searchParameters': {'q': 'Apple Inc.',\n",
" 'gl': 'us',\n",
" 'hl': 'en',\n",
" 'num': 10,\n",
" 'type': 'search'},\n",
" 'knowledgeGraph': {'title': 'Apple',\n",
" 'type': 'Technology company',\n",
" 'website': 'http://www.apple.com/',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwGQRv5TjjkycpctY66mOg_e2-npacrmjAb6_jAWhzlzkFE3OTjxyzbA&s=0',\n",
" 'description': 'Apple Inc. is an American multinational '\n",
" 'technology company headquartered in '\n",
" 'Cupertino, California. Apple is the '\n",
" \"world's largest technology company by \"\n",
" 'revenue, with US$394.3 billion in 2022 '\n",
" 'revenue. As of March 2023, Apple is the '\n",
" \"world's biggest...\",\n",
" 'descriptionSource': 'Wikipedia',\n",
" 'descriptionLink': 'https://en.wikipedia.org/wiki/Apple_Inc.',\n",
" 'attributes': {'Customer service': '1 (800) 275-2273',\n",
" 'CEO': 'Tim Cook (Aug 24, 2011)',\n",
" 'Headquarters': 'Cupertino, CA',\n",
" 'Founded': 'April 1, 1976, Los Altos, CA',\n",
" 'Founders': 'Steve Jobs, Steve Wozniak, '\n",
" 'Ronald Wayne, and more',\n",
" 'Products': 'iPhone, iPad, Apple TV, and '\n",
" 'more'}},\n",
" 'organic': [{'title': 'Apple',\n",
" 'link': 'https://www.apple.com/',\n",
" 'snippet': 'Discover the innovative world of Apple and shop '\n",
" 'everything iPhone, iPad, Apple Watch, Mac, and Apple '\n",
" 'TV, plus explore accessories, entertainment, ...',\n",
" 'sitelinks': [{'title': 'Support',\n",
" 'link': 'https://support.apple.com/'},\n",
" {'title': 'iPhone',\n",
" 'link': 'https://www.apple.com/iphone/'},\n",
" {'title': 'Site Map',\n",
" 'link': 'https://www.apple.com/sitemap/'},\n",
" {'title': 'Business',\n",
" 'link': 'https://www.apple.com/business/'},\n",
" {'title': 'Mac',\n",
" 'link': 'https://www.apple.com/mac/'},\n",
" {'title': 'Watch',\n",
" 'link': 'https://www.apple.com/watch/'}],\n",
" 'position': 1},\n",
" {'title': 'Apple Inc. - Wikipedia',\n",
" 'link': 'https://en.wikipedia.org/wiki/Apple_Inc.',\n",
" 'snippet': 'Apple Inc. is an American multinational technology '\n",
" 'company headquartered in Cupertino, California. '\n",
" \"Apple is the world's largest technology company by \"\n",
" 'revenue, ...',\n",
" 'attributes': {'Products': 'AirPods; Apple Watch; iPad; iPhone; '\n",
" 'Mac; Full list',\n",
" 'Founders': 'Steve Jobs; Steve Wozniak; Ronald '\n",
" 'Wayne; Mike Markkula'},\n",
" 'sitelinks': [{'title': 'History',\n",
" 'link': 'https://en.wikipedia.org/wiki/History_of_Apple_Inc.'},\n",
" {'title': 'Timeline of Apple Inc. products',\n",
" 'link': 'https://en.wikipedia.org/wiki/Timeline_of_Apple_Inc._products'},\n",
" {'title': 'Litigation involving Apple Inc.',\n",
" 'link': 'https://en.wikipedia.org/wiki/Litigation_involving_Apple_Inc.'},\n",
" {'title': 'Apple Store',\n",
" 'link': 'https://en.wikipedia.org/wiki/Apple_Store'}],\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRvmB5fT1LjqpZx02UM7IJq0Buoqt0DZs_y0dqwxwSWyP4PIN9FaxuTea0&s',\n",
" 'position': 2},\n",
" {'title': 'Apple Inc. | History, Products, Headquarters, & Facts '\n",
" '| Britannica',\n",
" 'link': 'https://www.britannica.com/topic/Apple-Inc',\n",
" 'snippet': 'Apple Inc., formerly Apple Computer, Inc., American '\n",
" 'manufacturer of personal computers, smartphones, '\n",
" 'tablet computers, computer peripherals, and computer '\n",
" '...',\n",
" 'attributes': {'Related People': 'Steve Jobs Steve Wozniak Jony '\n",
" 'Ive Tim Cook Angela Ahrendts',\n",
" 'Date': '1976 - present'},\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS3liELlhrMz3Wpsox29U8jJ3L8qETR0hBWHXbFnwjwQc34zwZvFELst2E&s',\n",
" 'position': 3},\n",
" {'title': 'AAPL: Apple Inc Stock Price Quote - NASDAQ GS - '\n",
" 'Bloomberg.com',\n",
" 'link': 'https://www.bloomberg.com/quote/AAPL:US',\n",
" 'snippet': 'AAPL:USNASDAQ GS. Apple Inc. COMPANY INFO ; Open. '\n",
" '170.09 ; Prev Close. 169.59 ; Volume. 48,425,696 ; '\n",
" 'Market Cap. 2.667T ; Day Range. 167.54170.35.',\n",
" 'position': 4},\n",
" {'title': 'Apple Inc. (AAPL) Company Profile & Facts - Yahoo '\n",
" 'Finance',\n",
" 'link': 'https://finance.yahoo.com/quote/AAPL/profile/',\n",
" 'snippet': 'Apple Inc. designs, manufactures, and markets '\n",
" 'smartphones, personal computers, tablets, wearables, '\n",
" 'and accessories worldwide. The company offers '\n",
" 'iPhone, a line ...',\n",
" 'position': 5},\n",
" {'title': 'Apple Inc. (AAPL) Stock Price, News, Quote & History - '\n",
" 'Yahoo Finance',\n",
" 'link': 'https://finance.yahoo.com/quote/AAPL',\n",
" 'snippet': 'Find the latest Apple Inc. (AAPL) stock quote, '\n",
" 'history, news and other vital information to help '\n",
" 'you with your stock trading and investing.',\n",
" 'position': 6}],\n",
" 'peopleAlsoAsk': [{'question': 'What does Apple Inc do?',\n",
" 'snippet': 'Apple Inc. (Apple) designs, manufactures and '\n",
" 'markets smartphones, personal\\n'\n",
" 'computers, tablets, wearables and accessories '\n",
" 'and sells a range of related\\n'\n",
" 'services.',\n",
" 'title': 'AAPL.O - | Stock Price & Latest News - Reuters',\n",
" 'link': 'https://www.reuters.com/markets/companies/AAPL.O/'},\n",
" {'question': 'What is the full form of Apple Inc?',\n",
" 'snippet': '(formerly Apple Computer Inc.) is an American '\n",
" 'computer and consumer electronics\\n'\n",
" 'company famous for creating the iPhone, iPad '\n",
" 'and Macintosh computers.',\n",
" 'title': 'What is Apple? An products and history overview '\n",
" '- TechTarget',\n",
" 'link': 'https://www.techtarget.com/whatis/definition/Apple'},\n",
" {'question': 'What is Apple Inc iPhone?',\n",
" 'snippet': 'Apple Inc (Apple) designs, manufactures, and '\n",
" 'markets smartphones, tablets,\\n'\n",
" 'personal computers, and wearable devices. The '\n",
" 'company also offers software\\n'\n",
" 'applications and related services, '\n",
" 'accessories, and third-party digital content.\\n'\n",
" \"Apple's product portfolio includes iPhone, \"\n",
" 'iPad, Mac, iPod, Apple Watch, and\\n'\n",
" 'Apple TV.',\n",
" 'title': 'Apple Inc Company Profile - Apple Inc Overview - '\n",
" 'GlobalData',\n",
" 'link': 'https://www.globaldata.com/company-profile/apple-inc/'},\n",
" {'question': 'Who runs Apple Inc?',\n",
" 'snippet': 'Timothy Donald Cook (born November 1, 1960) is '\n",
" 'an American business executive\\n'\n",
" 'who has been the chief executive officer of '\n",
" 'Apple Inc. since 2011. Cook\\n'\n",
" \"previously served as the company's chief \"\n",
" 'operating officer under its co-founder\\n'\n",
" 'Steve Jobs. He is the first CEO of any Fortune '\n",
" '500 company who is openly gay.',\n",
" 'title': 'Tim Cook - Wikipedia',\n",
" 'link': 'https://en.wikipedia.org/wiki/Tim_Cook'}],\n",
" 'relatedSearches': [{'query': 'Who invented the iPhone'},\n",
" {'query': 'Apple iPhone'},\n",
" {'query': 'History of Apple company PDF'},\n",
" {'query': 'Apple company history'},\n",
" {'query': 'Apple company introduction'},\n",
" {'query': 'Apple India'},\n",
" {'query': 'What does Apple Inc own'},\n",
" {'query': 'Apple Inc After Steve'},\n",
" {'query': 'Apple Watch'},\n",
" {'query': 'Apple App Store'}]}\n"
]
}
],
"source": [
"search = GoogleSerperAPIWrapper()\n",
"results = search.results(\"Apple Inc.\")\n",
"pprint.pp(results)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"is_executing": true
},
"ExecuteTime": {
"end_time": "2023-05-04T00:54:22.863413Z",
"start_time": "2023-05-04T00:54:20.827395Z"
}
}
},
{
"cell_type": "markdown",
"source": [
"## Searching for Google Images\n",
"We can also query Google Images using this wrapper. For example:"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": 7,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'searchParameters': {'q': 'Lion',\n",
" 'gl': 'us',\n",
" 'hl': 'en',\n",
" 'num': 10,\n",
" 'type': 'images'},\n",
" 'images': [{'title': 'Lion - Wikipedia',\n",
" 'imageUrl': 'https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Lion_waiting_in_Namibia.jpg/1200px-Lion_waiting_in_Namibia.jpg',\n",
" 'imageWidth': 1200,\n",
" 'imageHeight': 900,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRye79ROKwjfb6017jr0iu8Bz2E1KKuHg-A4qINJaspyxkZrkw&amp;s',\n",
" 'thumbnailWidth': 259,\n",
" 'thumbnailHeight': 194,\n",
" 'source': 'Wikipedia',\n",
" 'domain': 'en.wikipedia.org',\n",
" 'link': 'https://en.wikipedia.org/wiki/Lion',\n",
" 'position': 1},\n",
" {'title': 'Lion | Characteristics, Habitat, & Facts | Britannica',\n",
" 'imageUrl': 'https://cdn.britannica.com/55/2155-050-604F5A4A/lion.jpg',\n",
" 'imageWidth': 754,\n",
" 'imageHeight': 752,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS3fnDub1GSojI0hJ-ZGS8Tv-hkNNloXh98DOwXZoZ_nUs3GWSd&amp;s',\n",
" 'thumbnailWidth': 225,\n",
" 'thumbnailHeight': 224,\n",
" 'source': 'Encyclopedia Britannica',\n",
" 'domain': 'www.britannica.com',\n",
" 'link': 'https://www.britannica.com/animal/lion',\n",
" 'position': 2},\n",
" {'title': 'African lion, facts and photos',\n",
" 'imageUrl': 'https://i.natgeofe.com/n/487a0d69-8202-406f-a6a0-939ed3704693/african-lion.JPG',\n",
" 'imageWidth': 3072,\n",
" 'imageHeight': 2043,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTPlTarrtDbyTiEm-VI_PML9VtOTVPuDXJ5ybDf_lN11H2mShk&amp;s',\n",
" 'thumbnailWidth': 275,\n",
" 'thumbnailHeight': 183,\n",
" 'source': 'National Geographic',\n",
" 'domain': 'www.nationalgeographic.com',\n",
" 'link': 'https://www.nationalgeographic.com/animals/mammals/facts/african-lion',\n",
" 'position': 3},\n",
" {'title': 'Saint Louis Zoo | African Lion',\n",
" 'imageUrl': 'https://optimise2.assets-servd.host/maniacal-finch/production/animals/african-lion-01-01.jpg?w=1200&auto=compress%2Cformat&fit=crop&dm=1658933674&s=4b63f926a0f524f2087a8e0613282bdb',\n",
" 'imageWidth': 1200,\n",
" 'imageHeight': 1200,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTlewcJ5SwC7yKup6ByaOjTnAFDeoOiMxyJTQaph2W_I3dnks4&amp;s',\n",
" 'thumbnailWidth': 225,\n",
" 'thumbnailHeight': 225,\n",
" 'source': 'St. Louis Zoo',\n",
" 'domain': 'stlzoo.org',\n",
" 'link': 'https://stlzoo.org/animals/mammals/carnivores/lion',\n",
" 'position': 4},\n",
" {'title': 'How to Draw a Realistic Lion like an Artist - Studio '\n",
" 'Wildlife',\n",
" 'imageUrl': 'https://studiowildlife.com/wp-content/uploads/2021/10/245528858_183911853822648_6669060845725210519_n.jpg',\n",
" 'imageWidth': 1431,\n",
" 'imageHeight': 2048,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTmn5HayVj3wqoBDQacnUtzaDPZzYHSLKUlIEcni6VB8w0mVeA&amp;s',\n",
" 'thumbnailWidth': 188,\n",
" 'thumbnailHeight': 269,\n",
" 'source': 'Studio Wildlife',\n",
" 'domain': 'studiowildlife.com',\n",
" 'link': 'https://studiowildlife.com/how-to-draw-a-realistic-lion-like-an-artist/',\n",
" 'position': 5},\n",
" {'title': 'Lion | Characteristics, Habitat, & Facts | Britannica',\n",
" 'imageUrl': 'https://cdn.britannica.com/29/150929-050-547070A1/lion-Kenya-Masai-Mara-National-Reserve.jpg',\n",
" 'imageWidth': 1600,\n",
" 'imageHeight': 1085,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSCqaKY_THr0IBZN8c-2VApnnbuvKmnsWjfrwKoWHFR9w3eN5o&amp;s',\n",
" 'thumbnailWidth': 273,\n",
" 'thumbnailHeight': 185,\n",
" 'source': 'Encyclopedia Britannica',\n",
" 'domain': 'www.britannica.com',\n",
" 'link': 'https://www.britannica.com/animal/lion',\n",
" 'position': 6},\n",
" {'title': \"Where do lions live? Facts about lions' habitats and \"\n",
" 'other cool facts',\n",
" 'imageUrl': 'https://www.gannett-cdn.com/-mm-/b2b05a4ab25f4fca0316459e1c7404c537a89702/c=0-0-1365-768/local/-/media/2022/03/16/USATODAY/usatsports/imageForEntry5-ODq.jpg?width=1365&height=768&fit=crop&format=pjpg&auto=webp',\n",
" 'imageWidth': 1365,\n",
" 'imageHeight': 768,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTc_4vCHscgvFvYy3PSrtIOE81kNLAfhDK8F3mfOuotL0kUkbs&amp;s',\n",
" 'thumbnailWidth': 299,\n",
" 'thumbnailHeight': 168,\n",
" 'source': 'USA Today',\n",
" 'domain': 'www.usatoday.com',\n",
" 'link': 'https://www.usatoday.com/story/news/2023/01/08/where-do-lions-live-habitat/10927718002/',\n",
" 'position': 7},\n",
" {'title': 'Lion',\n",
" 'imageUrl': 'https://i.natgeofe.com/k/1d33938b-3d02-4773-91e3-70b113c3b8c7/lion-male-roar_square.jpg',\n",
" 'imageWidth': 3072,\n",
" 'imageHeight': 3072,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQqLfnBrBLcTiyTZynHH3FGbBtX2bd1ScwpcuOLnksTyS9-4GM&amp;s',\n",
" 'thumbnailWidth': 225,\n",
" 'thumbnailHeight': 225,\n",
" 'source': 'National Geographic Kids',\n",
" 'domain': 'kids.nationalgeographic.com',\n",
" 'link': 'https://kids.nationalgeographic.com/animals/mammals/facts/lion',\n",
" 'position': 8},\n",
" {'title': \"Lion | Smithsonian's National Zoo\",\n",
" 'imageUrl': 'https://nationalzoo.si.edu/sites/default/files/styles/1400_scale/public/animals/exhibit/africanlion-005.jpg?itok=6wA745g_',\n",
" 'imageWidth': 1400,\n",
" 'imageHeight': 845,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgB3z_D4dMEOWJ7lajJk4XaQSL4DdUvIRj4UXZ0YoE5fGuWuo&amp;s',\n",
" 'thumbnailWidth': 289,\n",
" 'thumbnailHeight': 174,\n",
" 'source': \"Smithsonian's National Zoo\",\n",
" 'domain': 'nationalzoo.si.edu',\n",
" 'link': 'https://nationalzoo.si.edu/animals/lion',\n",
" 'position': 9},\n",
" {'title': \"Zoo's New Male Lion Explores Habitat for the First Time \"\n",
" '- Virginia Zoo',\n",
" 'imageUrl': 'https://virginiazoo.org/wp-content/uploads/2022/04/ZOO_0056-scaled.jpg',\n",
" 'imageWidth': 2560,\n",
" 'imageHeight': 2141,\n",
" 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDCG7XvXRCwpe_-Vy5mpvrQpVl5q2qwgnDklQhrJpQzObQGz4&amp;s',\n",
" 'thumbnailWidth': 246,\n",
" 'thumbnailHeight': 205,\n",
" 'source': 'Virginia Zoo',\n",
" 'domain': 'virginiazoo.org',\n",
" 'link': 'https://virginiazoo.org/zoos-new-male-lion-explores-habitat-for-thefirst-time/',\n",
" 'position': 10}]}\n"
]
}
],
"source": [
"search = GoogleSerperAPIWrapper(type=\"images\")\n",
"results = search.results(\"Lion\")\n",
"pprint.pp(results)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-05-04T00:54:27.879867Z",
"start_time": "2023-05-04T00:54:26.380022Z"
}
}
},
{
"cell_type": "markdown",
"source": [
"## Searching for Google News\n",
"We can also query Google News using this wrapper. For example:"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": 8,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'searchParameters': {'q': 'Tesla Inc.',\n",
" 'gl': 'us',\n",
" 'hl': 'en',\n",
" 'num': 10,\n",
" 'type': 'news'},\n",
" 'news': [{'title': 'ISS recommends Tesla investors vote against re-election '\n",
" 'of Robyn Denholm',\n",
" 'link': 'https://www.reuters.com/business/autos-transportation/iss-recommends-tesla-investors-vote-against-re-election-robyn-denholm-2023-05-04/',\n",
" 'snippet': 'Proxy advisory firm ISS on Wednesday recommended Tesla '\n",
" 'investors vote against re-election of board chair Robyn '\n",
" 'Denholm, citing \"concerns on...',\n",
" 'date': '5 mins ago',\n",
" 'source': 'Reuters',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcROdETe_GUyp1e8RHNhaRM8Z_vfxCvdfinZwzL1bT1ZGSYaGTeOojIdBoLevA&s',\n",
" 'position': 1},\n",
" {'title': 'Global companies by market cap: Tesla fell most in April',\n",
" 'link': 'https://www.reuters.com/markets/global-companies-by-market-cap-tesla-fell-most-april-2023-05-02/',\n",
" 'snippet': 'Tesla Inc was the biggest loser among top companies by '\n",
" 'market capitalisation in April, hit by disappointing '\n",
" 'quarterly earnings after it...',\n",
" 'date': '1 day ago',\n",
" 'source': 'Reuters',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ4u4CP8aOdGyRFH6o4PkXi-_eZDeY96vLSag5gDjhKMYf98YBER2cZPbkStQ&s',\n",
" 'position': 2},\n",
" {'title': 'Tesla Wanted an EV Price War. Ford Showed Up.',\n",
" 'link': 'https://www.bloomberg.com/opinion/articles/2023-05-03/tesla-wanted-an-ev-price-war-ford-showed-up',\n",
" 'snippet': 'The legacy automaker is paring back the cost of its '\n",
" 'Mustang Mach-E model after Tesla discounted its '\n",
" 'competing EVs, portending tighter...',\n",
" 'date': '6 hours ago',\n",
" 'source': 'Bloomberg.com',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_3Eo4VI0H-nTeIbYc5DaQn5ep7YrWnmhx6pv8XddFgNF5zRC9gEpHfDq8yQ&s',\n",
" 'position': 3},\n",
" {'title': 'Joby Aviation to get investment from Tesla shareholder '\n",
" 'Baillie Gifford',\n",
" 'link': 'https://finance.yahoo.com/news/joby-aviation-investment-tesla-shareholder-204450712.html',\n",
" 'snippet': 'This comes days after Joby clinched a $55 million '\n",
" 'contract extension to deliver up to nine air taxis to '\n",
" 'the U.S. Air Force,...',\n",
" 'date': '4 hours ago',\n",
" 'source': 'Yahoo Finance',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQO0uVn297LI-xryrPNqJ-apUOulj4ohM-xkN4OfmvMOYh1CPdUEBbYx6hviw&s',\n",
" 'position': 4},\n",
" {'title': 'Tesla resumes U.S. orders for a Model 3 version at lower '\n",
" 'price, range',\n",
" 'link': 'https://finance.yahoo.com/news/tesla-resumes-us-orders-model-045736115.html',\n",
" 'snippet': '(Reuters) -Tesla Inc has resumed taking orders for its '\n",
" 'Model 3 long-range vehicle in the United States, the '\n",
" \"company's website showed late on...\",\n",
" 'date': '19 hours ago',\n",
" 'source': 'Yahoo Finance',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTIZetJ62sQefPfbQ9KKDt6iH7Mc0ylT5t_hpgeeuUkHhJuAx2FOJ4ZTRVDFg&s',\n",
" 'position': 5},\n",
" {'title': 'The Tesla Model 3 Long Range AWD Is Now Available in the '\n",
" 'U.S. With 325 Miles of Range',\n",
" 'link': 'https://www.notateslaapp.com/news/1393/tesla-reopens-orders-for-model-3-long-range-after-months-of-unavailability',\n",
" 'snippet': 'Tesla has reopened orders for the Model 3 Long Range '\n",
" 'RWD, which has been unavailable for months due to high '\n",
" 'demand.',\n",
" 'date': '7 hours ago',\n",
" 'source': 'Not a Tesla App',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSecrgxZpRj18xIJY-nDHljyP-A4ejEkswa9eq77qhMNrScnVIqe34uql5U4w&s',\n",
" 'position': 6},\n",
" {'title': 'Tesla Cybertruck alpha prototype spotted at the Fremont '\n",
" 'factory in new pics and videos',\n",
" 'link': 'https://www.teslaoracle.com/2023/05/03/tesla-cybertruck-alpha-prototype-interior-and-exterior-spotted-at-the-fremont-factory-in-new-pics-and-videos/',\n",
" 'snippet': 'A Tesla Cybertruck alpha prototype goes to Fremont, '\n",
" 'California for another round of testing before going to '\n",
" 'production later this year (pics...',\n",
" 'date': '14 hours ago',\n",
" 'source': 'Tesla Oracle',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRO7M5ZLQE-Zo4-_5dv9hNAQZ3wSqfvYCuKqzxHG-M6CgLpwPMMG_ssebdcMg&s',\n",
" 'position': 7},\n",
" {'title': 'Tesla putting facility in new part of country - Austin '\n",
" 'Business Journal',\n",
" 'link': 'https://www.bizjournals.com/austin/news/2023/05/02/tesla-leases-building-seattle-area.html',\n",
" 'snippet': 'Check out what Puget Sound Business Journal has to '\n",
" \"report about the Austin-based company's real estate \"\n",
" 'footprint in the Pacific Northwest.',\n",
" 'date': '22 hours ago',\n",
" 'source': 'The Business Journals',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR9kIEHWz1FcHKDUtGQBS0AjmkqtyuBkQvD8kyIY3kpaPrgYaN7I_H2zoOJsA&s',\n",
" 'position': 8},\n",
" {'title': 'Tesla (TSLA) Resumes Orders for Model 3 Long Range After '\n",
" 'Backlog',\n",
" 'link': 'https://www.bloomberg.com/news/articles/2023-05-03/tesla-resumes-orders-for-popular-model-3-long-range-at-47-240',\n",
" 'snippet': 'Tesla Inc. has resumed taking orders for its Model 3 '\n",
" 'Long Range edition with a starting price of $47240, '\n",
" 'according to its website.',\n",
" 'date': '5 hours ago',\n",
" 'source': 'Bloomberg.com',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTWWIC4VpMTfRvSyqiomODOoLg0xhoBf-Tc1qweKnSuaiTk-Y1wMJZM3jct0w&s',\n",
" 'position': 9}]}\n"
]
}
],
"source": [
"search = GoogleSerperAPIWrapper(type=\"news\")\n",
"results = search.results(\"Tesla Inc.\")\n",
"pprint.pp(results)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-05-04T00:54:34.984087Z",
"start_time": "2023-05-04T00:54:33.369231Z"
}
}
},
{
"cell_type": "markdown",
"source": [
"If you want to only receive news articles published in the last hour, you can do the following:"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": 9,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'searchParameters': {'q': 'Tesla Inc.',\n",
" 'gl': 'us',\n",
" 'hl': 'en',\n",
" 'num': 10,\n",
" 'type': 'news',\n",
" 'tbs': 'qdr:h'},\n",
" 'news': [{'title': 'Oklahoma Gov. Stitt sees growing foreign interest in '\n",
" 'investments in ...',\n",
" 'link': 'https://www.reuters.com/world/us/oklahoma-gov-stitt-sees-growing-foreign-interest-investments-state-2023-05-04/',\n",
" 'snippet': 'T)), a battery supplier to electric vehicle maker Tesla '\n",
" 'Inc (TSLA.O), said on Sunday it is considering building '\n",
" 'a battery plant in Oklahoma, its third in...',\n",
" 'date': '53 mins ago',\n",
" 'source': 'Reuters',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSSTcsXeenqmEKdiekvUgAmqIPR4nlAmgjTkBqLpza-lLfjX1CwB84MoNVj0Q&s',\n",
" 'position': 1},\n",
" {'title': 'Ryder lanza solución llave en mano para vehículos '\n",
" 'eléctricos en EU',\n",
" 'link': 'https://www.tyt.com.mx/nota/ryder-lanza-solucion-llave-en-mano-para-vehiculos-electricos-en-eu',\n",
" 'snippet': 'Ryder System Inc. presentó RyderElectric+ TM como su '\n",
" 'nueva solución llave en mano ... Ryder también tiene '\n",
" 'reservados los semirremolques Tesla y continúa...',\n",
" 'date': '56 mins ago',\n",
" 'source': 'Revista Transportes y Turismo',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJhXTQQtjSUZf9YPM235WQhFU5_d7lEA76zB8DGwZfixcgf1_dhPJyKA1Nbw&s',\n",
" 'position': 2},\n",
" {'title': '\"I think people can get by with $999 million,\" Bernie '\n",
" 'Sanders tells American Billionaires.',\n",
" 'link': 'https://thebharatexpressnews.com/i-think-people-can-get-by-with-999-million-bernie-sanders-tells-american-billionaires-heres-how-the-ultra-rich-can-pay-less-income-tax-than-you-legally/',\n",
" 'snippet': 'The report noted that in 2007 and 2011, Amazon.com Inc. '\n",
" 'founder Jeff Bezos “did not pay a dime in federal ... '\n",
" 'If you want to bet on Musk, check out Tesla.',\n",
" 'date': '11 mins ago',\n",
" 'source': 'THE BHARAT EXPRESS NEWS',\n",
" 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_X9qqSwVFBBdos2CK5ky5IWIE3aJPCQeRYR9O1Jz4t-MjaEYBuwK7AU3AJQ&s',\n",
" 'position': 3}]}\n"
]
}
],
"source": [
"search = GoogleSerperAPIWrapper(type=\"news\", tbs=\"qdr:h\")\n",
"results = search.results(\"Tesla Inc.\")\n",
"pprint.pp(results)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-05-04T00:54:41.786864Z",
"start_time": "2023-05-04T00:54:40.691905Z"
}
}
},
{
"cell_type": "markdown",
"source": [
"Some examples of the `tbs` parameter:\n",
"\n",
"`qdr:h` (past hour)\n",
"`qdr:d` (past day)\n",
"`qdr:w` (past week)\n",
"`qdr:m` (past month)\n",
"`qdr:y` (past year)\n",
"\n",
"You can specify intermediate time periods by adding a number:\n",
"`qdr:h12` (past 12 hours)\n",
"`qdr:d3` (past 3 days)\n",
"`qdr:w2` (past 2 weeks)\n",
"`qdr:m6` (past 6 months)\n",
"`qdr:m2` (past 2 years)\n",
"\n",
"For all supported filters simply go to [Google Search](https://google.com), search for something, click on \"Tools\", add your date filter and check the URL for \"tbs=\".\n"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "markdown",
"source": [
"## Searching for Google Places\n",
"We can also query Google Places using this wrapper. For example:"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": 10,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'searchParameters': {'q': 'Italian restaurants in Upper East Side',\n",
" 'gl': 'us',\n",
" 'hl': 'en',\n",
" 'num': 10,\n",
" 'type': 'places'},\n",
" 'places': [{'position': 1,\n",
" 'title': \"L'Osteria\",\n",
" 'address': '1219 Lexington Ave',\n",
" 'latitude': 40.777154599999996,\n",
" 'longitude': -73.9571363,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNjU7BWEq_aYQANBCbX52Kb0lDpd_lFIx5onw40=w92-h92-n-k-no',\n",
" 'rating': 4.7,\n",
" 'ratingCount': 91,\n",
" 'category': 'Italian'},\n",
" {'position': 2,\n",
" 'title': \"Tony's Di Napoli\",\n",
" 'address': '1081 3rd Ave',\n",
" 'latitude': 40.7643567,\n",
" 'longitude': -73.9642373,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNbNv6jZkJ9nyVi60__8c1DQbe_eEbugRAhIYye=w92-h92-n-k-no',\n",
" 'rating': 4.5,\n",
" 'ratingCount': 2265,\n",
" 'category': 'Italian'},\n",
" {'position': 3,\n",
" 'title': 'Caravaggio',\n",
" 'address': '23 E 74th St',\n",
" 'latitude': 40.773412799999996,\n",
" 'longitude': -73.96473379999999,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPDGchokDvppoLfmVEo6X_bWd3Fz0HyxIHTEe9V=w92-h92-n-k-no',\n",
" 'rating': 4.5,\n",
" 'ratingCount': 276,\n",
" 'category': 'Italian'},\n",
" {'position': 4,\n",
" 'title': 'Luna Rossa',\n",
" 'address': '347 E 85th St',\n",
" 'latitude': 40.776593999999996,\n",
" 'longitude': -73.950351,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNPCpCPuqPAb1Mv6_fOP7cjb8Wu1rbqbk2sMBlh=w92-h92-n-k-no',\n",
" 'rating': 4.5,\n",
" 'ratingCount': 140,\n",
" 'category': 'Italian'},\n",
" {'position': 5,\n",
" 'title': \"Paola's\",\n",
" 'address': '1361 Lexington Ave',\n",
" 'latitude': 40.7822019,\n",
" 'longitude': -73.9534096,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPJr2Vcx-B6K-GNQa4koOTffggTePz8TKRTnWi3=w92-h92-n-k-no',\n",
" 'rating': 4.5,\n",
" 'ratingCount': 344,\n",
" 'category': 'Italian'},\n",
" {'position': 6,\n",
" 'title': 'Come Prima',\n",
" 'address': '903 Madison Ave',\n",
" 'latitude': 40.772124999999996,\n",
" 'longitude': -73.965012,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNrX19G0NVdtDyMovCQ-M-m0c_gLmIxrWDQAAbz=w92-h92-n-k-no',\n",
" 'rating': 4.5,\n",
" 'ratingCount': 176,\n",
" 'category': 'Italian'},\n",
" {'position': 7,\n",
" 'title': 'Botte UES',\n",
" 'address': '1606 1st Ave.',\n",
" 'latitude': 40.7750785,\n",
" 'longitude': -73.9504801,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPPN5GXxfH3NDacBc0Pt3uGAInd9OChS5isz9RF=w92-h92-n-k-no',\n",
" 'rating': 4.4,\n",
" 'ratingCount': 152,\n",
" 'category': 'Italian'},\n",
" {'position': 8,\n",
" 'title': 'Piccola Cucina Uptown',\n",
" 'address': '106 E 60th St',\n",
" 'latitude': 40.7632468,\n",
" 'longitude': -73.9689825,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPifIgzOCD5SjgzzqBzGkdZCBp0MQsK5k7M7znn=w92-h92-n-k-no',\n",
" 'rating': 4.6,\n",
" 'ratingCount': 941,\n",
" 'category': 'Italian'},\n",
" {'position': 9,\n",
" 'title': 'Pinocchio Restaurant',\n",
" 'address': '300 E 92nd St',\n",
" 'latitude': 40.781453299999995,\n",
" 'longitude': -73.9486788,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNtxlIyEEJHtDtFtTR9nB38S8A2VyMu-mVVz72A=w92-h92-n-k-no',\n",
" 'rating': 4.5,\n",
" 'ratingCount': 113,\n",
" 'category': 'Italian'},\n",
" {'position': 10,\n",
" 'title': 'Barbaresco',\n",
" 'address': '843 Lexington Ave #1',\n",
" 'latitude': 40.7654332,\n",
" 'longitude': -73.9656873,\n",
" 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipMb9FbPuXF_r9g5QseOHmReejxSHgSahPMPJ9-8=w92-h92-n-k-no',\n",
" 'rating': 4.3,\n",
" 'ratingCount': 122,\n",
" 'locationHint': 'In The Touraine',\n",
" 'category': 'Italian'}]}\n"
]
}
],
"source": [
"search = GoogleSerperAPIWrapper(type=\"places\")\n",
"results = search.results(\"Italian restaurants in Upper East Side\")\n",
"pprint.pp(results)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-05-04T00:56:07.271164Z",
"start_time": "2023-05-04T00:56:05.645847Z"
}
}
}
],
"metadata": {

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,102 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "40a27d3c-4e5c-4b96-b290-4c49d4fd7219",
"metadata": {},
"source": [
"## HuggingFace Tools\n",
"\n",
"[Huggingface Tools](https://huggingface.co/docs/transformers/v4.29.0/en/custom_tools) supporting text I/O can be\n",
"loaded directly using the `load_huggingface_tool` function."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d1055b75-362c-452a-b40d-c9a359706a3a",
"metadata": {},
"outputs": [],
"source": [
"# Requires transformers>=4.29.0 and huggingface_hub>=0.14.1\n",
"!pip install --uprade transformers huggingface_hub > /dev/null"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "f964bb45-fba3-4919-b022-70a602ed4354",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"model_download_counter: This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. It takes the name of the category (such as text-classification, depth-estimation, etc), and returns the name of the checkpoint\n"
]
}
],
"source": [
"from langchain.agents import load_huggingface_tool\n",
"\n",
"tool = load_huggingface_tool(\"lysandre/hf-model-downloads\")\n",
"\n",
"print(f\"{tool.name}: {tool.description}\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "641d9d79-95bb-469d-b40a-50f37375de7f",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"'facebook/bart-large-mnli'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tool.run(\"text-classification\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "88724222-7c10-4aff-8713-751911dc8b63",
"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.11.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -13,10 +13,11 @@
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import sys\n",
"from langchain.chat_models import ChatOpenAI\n",
"from langchain.llms import OpenAI\n",
"from langchain.agents import load_tools, initialize_agent\n",
@@ -42,13 +43,15 @@
"metadata": {},
"source": [
"In the above code you can see the tool takes input directly from command line.\n",
"You can customize `prompt_func` and `input_func` according to your need."
"You can customize `prompt_func` and `input_func` according to your need (as shown below)."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"execution_count": 2,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
@@ -57,29 +60,28 @@
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mI don't know Eric Zhu, so I should ask a human for guidance.\n",
"\u001b[32;1m\u001b[1;3mI don't know Eric's surname, so I should ask a human for guidance.\n",
"Action: Human\n",
"Action Input: \"Do you know when Eric Zhu's birthday is?\"\u001b[0m\n",
"Action Input: \"What is Eric's surname?\"\u001b[0m\n",
"\n",
"Do you know when Eric Zhu's birthday is?\n",
"last week\n",
"What is Eric's surname?\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
" Zhu\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Observation: \u001b[36;1m\u001b[1;3mlast week\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mThat's not very helpful. I should ask for more information.\n",
"Action: Human\n",
"Action Input: \"Do you know the specific date of Eric Zhu's birthday?\"\u001b[0m\n",
"\n",
"Do you know the specific date of Eric Zhu's birthday?\n",
"august 1st\n",
"\n",
"Observation: \u001b[36;1m\u001b[1;3maugust 1st\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mNow that I have the date, I can check if it's a leap year or not.\n",
"Action: Calculator\n",
"Action Input: \"Is 2021 a leap year?\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mAnswer: False\n",
"\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI have all the information I need to answer the original question.\n",
"Final Answer: Eric Zhu's birthday is on August 1st and it is not a leap year in 2021.\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mZhu\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI now know Eric's surname is Zhu.\n",
"Final Answer: Eric's surname is Zhu.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@@ -87,18 +89,175 @@
{
"data": {
"text/plain": [
"\"Eric Zhu's birthday is on August 1st and it is not a leap year in 2021.\""
"\"Eric's surname is Zhu.\""
]
},
"execution_count": 3,
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_chain.run(\"What's my friend Eric's surname?\")\n",
"# Answer with 'Zhu'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Configuring the Input Function\n",
"\n",
"agent_chain.run(\"What is Eric Zhu's birthday?\")\n",
"# Answer with \"last week\""
"By default, the `HumanInputRun` tool uses the python `input` function to get input from the user.\n",
"You can customize the input_func to be anything you'd like.\n",
"For instance, if you want to accept multi-line input, you could do the following:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def get_input() -> str:\n",
" print(\"Insert your text. Enter 'q' or press Ctrl-D (or Ctrl-Z on Windows) to end.\")\n",
" contents = []\n",
" while True:\n",
" try:\n",
" line = input()\n",
" except EOFError:\n",
" break\n",
" if line == \"q\":\n",
" break\n",
" contents.append(line)\n",
" return \"\\n\".join(contents)\n",
"\n",
"\n",
"# You can modify the tool when loading\n",
"tools = load_tools(\n",
" [\"human\", \"ddg-search\"], \n",
" llm=math_llm,\n",
" input_func=get_input\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Or you can directly instantiate the tool\n",
"from langchain.tools import HumanInputRun\n",
"\n",
"tool = HumanInputRun(input_func=get_input)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"agent_chain = initialize_agent(\n",
" tools,\n",
" llm,\n",
" agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n",
" verbose=True,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mI should ask a human for guidance\n",
"Action: Human\n",
"Action Input: \"Can you help me attribute a quote?\"\u001b[0m\n",
"\n",
"Can you help me attribute a quote?\n",
"Insert your text. Enter 'q' or press Ctrl-D (or Ctrl-Z on Windows) to end.\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
" vini\n",
" vidi\n",
" vici\n",
" q\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Observation: \u001b[36;1m\u001b[1;3mvini\n",
"vidi\n",
"vici\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI need to provide more context about the quote\n",
"Action: Human\n",
"Action Input: \"The quote is 'Veni, vidi, vici'\"\u001b[0m\n",
"\n",
"The quote is 'Veni, vidi, vici'\n",
"Insert your text. Enter 'q' or press Ctrl-D (or Ctrl-Z on Windows) to end.\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
" oh who said it \n",
" q\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Observation: \u001b[36;1m\u001b[1;3moh who said it \u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI can use DuckDuckGo Search to find out who said the quote\n",
"Action: DuckDuckGo Search\n",
"Action Input: \"Who said 'Veni, vidi, vici'?\"\u001b[0m\n",
"Observation: \u001b[33;1m\u001b[1;3mUpdated on September 06, 2019. \"Veni, vidi, vici\" is a famous phrase said to have been spoken by the Roman Emperor Julius Caesar (100-44 BCE) in a bit of stylish bragging that impressed many of the writers of his day and beyond. The phrase means roughly \"I came, I saw, I conquered\" and it could be pronounced approximately Vehnee, Veedee ... Veni, vidi, vici (Classical Latin: [weːniː wiːdiː wiːkiː], Ecclesiastical Latin: [ˈveni ˈvidi ˈvitʃi]; \"I came; I saw; I conquered\") is a Latin phrase used to refer to a swift, conclusive victory.The phrase is popularly attributed to Julius Caesar who, according to Appian, used the phrase in a letter to the Roman Senate around 47 BC after he had achieved a quick victory in his short ... veni, vidi, vici Latin quotation from Julius Caesar ve· ni, vi· di, vi· ci ˌwā-nē ˌwē-dē ˈwē-kē ˌvā-nē ˌvē-dē ˈvē-chē : I came, I saw, I conquered Articles Related to veni, vidi, vici 'In Vino Veritas' and Other Latin... Dictionary Entries Near veni, vidi, vici Venite veni, vidi, vici Venizélos See More Nearby Entries Cite this Entry Style The simplest explanation for why veni, vidi, vici is a popular saying is that it comes from Julius Caesar, one of history's most famous figures, and has a simple, strong meaning: I'm powerful and fast. But it's not just the meaning that makes the phrase so powerful. Caesar was a gifted writer, and the phrase makes use of Latin grammar to ... One of the best known and most frequently quoted Latin expression, veni, vidi, vici may be found hundreds of times throughout the centuries used as an expression of triumph. The words are said to have been used by Caesar as he was enjoying a triumph.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI now know the final answer\n",
"Final Answer: Julius Caesar said the quote \"Veni, vidi, vici\" which means \"I came, I saw, I conquered\".\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"'Julius Caesar said the quote \"Veni, vidi, vici\" which means \"I came, I saw, I conquered\".'"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_chain.run(\"I need help attributing a quote\")"
]
},
{
@@ -125,9 +284,9 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.1"
"version": "3.11.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
"nbformat_minor": 4
}

View File

@@ -0,0 +1,246 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Metaphor Search"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook goes over how to use Metaphor search.\n",
"\n",
"First, you need to set up the proper API keys and environment variables. Request an API key [here](Sign up for early access here).\n",
"\n",
"Then enter your API key as an environment variable."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"os.environ[\"METAPHOR_API_KEY\"] = \"\""
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from langchain.utilities import MetaphorSearchAPIWrapper"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"search = MetaphorSearchAPIWrapper()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Call the API\n",
"`results` takes in a Metaphor-optimized search query and a number of results (up to 500). It returns a list of results with title, url, author, and creation date."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'results': [{'url': 'https://www.anthropic.com/index/core-views-on-ai-safety', 'title': 'Core Views on AI Safety: When, Why, What, and How', 'dateCreated': '2023-03-08', 'author': None, 'score': 0.1998831331729889}, {'url': 'https://aisafety.wordpress.com/', 'title': 'Extinction Risk from Artificial Intelligence', 'dateCreated': '2013-10-08', 'author': None, 'score': 0.19801370799541473}, {'url': 'https://www.lesswrong.com/posts/WhNxG4r774bK32GcH/the-simple-picture-on-ai-safety', 'title': 'The simple picture on AI safety - LessWrong', 'dateCreated': '2018-05-27', 'author': 'Alex Flint', 'score': 0.19735534489154816}, {'url': 'https://slatestarcodex.com/2015/05/29/no-time-like-the-present-for-ai-safety-work/', 'title': 'No Time Like The Present For AI Safety Work', 'dateCreated': '2015-05-29', 'author': None, 'score': 0.19408763945102692}, {'url': 'https://www.lesswrong.com/posts/5BJvusxdwNXYQ4L9L/so-you-want-to-save-the-world', 'title': 'So You Want to Save the World - LessWrong', 'dateCreated': '2012-01-01', 'author': 'Lukeprog', 'score': 0.18853715062141418}, {'url': 'https://openai.com/blog/planning-for-agi-and-beyond', 'title': 'Planning for AGI and beyond', 'dateCreated': '2023-02-24', 'author': 'Authors', 'score': 0.18665121495723724}, {'url': 'https://waitbutwhy.com/2015/01/artificial-intelligence-revolution-1.html', 'title': 'The Artificial Intelligence Revolution: Part 1 - Wait But Why', 'dateCreated': '2015-01-22', 'author': 'Tim Urban', 'score': 0.18604731559753418}, {'url': 'https://forum.effectivealtruism.org/posts/uGDCaPFaPkuxAowmH/anthropic-core-views-on-ai-safety-when-why-what-and-how', 'title': 'Anthropic: Core Views on AI Safety: When, Why, What, and How - EA Forum', 'dateCreated': '2023-03-09', 'author': 'Jonmenaster', 'score': 0.18415069580078125}, {'url': 'https://www.lesswrong.com/posts/xBrpph9knzWdtMWeQ/the-proof-of-doom', 'title': 'The Proof of Doom - LessWrong', 'dateCreated': '2022-03-09', 'author': 'Johnlawrenceaspden', 'score': 0.18159329891204834}, {'url': 'https://intelligence.org/why-ai-safety/', 'title': 'Why AI Safety? - Machine Intelligence Research Institute', 'dateCreated': '2017-03-01', 'author': None, 'score': 0.1814115345478058}]}\n"
]
},
{
"data": {
"text/plain": [
"[{'title': 'Core Views on AI Safety: When, Why, What, and How',\n",
" 'url': 'https://www.anthropic.com/index/core-views-on-ai-safety',\n",
" 'author': None,\n",
" 'date_created': '2023-03-08'},\n",
" {'title': 'Extinction Risk from Artificial Intelligence',\n",
" 'url': 'https://aisafety.wordpress.com/',\n",
" 'author': None,\n",
" 'date_created': '2013-10-08'},\n",
" {'title': 'The simple picture on AI safety - LessWrong',\n",
" 'url': 'https://www.lesswrong.com/posts/WhNxG4r774bK32GcH/the-simple-picture-on-ai-safety',\n",
" 'author': 'Alex Flint',\n",
" 'date_created': '2018-05-27'},\n",
" {'title': 'No Time Like The Present For AI Safety Work',\n",
" 'url': 'https://slatestarcodex.com/2015/05/29/no-time-like-the-present-for-ai-safety-work/',\n",
" 'author': None,\n",
" 'date_created': '2015-05-29'},\n",
" {'title': 'So You Want to Save the World - LessWrong',\n",
" 'url': 'https://www.lesswrong.com/posts/5BJvusxdwNXYQ4L9L/so-you-want-to-save-the-world',\n",
" 'author': 'Lukeprog',\n",
" 'date_created': '2012-01-01'},\n",
" {'title': 'Planning for AGI and beyond',\n",
" 'url': 'https://openai.com/blog/planning-for-agi-and-beyond',\n",
" 'author': 'Authors',\n",
" 'date_created': '2023-02-24'},\n",
" {'title': 'The Artificial Intelligence Revolution: Part 1 - Wait But Why',\n",
" 'url': 'https://waitbutwhy.com/2015/01/artificial-intelligence-revolution-1.html',\n",
" 'author': 'Tim Urban',\n",
" 'date_created': '2015-01-22'},\n",
" {'title': 'Anthropic: Core Views on AI Safety: When, Why, What, and How - EA Forum',\n",
" 'url': 'https://forum.effectivealtruism.org/posts/uGDCaPFaPkuxAowmH/anthropic-core-views-on-ai-safety-when-why-what-and-how',\n",
" 'author': 'Jonmenaster',\n",
" 'date_created': '2023-03-09'},\n",
" {'title': 'The Proof of Doom - LessWrong',\n",
" 'url': 'https://www.lesswrong.com/posts/xBrpph9knzWdtMWeQ/the-proof-of-doom',\n",
" 'author': 'Johnlawrenceaspden',\n",
" 'date_created': '2022-03-09'},\n",
" {'title': 'Why AI Safety? - Machine Intelligence Research Institute',\n",
" 'url': 'https://intelligence.org/why-ai-safety/',\n",
" 'author': None,\n",
" 'date_created': '2017-03-01'}]"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"search.results(\"The best blog post about AI safety is definitely this: \", 10)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Use Metaphor as a tool\n",
"Metaphor can be used as a tool that gets URLs that other tools such as browsing tools."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents.agent_toolkits import PlayWrightBrowserToolkit\n",
"from langchain.tools.playwright.utils import (\n",
" create_async_playwright_browser,# A synchronous browser is available, though it isn't compatible with jupyter.\n",
")\n",
"\n",
"async_browser = create_async_playwright_browser()\n",
"toolkit = PlayWrightBrowserToolkit.from_browser(async_browser=async_browser)\n",
"tools = toolkit.get_tools()\n",
"\n",
"tools_by_name = {tool.name: tool for tool in tools}\n",
"print(tools_by_name.keys())\n",
"navigate_tool = tools_by_name[\"navigate_browser\"]\n",
"extract_text = tools_by_name[\"extract_text\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: I need to find a tweet about AI safety using Metaphor Search.\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"Metaphor Search Results JSON\",\n",
" \"action_input\": {\n",
" \"query\": \"interesting tweet AI safety\",\n",
" \"num_results\": 1\n",
" }\n",
"}\n",
"```\n",
"\u001b[0m{'results': [{'url': 'https://safe.ai/', 'title': 'Center for AI Safety', 'dateCreated': '2022-01-01', 'author': None, 'score': 0.18083244562149048}]}\n",
"\n",
"Observation: \u001b[36;1m\u001b[1;3m[{'title': 'Center for AI Safety', 'url': 'https://safe.ai/', 'author': None, 'date_created': '2022-01-01'}]\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI need to navigate to the URL provided in the search results to find the tweet.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"'I need to navigate to the URL provided in the search results to find the tweet.'"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from langchain.agents import initialize_agent, AgentType\n",
"from langchain.chat_models import ChatOpenAI\n",
"from langchain.tools import MetaphorSearchResults\n",
"\n",
"llm = ChatOpenAI(model_name=\"gpt-4\", temperature=0.7)\n",
"\n",
"metaphor_tool = MetaphorSearchResults(api_wrapper=search)\n",
"\n",
"agent_chain = initialize_agent([metaphor_tool, extract_text, navigate_tool], llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n",
"\n",
"agent_chain.run(\"find me an interesting tweet about AI safety using Metaphor, then tell me the first sentence in the post. Do not finish until able to retrieve the first sentence.\")"
]
},
{
"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.11.3"
},
"vscode": {
"interpreter": {
"hash": "a0a0263b650d907a3bfe41c0f8d6a63a071b884df3cfdc1579f00cdc1aed6b03"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -19,6 +19,7 @@
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import Tool\n",
"from langchain.utilities import PythonREPL"
]
},
@@ -59,7 +60,14 @@
"id": "54fc1f03",
"metadata": {},
"outputs": [],
"source": []
"source": [
"# You can create the tool to pass to an agent\n",
"repl_tool = Tool(\n",
" name=\"python_repl\",\n",
" description=\"A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.\",\n",
" func=python_repl.run\n",
")"
]
}
],
"metadata": {

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,139 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# SceneXplain\n",
"\n",
"\n",
"[SceneXplain](https://scenex.jina.ai/) is an ImageCaptioning service accessible through the SceneXplain Tool.\n",
"\n",
"To use this tool, you'll need to make an account and fetch your API Token [from the website](https://scenex.jina.ai/api). Then you can instantiate the tool."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"os.environ[\"SCENEX_API_KEY\"] = \"<YOUR_API_KEY>\""
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import load_tools\n",
"\n",
"tools = load_tools([\"sceneXplain\"])"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Or directly instantiate the tool."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from langchain.tools import SceneXplainTool\n",
"\n",
"\n",
"tool = SceneXplainTool()\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Usage in an Agent\n",
"\n",
"The tool can be used in any LangChain agent as follows:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m\n",
"Thought: Do I need to use a tool? Yes\n",
"Action: Image Explainer\n",
"Action Input: https://storage.googleapis.com/causal-diffusion.appspot.com/imagePrompts%2F0rw369i5h9t%2Foriginal.png\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mIn a charmingly whimsical scene, a young girl is seen braving the rain alongside her furry companion, the lovable Totoro. The two are depicted standing on a bustling street corner, where they are sheltered from the rain by a bright yellow umbrella. The girl, dressed in a cheerful yellow frock, holds onto the umbrella with both hands while gazing up at Totoro with an expression of wonder and delight.\n",
"\n",
"Totoro, meanwhile, stands tall and proud beside his young friend, holding his own umbrella aloft to protect them both from the downpour. His furry body is rendered in rich shades of grey and white, while his large ears and wide eyes lend him an endearing charm.\n",
"\n",
"In the background of the scene, a street sign can be seen jutting out from the pavement amidst a flurry of raindrops. A sign with Chinese characters adorns its surface, adding to the sense of cultural diversity and intrigue. Despite the dreary weather, there is an undeniable sense of joy and camaraderie in this heartwarming image.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m Do I need to use a tool? No\n",
"AI: This image appears to be a still from the 1988 Japanese animated fantasy film My Neighbor Totoro. The film follows two young girls, Satsuki and Mei, as they explore the countryside and befriend the magical forest spirits, including the titular character Totoro.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"This image appears to be a still from the 1988 Japanese animated fantasy film My Neighbor Totoro. The film follows two young girls, Satsuki and Mei, as they explore the countryside and befriend the magical forest spirits, including the titular character Totoro.\n"
]
}
],
"source": [
"from langchain.llms import OpenAI\n",
"from langchain.agents import initialize_agent\n",
"from langchain.memory import ConversationBufferMemory\n",
"\n",
"llm = OpenAI(temperature=0)\n",
"memory = ConversationBufferMemory(memory_key=\"chat_history\")\n",
"agent = initialize_agent(\n",
" tools, llm, memory=memory, agent=\"conversational-react-description\", verbose=True\n",
")\n",
"output = agent.run(\n",
" input=(\n",
" \"What is in this image https://storage.googleapis.com/causal-diffusion.appspot.com/imagePrompts%2F0rw369i5h9t%2Foriginal.png. \"\n",
" \"Is it movie or a game? If it is a movie, what is the name of the movie?\"\n",
" )\n",
")\n",
"\n",
"print(output)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.2"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -102,7 +102,15 @@
"id": "e0a1dc1c",
"metadata": {},
"outputs": [],
"source": []
"source": [
"from langchain.agents import Tool\n",
"# You can create the tool to pass to an agent\n",
"repl_tool = Tool(\n",
" name=\"python_repl\",\n",
" description=\"A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.\",\n",
" func=search.run,\n",
")"
]
}
],
"metadata": {

Some files were not shown because too many files have changed in this diff Show More